PageRenderTime 145ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Net/SFTP/Foreign.pm

https://github.com/gitpan/Net-SFTP-Foreign
Perl | 5539 lines | 5006 code | 464 blank | 69 comment | 381 complexity | 1e86b93b9d910ec891b45dadf0c17437 MD5 | raw file
Possible License(s): AGPL-1.0
  1. package Net::SFTP::Foreign;
  2. our $VERSION = '1.78_03';
  3. use strict;
  4. use warnings;
  5. use warnings::register;
  6. use Carp qw(carp croak);
  7. use Symbol ();
  8. use Errno ();
  9. use Fcntl;
  10. use File::Spec ();
  11. BEGIN {
  12. if ($] >= 5.008) {
  13. require Encode;
  14. }
  15. else {
  16. # Work around for incomplete Unicode handling in perl 5.6.x
  17. require bytes;
  18. bytes->import();
  19. *Encode::encode = sub { $_[1] };
  20. *Encode::decode = sub { $_[1] };
  21. *utf8::downgrade = sub { 1 };
  22. }
  23. }
  24. # we make $Net::SFTP::Foreign::Helpers::debug an alias for
  25. # $Net::SFTP::Foreign::debug so that the user can set it without
  26. # knowing anything about the Helpers package!
  27. our $debug;
  28. BEGIN { *Net::SFTP::Foreign::Helpers::debug = \$debug };
  29. use Net::SFTP::Foreign::Helpers qw(_is_reg _is_lnk _is_dir _debug
  30. _sort_entries _gen_wanted
  31. _gen_converter _hexdump
  32. _ensure_list _catch_tainted_args
  33. _file_part _umask_save_and_set);
  34. use Net::SFTP::Foreign::Constants qw( :fxp :flags :att
  35. :status :error
  36. SSH2_FILEXFER_VERSION );
  37. use Net::SFTP::Foreign::Attributes;
  38. use Net::SFTP::Foreign::Buffer;
  39. require Net::SFTP::Foreign::Common;
  40. our @ISA = qw(Net::SFTP::Foreign::Common);
  41. our $dirty_cleanup;
  42. my $windows;
  43. BEGIN {
  44. $windows = $^O =~ /Win(?:32|64)/;
  45. if ($^O =~ /solaris/i) {
  46. $dirty_cleanup = 1 unless defined $dirty_cleanup;
  47. }
  48. }
  49. sub _deprecated {
  50. if (warnings::enabled('deprecated') and warnings::enabled(__PACKAGE__)) {
  51. Carp::carp(join('', @_));
  52. }
  53. }
  54. sub _next_msg_id { shift->{_msg_id}++ }
  55. use constant _empty_attributes => Net::SFTP::Foreign::Attributes->new;
  56. sub _queue_new_msg {
  57. my $sftp = shift;
  58. my $code = shift;
  59. my $id = $sftp->_next_msg_id;
  60. my $msg = Net::SFTP::Foreign::Buffer->new(int8 => $code, int32 => $id, @_);
  61. $sftp->_queue_msg($msg);
  62. return $id;
  63. }
  64. sub _queue_msg {
  65. my ($sftp, $buf) = @_;
  66. my $bytes = $buf->bytes;
  67. my $len = length $bytes;
  68. if ($debug and $debug & 1) {
  69. $sftp->{_queued}++;
  70. _debug(sprintf("queueing msg len: %i, code:%i, id:%i ... [$sftp->{_queued}]",
  71. $len, unpack(CN => $bytes)));
  72. $debug & 16 and _hexdump(pack('N', length($bytes)) . $bytes);
  73. }
  74. $sftp->{_bout} .= pack('N', length($bytes));
  75. $sftp->{_bout} .= $bytes;
  76. }
  77. sub _do_io { $_[0]->{_backend}->_do_io(@_) }
  78. sub _conn_lost {
  79. my ($sftp, $status, $err, @str) = @_;
  80. $debug and $debug & 32 and _debug("_conn_lost");
  81. $sftp->{_status} or
  82. $sftp->_set_status(defined $status ? $status : SSH2_FX_CONNECTION_LOST);
  83. $sftp->{_error} or
  84. $sftp->_set_error((defined $err ? $err : SFTP_ERR_CONNECTION_BROKEN),
  85. (@str ? @str : "Connection to remote server is broken"));
  86. undef $sftp->{_connected};
  87. }
  88. sub _conn_failed {
  89. my $sftp = shift;
  90. $sftp->_conn_lost(SSH2_FX_NO_CONNECTION,
  91. SFTP_ERR_CONNECTION_BROKEN,
  92. @_)
  93. unless $sftp->{_error};
  94. }
  95. sub _get_msg {
  96. my $sftp = shift;
  97. $debug and $debug & 1 and _debug("waiting for message... [$sftp->{_queued}]");
  98. unless ($sftp->_do_io($sftp->{_timeout})) {
  99. $sftp->_conn_lost(undef, undef, "Connection to remote server stalled");
  100. return undef;
  101. }
  102. my $bin = \$sftp->{_bin};
  103. my $len = unpack N => substr($$bin, 0, 4, '');
  104. my $msg = Net::SFTP::Foreign::Buffer->make(substr($$bin, 0, $len, ''));
  105. if ($debug and $debug & 1) {
  106. $sftp->{_queued}--;
  107. my ($code, $id, $status) = unpack( CNN => $$msg);
  108. $id = '-' if $code == SSH2_FXP_VERSION;
  109. $status = '-' unless $code == SSH2_FXP_STATUS;
  110. _debug(sprintf("got it!, len:%i, code:%i, id:%s, status: %s",
  111. $len, $code, $id, $status));
  112. $debug & 8 and _hexdump($$msg);
  113. }
  114. return $msg;
  115. }
  116. sub _croak_bad_options {
  117. if (@_) {
  118. my $s = (@_ > 1 ? 's' : '');
  119. croak "Invalid option$s '" . CORE::join("', '", @_) . "' or bad combination of options";
  120. }
  121. }
  122. sub _fs_encode {
  123. my ($sftp, $path) = @_;
  124. Encode::encode($sftp->{_fs_encoding}, $path);
  125. }
  126. sub _fs_decode {
  127. my ($sftp, $path) = @_;
  128. Encode::decode($sftp->{_fs_encoding}, $path);
  129. }
  130. sub new {
  131. ${^TAINT} and &_catch_tainted_args;
  132. my $class = shift;
  133. unshift @_, 'host' if @_ & 1;
  134. my %opts = @_;
  135. my $sftp = { _msg_id => 0,
  136. _bout => '',
  137. _bin => '',
  138. _connected => 1,
  139. _queued => 0,
  140. _error => 0,
  141. _status => 0 };
  142. bless $sftp, $class;
  143. if ($debug) {
  144. _debug "This is Net::SFTP::Foreign $Net::SFTP::Foreign::VERSION";
  145. _debug "Loaded from $INC{'Net/SFTP/Foreign.pm'}";
  146. _debug "Running on Perl $^V for $^O";
  147. _debug "debug set to $debug";
  148. _debug "~0 is " . ~0;
  149. }
  150. $sftp->_clear_error_and_status;
  151. my $backend = delete $opts{backend};
  152. unless (ref $backend) {
  153. $backend = ($windows ? 'Windows' : 'Unix')
  154. unless (defined $backend);
  155. $backend =~ /^\w+$/
  156. or croak "Bad backend name $backend";
  157. my $backend_class = "Net::SFTP::Foreign::Backend::$backend";
  158. eval "require $backend_class; 1"
  159. or croak "Unable to load backend $backend: $@";
  160. $backend = $backend_class->_new($sftp, \%opts);
  161. }
  162. $sftp->{_backend} = $backend;
  163. if ($debug) {
  164. my $class = ref($backend) || $backend;
  165. no strict 'refs';
  166. my $version = ${$class .'::VERSION'} || 0;
  167. _debug "Using backend $class $version";
  168. }
  169. my %defs = $backend->_defaults;
  170. $sftp->{_autodie} = delete $opts{autodie};
  171. $sftp->{_block_size} = delete $opts{block_size} || $defs{block_size} || 32*1024;
  172. $sftp->{_min_block_size} = delete $opts{min_block_size} || $defs{min_block_size} || 512;
  173. $sftp->{_queue_size} = delete $opts{queue_size} || $defs{queue_size} || 32;
  174. $sftp->{_read_ahead} = $defs{read_ahead} || $sftp->{_block_size} * 4;
  175. $sftp->{_write_delay} = $defs{write_delay} || $sftp->{_block_size} * 8;
  176. $sftp->{_autoflush} = delete $opts{autoflush};
  177. $sftp->{_late_set_perm} = delete $opts{late_set_perm};
  178. $sftp->{_dirty_cleanup} = delete $opts{dirty_cleanup};
  179. $sftp->{_timeout} = delete $opts{timeout};
  180. defined $sftp->{_timeout} and $sftp->{_timeout} <= 0 and croak "invalid timeout";
  181. $sftp->{_fs_encoding} = delete $opts{fs_encoding};
  182. if (defined $sftp->{_fs_encoding}) {
  183. $] < 5.008
  184. and carp "fs_encoding feature is not supported in this perl version $]";
  185. }
  186. else {
  187. $sftp->{_fs_encoding} = 'utf8';
  188. }
  189. $sftp->autodisconnect(delete $opts{autodisconnect});
  190. $backend->_init_transport($sftp, \%opts);
  191. %opts and _croak_bad_options(keys %opts);
  192. $sftp->_init unless $sftp->{_error};
  193. $backend->_after_init($sftp);
  194. $sftp
  195. }
  196. sub autodisconnect {
  197. my ($sftp, $ad) = @_;
  198. if (defined $ad and $ad != 1) {
  199. if ($ad == 0) {
  200. $sftp->{_disconnect_by_pid} = -1;
  201. }
  202. elsif ($ad == 2) {
  203. $sftp->{_disconnect_by_pid} = $$;
  204. }
  205. else {
  206. croak "bad value '$ad' for autodisconnect";
  207. }
  208. }
  209. 1;
  210. }
  211. sub disconnect {
  212. my $sftp = shift;
  213. my $pid = delete $sftp->{pid};
  214. $debug and $debug & 4 and _debug("$sftp->disconnect called (ssh pid: ".($pid||'').")");
  215. local $sftp->{_autodie};
  216. $sftp->_conn_lost;
  217. if (defined $pid) {
  218. close $sftp->{ssh_out} if (defined $sftp->{ssh_out} and not $sftp->{_ssh_out_is_not_dupped});
  219. close $sftp->{ssh_in} if defined $sftp->{ssh_in};
  220. if ($windows) {
  221. kill KILL => $pid
  222. and waitpid($pid, 0);
  223. $debug and $debug & 4 and _debug "process $pid reaped";
  224. }
  225. else {
  226. my $dirty = ( defined $sftp->{_dirty_cleanup}
  227. ? $sftp->{_dirty_cleanup}
  228. : $dirty_cleanup );
  229. if ($dirty or not defined $dirty) {
  230. $debug and $debug & 4 and _debug("starting dirty cleanup of process $pid");
  231. for my $sig (($dirty ? () : 0), qw(TERM TERM KILL KILL)) {
  232. $debug and $debug & 4 and _debug("killing process $pid with signal $sig");
  233. $sig and kill $sig, $pid;
  234. local ($@, $SIG{__DIE__}, $SIG{__WARN__});
  235. my $wpr;
  236. eval {
  237. local $SIG{ALRM} = sub { die "timeout\n" };
  238. alarm 8;
  239. $wpr = waitpid($pid, 0);
  240. alarm 0;
  241. };
  242. $debug and $debug & 4 and _debug("waitpid returned " . (defined $wpr ? $wpr : '<undef>'));
  243. if ($wpr) {
  244. # $wpr > 0 ==> the process has ben reaped
  245. # $wpr < 0 ==> some error happened, retry unless ECHILD
  246. last if $wpr > 0 or $! == Errno::ECHILD();
  247. }
  248. }
  249. }
  250. else {
  251. while (1) {
  252. last if waitpid($pid, 0) > 0;
  253. if ($! != Errno::EINTR) {
  254. warn "internal error: unexpected error in waitpid($pid): $!"
  255. if $! != Errno::ECHILD;
  256. last;
  257. }
  258. }
  259. }
  260. $debug and $debug & 4 and _debug "process $pid reaped";
  261. }
  262. }
  263. close $sftp->{_pty} if defined $sftp->{_pty};
  264. 1
  265. }
  266. sub DESTROY {
  267. local ($?, $!, $@);
  268. my $sftp = shift;
  269. my $dbpid = $sftp->{_disconnect_by_pid};
  270. $debug and $debug & 4 and _debug("$sftp->DESTROY called (current pid: $$, disconnect_by_pid: ".($dbpid||'').")");
  271. $sftp->disconnect if (!defined $dbpid or $dbpid == $$);
  272. }
  273. sub _init {
  274. my $sftp = shift;
  275. $sftp->_queue_msg( Net::SFTP::Foreign::Buffer->new(int8 => SSH2_FXP_INIT,
  276. int32 => SSH2_FILEXFER_VERSION));
  277. if (my $msg = $sftp->_get_msg) {
  278. my $type = $msg->get_int8;
  279. if ($type == SSH2_FXP_VERSION) {
  280. my $version = $msg->get_int32;
  281. $sftp->{server_version} = $version;
  282. $sftp->{server_extensions} = {};
  283. while (length $$msg) {
  284. my $key = $msg->get_str;
  285. my $value = $msg->get_str;
  286. $sftp->{server_extensions}{$key} = $value;
  287. if ($key eq 'vendor-id') {
  288. my $vid = Net::SFTP::Foreign::Buffer->make("$value");
  289. $sftp->{_ext__vendor_id} = [ Encode::decode(utf8 => $vid->get_str),
  290. Encode::decode(utf8 => $vid->get_str),
  291. Encode::decode(utf8 => $vid->get_str),
  292. $vid->get_int64 ];
  293. }
  294. elsif ($key eq 'supported2') {
  295. my $s2 = Net::SFTP::Foreign::Buffer->make("$value");
  296. $sftp->{_ext__supported2} = [ $s2->get_int32,
  297. $s2->get_int32,
  298. $s2->get_int32,
  299. $s2->get_int32,
  300. $s2->get_int32,
  301. $s2->get_int16,
  302. $s2->get_int16,
  303. [map Encode::decode(utf8 => $_), $s2->get_str_list],
  304. [map Encode::decode(utf8 => $_), $s2->get_str_list] ];
  305. }
  306. }
  307. return $version;
  308. }
  309. $sftp->_conn_lost(SSH2_FX_BAD_MESSAGE,
  310. SFTP_ERR_REMOTE_BAD_MESSAGE,
  311. "bad packet type, expecting SSH2_FXP_VERSION, got $type");
  312. }
  313. elsif ($sftp->{_status} == SSH2_FX_CONNECTION_LOST
  314. and $sftp->{_password_authentication}
  315. and $sftp->{_password_sent}) {
  316. $sftp->_set_error(SFTP_ERR_PASSWORD_AUTHENTICATION_FAILED,
  317. "Password authentication failed or connection lost");
  318. }
  319. return undef;
  320. }
  321. sub server_extensions { %{shift->{server_extensions}} }
  322. sub _check_extension {
  323. my ($sftp, $name, $version, $error, $errstr) = @_;
  324. my $ext = $sftp->{server_extensions}{$name};
  325. return 1 if (defined $ext and $ext == $version);
  326. $sftp->_set_status(SSH2_FX_OP_UNSUPPORTED);
  327. $sftp->_set_error($error, "$errstr: extended operation not supported by server");
  328. return undef;
  329. }
  330. # helper methods:
  331. sub _get_msg_and_check {
  332. my ($sftp, $etype, $eid, $err, $errstr) = @_;
  333. my $msg = $sftp->_get_msg;
  334. if ($msg) {
  335. my $type = $msg->get_int8;
  336. my $id = $msg->get_int32;
  337. $sftp->_clear_error_and_status;
  338. if ($id != $eid) {
  339. $sftp->_conn_lost(SSH2_FX_BAD_MESSAGE,
  340. SFTP_ERR_REMOTE_BAD_MESSAGE,
  341. $errstr, "bad packet sequence, expected $eid, got $id");
  342. return undef;
  343. }
  344. if ($type != $etype) {
  345. if ($type == SSH2_FXP_STATUS) {
  346. my $code = $msg->get_int32;
  347. my $str = Encode::decode(utf8 => $msg->get_str);
  348. my $status = $sftp->_set_status($code, (defined $str ? $str : ()));
  349. $sftp->_set_error($err, $errstr, $status);
  350. }
  351. else {
  352. $sftp->_conn_lost(SSH2_FX_BAD_MESSAGE,
  353. SFTP_ERR_REMOTE_BAD_MESSAGE,
  354. $errstr, "bad packet type, expected $etype packet, got $type");
  355. }
  356. return undef;
  357. }
  358. }
  359. $msg;
  360. }
  361. # reads SSH2_FXP_HANDLE packet and returns handle, or undef on failure
  362. sub _get_handle {
  363. my ($sftp, $eid, $error, $errstr) = @_;
  364. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_HANDLE, $eid,
  365. $error, $errstr)) {
  366. return $msg->get_str;
  367. }
  368. return undef;
  369. }
  370. sub _rid {
  371. my ($sftp, $rfh) = @_;
  372. my $rid = $rfh->_rid;
  373. unless (defined $rid) {
  374. $sftp->_set_error(SFTP_ERR_REMOTE_ACCESING_CLOSED_FILE,
  375. "Couldn't access a file that has been previosly closed");
  376. }
  377. $rid
  378. }
  379. sub _rfid {
  380. $_[1]->_check_is_file;
  381. &_rid;
  382. }
  383. sub _rdid {
  384. $_[1]->_check_is_dir;
  385. &_rid;
  386. }
  387. sub _queue_rid_request {
  388. my ($sftp, $code, $fh, $attrs) = @_;
  389. my $rid = $sftp->_rid($fh);
  390. return undef unless defined $rid;
  391. $sftp->_queue_new_msg($code, str => $rid,
  392. (defined $attrs ? (attr => $attrs) : ()));
  393. }
  394. sub _queue_rfid_request {
  395. $_[2]->_check_is_file;
  396. &_queue_rid_request;
  397. }
  398. sub _queue_rdid_request {
  399. $_[2]->_check_is_dir;
  400. &_queue_rid_request;
  401. }
  402. sub _queue_str_request {
  403. my($sftp, $code, $str, $attrs) = @_;
  404. $sftp->_queue_new_msg($code, str => $str,
  405. (defined $attrs ? (attr => $attrs) : ()));
  406. }
  407. sub _check_status_ok {
  408. my ($sftp, $eid, $error, $errstr) = @_;
  409. if (defined $eid) {
  410. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_STATUS, $eid,
  411. $error, $errstr)) {
  412. my $status = $sftp->_set_status($msg->get_int32, $msg->get_str);
  413. return 1 if $status == SSH2_FX_OK;
  414. $sftp->_set_error($error, $errstr, $status);
  415. }
  416. }
  417. return undef;
  418. }
  419. sub setcwd {
  420. ${^TAINT} and &_catch_tainted_args;
  421. my ($sftp, $cwd, %opts) = @_;
  422. $sftp->_clear_error_and_status;
  423. my $check = delete $opts{check};
  424. $check = 1 unless defined $check;
  425. %opts and _croak_bad_options(keys %opts);
  426. if (defined $cwd) {
  427. if ($check) {
  428. $cwd = $sftp->realpath($cwd);
  429. return undef unless defined $cwd;
  430. my $a = $sftp->stat($cwd)
  431. or return undef;
  432. unless (_is_dir($a->perm)) {
  433. $sftp->_set_error(SFTP_ERR_REMOTE_BAD_OBJECT,
  434. "Remote object '$cwd' is not a directory");
  435. return undef;
  436. }
  437. }
  438. else {
  439. $cwd = $sftp->_rel2abs($cwd);
  440. }
  441. return $sftp->{cwd} = $cwd;
  442. }
  443. else {
  444. delete $sftp->{cwd};
  445. return $sftp->cwd if defined wantarray;
  446. }
  447. }
  448. sub cwd {
  449. @_ == 1 or croak 'Usage: $sftp->cwd()';
  450. my $sftp = shift;
  451. return defined $sftp->{cwd} ? $sftp->{cwd} : $sftp->realpath('');
  452. }
  453. ## SSH2_FXP_OPEN (3)
  454. # returns handle on success, undef on failure
  455. sub open {
  456. (@_ >= 2 and @_ <= 4)
  457. or croak 'Usage: $sftp->open($path [, $flags [, $attrs]])';
  458. ${^TAINT} and &_catch_tainted_args;
  459. my ($sftp, $path, $flags, $a) = @_;
  460. $path = $sftp->_rel2abs($path);
  461. defined $flags or $flags = SSH2_FXF_READ;
  462. defined $a or $a = Net::SFTP::Foreign::Attributes->new;
  463. my $id = $sftp->_queue_new_msg(SSH2_FXP_OPEN,
  464. str => $sftp->_fs_encode($path),
  465. int32 => $flags, attr => $a);
  466. my $rid = $sftp->_get_handle($id,
  467. SFTP_ERR_REMOTE_OPEN_FAILED,
  468. "Couldn't open remote file '$path'");
  469. if ($debug and $debug & 2) {
  470. if (defined $rid) {
  471. _debug("new remote file '$path' open, rid:");
  472. _hexdump($rid);
  473. }
  474. else {
  475. _debug("open failed: $sftp->{_status}");
  476. }
  477. }
  478. defined $rid or return undef;
  479. my $fh = Net::SFTP::Foreign::FileHandle->_new_from_rid($sftp, $rid);
  480. $fh->_flag(append => 1) if ($flags & SSH2_FXF_APPEND);
  481. $fh;
  482. }
  483. sub _open_mkpath {
  484. my ($sftp, $filename, $mkpath, $flags, $attrs) = @_;
  485. $flags = ($flags || 0) | SSH2_FXF_WRITE|SSH2_FXF_CREAT;
  486. my $fh = do {
  487. local $sftp->{_autodie};
  488. $sftp->open($filename, $flags, $attrs);
  489. };
  490. unless ($fh) {
  491. if ($mkpath and $sftp->status == SSH2_FX_NO_SUCH_FILE) {
  492. my $da = $attrs->clone;
  493. $da->set_perm(($da->perm || 0) | 0700);
  494. $sftp->mkpath($filename, $da, 1) or return;
  495. $fh = $sftp->open($filename, $flags, $attrs);
  496. }
  497. else {
  498. $sftp->_ok_or_autodie;
  499. }
  500. }
  501. $fh;
  502. }
  503. ## SSH2_FXP_OPENDIR (11)
  504. sub opendir {
  505. @_ == 2 or croak 'Usage: $sftp->opendir($path)';
  506. ${^TAINT} and &_catch_tainted_args;
  507. my $sftp = shift;
  508. my $path = shift;
  509. $path = $sftp->_rel2abs($path);
  510. my $id = $sftp->_queue_str_request(SSH2_FXP_OPENDIR, $sftp->_fs_encode($path), @_);
  511. my $rid = $sftp->_get_handle($id, SFTP_ERR_REMOTE_OPENDIR_FAILED,
  512. "Couldn't open remote dir '$path'");
  513. if ($debug and $debug & 2) {
  514. _debug("new remote dir '$path' open, rid:");
  515. _hexdump($rid);
  516. }
  517. defined $rid
  518. or return undef;
  519. Net::SFTP::Foreign::DirHandle->_new_from_rid($sftp, $rid, 0)
  520. }
  521. ## SSH2_FXP_READ (4)
  522. # returns data on success undef on failure
  523. sub sftpread {
  524. (@_ >= 3 and @_ <= 4)
  525. or croak 'Usage: $sftp->sftpread($fh, $offset [, $size])';
  526. my ($sftp, $rfh, $offset, $size) = @_;
  527. unless ($size) {
  528. return '' if defined $size;
  529. $size = $sftp->{_block_size};
  530. }
  531. my $rfid = $sftp->_rfid($rfh);
  532. defined $rfid or return undef;
  533. my $id = $sftp->_queue_new_msg(SSH2_FXP_READ, str=> $rfid,
  534. int64 => $offset, int32 => $size);
  535. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_DATA, $id,
  536. SFTP_ERR_REMOTE_READ_FAILED,
  537. "Couldn't read from remote file")) {
  538. return $msg->get_str;
  539. }
  540. return undef;
  541. }
  542. ## SSH2_FXP_WRITE (6)
  543. # returns true on success, undef on failure
  544. sub sftpwrite {
  545. @_ == 4 or croak 'Usage: $sftp->sftpwrite($fh, $offset, $data)';
  546. my ($sftp, $rfh, $offset) = @_;
  547. my $rfid = $sftp->_rfid($rfh);
  548. defined $rfid or return undef;
  549. utf8::downgrade($_[3], 1) or croak "wide characters found in data";
  550. my $id = $sftp->_queue_new_msg(SSH2_FXP_WRITE, str => $rfid,
  551. int64 => $offset, str => $_[3]);
  552. if ($sftp->_check_status_ok($id,
  553. SFTP_ERR_REMOTE_WRITE_FAILED,
  554. "Couldn't write to remote file")) {
  555. return 1;
  556. }
  557. return undef;
  558. }
  559. sub seek {
  560. (@_ >= 3 and @_ <= 4)
  561. or croak 'Usage: $sftp->seek($fh, $pos [, $whence])';
  562. my ($sftp, $rfh, $pos, $whence) = @_;
  563. $sftp->flush($rfh) or return undef;
  564. if (!$whence) {
  565. $rfh->_pos($pos)
  566. }
  567. elsif ($whence == 1) {
  568. $rfh->_inc_pos($pos)
  569. }
  570. elsif ($whence == 2) {
  571. my $a = $sftp->stat($rfh) or return undef;
  572. $rfh->_pos($pos + $a->size);
  573. }
  574. else {
  575. croak "invalid value for whence argument ('$whence')";
  576. }
  577. 1;
  578. }
  579. sub tell {
  580. @_ == 2 or croak 'Usage: $sftp->tell($fh)';
  581. my ($sftp, $rfh) = @_;
  582. return $rfh->_pos + length ${$rfh->_bout};
  583. }
  584. sub eof {
  585. @_ == 2 or croak 'Usage: $sftp->eof($fh)';
  586. my ($sftp, $rfh) = @_;
  587. $sftp->_fill_read_cache($rfh, 1);
  588. return length(${$rfh->_bin}) == 0
  589. }
  590. sub _write {
  591. my ($sftp, $rfh, $off, $cb) = @_;
  592. $sftp->_clear_error_and_status;
  593. my $rfid = $sftp->_rfid($rfh);
  594. defined $rfid or return undef;
  595. my $qsize = $sftp->{_queue_size};
  596. my @msgid;
  597. my @written;
  598. my $written = 0;
  599. my $end;
  600. while (!$end or @msgid) {
  601. while (!$end and @msgid < $qsize) {
  602. my $data = $cb->();
  603. if (defined $data and length $data) {
  604. my $id = $sftp->_queue_new_msg(SSH2_FXP_WRITE, str => $rfid,
  605. int64 => $off + $written, str => $data);
  606. push @written, $written;
  607. $written += length $data;
  608. push @msgid, $id;
  609. }
  610. else {
  611. $end = 1;
  612. }
  613. }
  614. my $eid = shift @msgid;
  615. my $last = shift @written;
  616. unless ($sftp->_check_status_ok($eid,
  617. SFTP_ERR_REMOTE_WRITE_FAILED,
  618. "Couldn't write to remote file")) {
  619. # discard responses to queued requests:
  620. $sftp->_get_msg for @msgid;
  621. return $last;
  622. }
  623. }
  624. return $written;
  625. }
  626. sub write {
  627. @_ == 3 or croak 'Usage: $sftp->write($fh, $data)';
  628. my ($sftp, $rfh) = @_;
  629. $sftp->flush($rfh, 'in') or return undef;
  630. utf8::downgrade($_[2], 1) or croak "wide characters found in data";
  631. my $datalen = length $_[2];
  632. my $bout = $rfh->_bout;
  633. $$bout .= $_[2];
  634. my $len = length $$bout;
  635. $sftp->flush($rfh, 'out')
  636. if ($len >= $sftp->{_write_delay} or ($len and $sftp->{_autoflush} ));
  637. return $datalen;
  638. }
  639. sub flush {
  640. (@_ >= 2 and @_ <= 3)
  641. or croak 'Usage: $sftp->flush($fh [, $direction])';
  642. my ($sftp, $rfh, $dir) = @_;
  643. $dir ||= '';
  644. if ($dir ne 'out') { # flush in!
  645. ${$rfh->_bin} = '';
  646. }
  647. if ($dir ne 'in') { # flush out!
  648. my $bout = $rfh->_bout;
  649. my $len = length $$bout;
  650. if ($len) {
  651. my $start;
  652. my $append = $rfh->_flag('append');
  653. if ($append) {
  654. my $attr = $sftp->stat($rfh)
  655. or return undef;
  656. $start = $attr->size;
  657. }
  658. else {
  659. $start = $rfh->_pos;
  660. ${$rfh->_bin} = '';
  661. }
  662. my $off = 0;
  663. my $written = $sftp->_write($rfh, $start,
  664. sub {
  665. my $data = substr($$bout, $off, $sftp->{_block_size});
  666. $off += length $data;
  667. $data;
  668. } );
  669. $rfh->_inc_pos($written)
  670. unless $append;
  671. substr($$bout, 0, $written, '');
  672. $written == $len or return undef;
  673. }
  674. }
  675. 1;
  676. }
  677. sub _fill_read_cache {
  678. my ($sftp, $rfh, $len) = @_;
  679. $sftp->_clear_error_and_status;
  680. $sftp->flush($rfh, 'out')
  681. or return undef;
  682. my $rfid = $sftp->_rfid($rfh);
  683. defined $rfid or return undef;
  684. my $bin = $rfh->_bin;
  685. if (defined $len) {
  686. return 1 if ($len < length $$bin);
  687. my $read_ahead = $sftp->{_read_ahead};
  688. $len = length($$bin) + $read_ahead
  689. if $len - length($$bin) < $read_ahead;
  690. }
  691. my $pos = $rfh->_pos;
  692. my $qsize = $sftp->{_queue_size};
  693. my $bsize = $sftp->{_block_size};
  694. my @msgid;
  695. my $askoff = length $$bin;
  696. my $eof;
  697. while (!defined $len or length $$bin < $len) {
  698. while ((!defined $len or $askoff < $len) and @msgid < $qsize) {
  699. my $id = $sftp->_queue_new_msg(SSH2_FXP_READ, str=> $rfid,
  700. int64 => $pos + $askoff, int32 => $bsize);
  701. push @msgid, $id;
  702. $askoff += $bsize;
  703. }
  704. my $eid = shift @msgid;
  705. my $msg = $sftp->_get_msg_and_check(SSH2_FXP_DATA, $eid,
  706. SFTP_ERR_REMOTE_READ_FAILED,
  707. "Couldn't read from remote file")
  708. or last;
  709. my $data = $msg->get_str;
  710. $$bin .= $data;
  711. if (length $data < $bsize) {
  712. unless (defined $len) {
  713. $eof = $sftp->_queue_new_msg(SSH2_FXP_READ, str=> $rfid,
  714. int64 => $pos + length $$bin, int32 => 1);
  715. }
  716. last;
  717. }
  718. }
  719. $sftp->_get_msg for @msgid;
  720. if ($eof) {
  721. $sftp->_get_msg_and_check(SSH2_FXP_DATA, $eof,
  722. SFTP_ERR_REMOTE_BLOCK_TOO_SMALL,
  723. "received block was too small")
  724. }
  725. if ($sftp->{_status} == SSH2_FX_EOF and length $$bin) {
  726. $sftp->_clear_error_and_status;
  727. }
  728. return $sftp->{_error} ? undef : length $$bin;
  729. }
  730. sub read {
  731. @_ == 3 or croak 'Usage: $sftp->read($fh, $len)';
  732. my ($sftp, $rfh, $len) = @_;
  733. if ($sftp->_fill_read_cache($rfh, $len)) {
  734. my $bin = $rfh->_bin;
  735. my $data = substr($$bin, 0, $len, '');
  736. $rfh->_inc_pos(length $data);
  737. return $data;
  738. }
  739. return undef;
  740. }
  741. sub _readline {
  742. my ($sftp, $rfh, $sep) = @_;
  743. $sep = "\n" if @_ < 3;
  744. my $sl = length $sep;
  745. my $bin = $rfh->_bin;
  746. my $last = 0;
  747. while(1) {
  748. my $ix = index $$bin, $sep, $last + 1 - $sl ;
  749. if ($ix >= 0) {
  750. $ix += $sl;
  751. $rfh->_inc_pos($ix);
  752. return substr($$bin, 0, $ix, '');
  753. }
  754. $last = length $$bin;
  755. $sftp->_fill_read_cache($rfh, length($$bin) + 1);
  756. unless (length $$bin > $last) {
  757. $sftp->{_error}
  758. and return undef;
  759. my $line = $$bin;
  760. $rfh->_inc_pos(length $line);
  761. $$bin = '';
  762. return $line;
  763. }
  764. }
  765. }
  766. sub readline {
  767. (@_ >= 2 and @_ <= 3)
  768. or croak 'Usage: $sftp->readline($fh [, $sep])';
  769. my ($sftp, $rfh, $sep) = @_;
  770. $sep = "\n" if @_ < 3;
  771. if (!defined $sep or $sep eq '') {
  772. $sftp->_fill_read_cache($rfh);
  773. $sftp->{_error}
  774. and return undef;
  775. my $bin = $rfh->_bin;
  776. my $line = $$bin;
  777. $rfh->_inc_pos(length $line);
  778. $$bin = '';
  779. return $line;
  780. }
  781. if (wantarray) {
  782. my @lines;
  783. while (defined (my $line = $sftp->_readline($rfh, $sep))) {
  784. push @lines, $line;
  785. }
  786. return @lines;
  787. }
  788. return $sftp->_readline($rfh, $sep);
  789. }
  790. sub getc {
  791. @_ == 2 or croak 'Usage: $sftp->getc($fh)';
  792. my ($sftp, $rfh) = @_;
  793. $sftp->_fill_read_cache($rfh, 1);
  794. my $bin = $rfh->_bin;
  795. if (length $bin) {
  796. $rfh->_inc_pos(1);
  797. return substr $$bin, 0, 1, '';
  798. }
  799. return undef;
  800. }
  801. ## SSH2_FXP_LSTAT (7), SSH2_FXP_FSTAT (8), SSH2_FXP_STAT (17)
  802. # these all return a Net::SFTP::Foreign::Attributes object on success, undef on failure
  803. sub lstat {
  804. @_ <= 2 or croak 'Usage: $sftp->lstat($path)';
  805. ${^TAINT} and &_catch_tainted_args;
  806. my ($sftp, $path) = @_;
  807. $path = '.' unless defined $path;
  808. $path = $sftp->_rel2abs($path);
  809. my $id = $sftp->_queue_str_request(SSH2_FXP_LSTAT, $sftp->_fs_encode($path));
  810. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_ATTRS, $id,
  811. SFTP_ERR_REMOTE_LSTAT_FAILED, "Couldn't stat remote link")) {
  812. return $msg->get_attributes;
  813. }
  814. return undef;
  815. }
  816. sub stat {
  817. @_ <= 2 or croak 'Usage: $sftp->stat($path_or_fh)';
  818. ${^TAINT} and &_catch_tainted_args;
  819. my ($sftp, $pofh) = @_;
  820. $pofh = '.' unless defined $pofh;
  821. my $id = $sftp->_queue_new_msg( (ref $pofh and UNIVERSAL::isa($pofh, 'Net::SFTP::Foreign::FileHandle'))
  822. ? ( SSH2_FXP_FSTAT, str => $sftp->_rid($pofh))
  823. : ( SSH2_FXP_STAT, str => $sftp->_fs_encode($sftp->_rel2abs($pofh))) );
  824. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_ATTRS, $id,
  825. SFTP_ERR_REMOTE_STAT_FAILED, "Couldn't stat remote file")) {
  826. return $msg->get_attributes;
  827. }
  828. return undef;
  829. }
  830. sub fstat {
  831. _deprecated "fstat is deprecated and will be removed on the upcomming 2.xx series, "
  832. . "stat method accepts now both file handlers and paths";
  833. goto &stat;
  834. }
  835. ## SSH2_FXP_RMDIR (15), SSH2_FXP_REMOVE (13)
  836. # these return true on success, undef on failure
  837. sub _gen_remove_method {
  838. my($name, $code, $error, $errstr) = @_;
  839. my $sub = sub {
  840. @_ == 2 or croak "Usage: \$sftp->$name(\$path)";
  841. ${^TAINT} and &_catch_tainted_args;
  842. my ($sftp, $path) = @_;
  843. $path = $sftp->_rel2abs($path);
  844. my $id = $sftp->_queue_str_request($code, $sftp->_fs_encode($path));
  845. $sftp->_check_status_ok($id, $error, $errstr);
  846. };
  847. no strict 'refs';
  848. *$name = $sub;
  849. }
  850. _gen_remove_method(remove => SSH2_FXP_REMOVE,
  851. SFTP_ERR_REMOTE_REMOVE_FAILED, "Couldn't delete remote file");
  852. _gen_remove_method(rmdir => SSH2_FXP_RMDIR,
  853. SFTP_ERR_REMOTE_RMDIR_FAILED, "Couldn't remove remote directory");
  854. ## SSH2_FXP_MKDIR (14), SSH2_FXP_SETSTAT (9)
  855. # these return true on success, undef on failure
  856. sub mkdir {
  857. (@_ >= 2 and @_ <= 3)
  858. or croak 'Usage: $sftp->mkdir($path [, $attrs])';
  859. ${^TAINT} and &_catch_tainted_args;
  860. my ($sftp, $path, $attrs) = @_;
  861. $attrs = _empty_attributes unless defined $attrs;
  862. $path = $sftp->_rel2abs($path);
  863. my $id = $sftp->_queue_str_request(SSH2_FXP_MKDIR,
  864. $sftp->_fs_encode($path),
  865. $attrs);
  866. $sftp->_check_status_ok($id,
  867. SFTP_ERR_REMOTE_MKDIR_FAILED,
  868. "Couldn't create remote directory");
  869. }
  870. sub join {
  871. my $sftp = shift;
  872. my $a = '.';
  873. while (@_) {
  874. my $b = shift;
  875. if (defined $b) {
  876. $b =~ s|^(?:\./+)+||;
  877. if (length $b and $b ne '.') {
  878. if ($b !~ m|^/| and $a ne '.' ) {
  879. $a = ($a =~ m|/$| ? "$a$b" : "$a/$b");
  880. }
  881. else {
  882. $a = $b
  883. }
  884. $a =~ s|(?:/+\.)+/?$|/|;
  885. $a =~ s|(?<=[^/])/+$||;
  886. $a = '.' unless length $a;
  887. }
  888. }
  889. }
  890. $a;
  891. }
  892. sub _rel2abs {
  893. my ($sftp, $path) = @_;
  894. my $old = $path;
  895. my $cwd = $sftp->{cwd};
  896. $path = $sftp->join($sftp->{cwd}, $path);
  897. $debug and $debug & 4096 and _debug("'$old' --> '$path'");
  898. return $path
  899. }
  900. sub mkpath {
  901. (@_ >= 2 and @_ <= 4)
  902. or croak 'Usage: $sftp->mkpath($path [, $attrs [, $parent]])';
  903. ${^TAINT} and &_catch_tainted_args;
  904. my ($sftp, $path, $attrs, $parent) = @_;
  905. $sftp->_clear_error_and_status;
  906. my $first = !$parent; # skips file name
  907. $path =~ s{^(/*)}{};
  908. my $start = $1;
  909. $path =~ s{/+$}{};
  910. my @path;
  911. while (1) {
  912. if ($first) {
  913. $first = 0
  914. }
  915. else {
  916. $path =~ s{/*[^/]*$}{}
  917. }
  918. my $p = "$start$path";
  919. $debug and $debug & 8192 and _debug "checking $p";
  920. if ($sftp->test_d($p)) {
  921. $debug and $debug & 8192 and _debug "$p is a dir";
  922. last;
  923. }
  924. unless (length $path) {
  925. $sftp->_set_error(SFTP_ERR_REMOTE_MKDIR_FAILED,
  926. "Unable to make path, bad root");
  927. return undef;
  928. }
  929. unshift @path, $p;
  930. }
  931. for my $p (@path) {
  932. $debug and $debug & 8192 and _debug "mkdir $p";
  933. if ($p =~ m{^(?:.*/)?\.{1,2}$} or $p =~ m{/$}) {
  934. $debug and $debug & 8192 and _debug "$p is a symbolic dir, skipping";
  935. unless ($sftp->test_d($p)) {
  936. $debug and $debug & 8192 and _debug "symbolic dir $p can not be checked";
  937. $sftp->{_error} or
  938. $sftp->_set_error(SFTP_ERR_REMOTE_MKDIR_FAILED,
  939. "Unable to make path, bad name");
  940. return undef;
  941. }
  942. }
  943. else {
  944. $sftp->mkdir($p, $attrs)
  945. or return undef;
  946. }
  947. }
  948. 1;
  949. }
  950. sub _mkpath_local {
  951. my ($sftp, $path, $perm, $parent) = @_;
  952. my @parts = File::Spec->splitdir($path);
  953. my @tail;
  954. if ($debug and $debug & 32768) {
  955. my $target = File::Spec->join(@parts);
  956. _debug "_mkpath_local('$target')";
  957. }
  958. if ($parent) {
  959. pop @parts while @parts and not length $parts[-1];
  960. @parts or goto top_dir_reached;
  961. pop @parts;
  962. }
  963. while (1) {
  964. my $target = File::Spec->join(@parts);
  965. $target = '' unless defined $target;
  966. if (-e $target) {
  967. if (-d $target) {
  968. while (@tail) {
  969. $target = File::Spec->join($target, shift(@tail));
  970. $debug and $debug and 32768 and _debug "creating local directory $target";
  971. unless (CORE::mkdir $target, $perm) {
  972. unless (do { local $!; -d $target}) {
  973. $sftp->_set_error(SFTP_ERR_LOCAL_MKDIR_FAILED,
  974. "mkdir '$target' failed", $!);
  975. return;
  976. }
  977. }
  978. }
  979. return 1;
  980. }
  981. else {
  982. $sftp->_set_error(SFTP_ERR_LOCAL_BAD_OBJECT,
  983. "Local file '$target' is not a directory");
  984. return;
  985. }
  986. }
  987. @parts or last;
  988. unshift @tail, pop @parts;
  989. }
  990. top_dir_reached:
  991. $sftp->_set_error(SFTP_ERR_LOCAL_MKDIR_FAILED,
  992. "mkpath failed, top dir reached");
  993. return;
  994. }
  995. sub setstat {
  996. @_ == 3 or croak 'Usage: $sftp->setstat($path_or_fh, $attrs)';
  997. ${^TAINT} and &_catch_tainted_args;
  998. my ($sftp, $pofh, $attrs) = @_;
  999. my $id = $sftp->_queue_new_msg( ( (ref $pofh and UNIVERSAL::isa($pofh, 'Net::SFTP::Foreign::FileHandle') )
  1000. ? ( SSH2_FXP_FSETSTAT, str => $sftp->_rid($pofh) )
  1001. : ( SSH2_FXP_SETSTAT, str => $sftp->_fs_encode($sftp->_rel2abs($pofh)) ) ),
  1002. attr => $attrs );
  1003. return $sftp->_check_status_ok($id,
  1004. SFTP_ERR_REMOTE_SETSTAT_FAILED,
  1005. "Couldn't setstat remote file");
  1006. }
  1007. ## SSH2_FXP_CLOSE (4), SSH2_FXP_FSETSTAT (10)
  1008. # these return true on success, undef on failure
  1009. sub fsetstat {
  1010. _deprecated "fsetstat is deprecated and will be removed on the upcomming 2.xx series, "
  1011. . "setstat method accepts now both file handlers and paths";
  1012. goto &setstat;
  1013. }
  1014. sub _gen_setstat_shortcut {
  1015. my ($name, $rid_type, $attrs_flag, @arg_types) = @_;
  1016. my $nargs = 2 + @arg_types;
  1017. my $usage = ("\$sftp->$name("
  1018. . CORE::join(', ', '$path_or_fh', map "arg$_", 1..@arg_types)
  1019. . ')');
  1020. my $rid_method = ($rid_type eq 'file' ? '_rfid' :
  1021. $rid_type eq 'dir' ? '_rdid' :
  1022. $rid_type eq 'any' ? '_rid' :
  1023. croak "bad rid type $rid_type");
  1024. my $sub = sub {
  1025. @_ == $nargs or croak $usage;
  1026. my $sftp = shift;
  1027. my $pofh = shift;
  1028. my $id = $sftp->_queue_new_msg( ( (ref $pofh and UNIVERSAL::isa($pofh, 'Net::SFTP::Foreign::FileHandle') )
  1029. ? ( SSH2_FXP_FSETSTAT, str => $sftp->$rid_method($pofh) )
  1030. : ( SSH2_FXP_SETSTAT, str => $sftp->_fs_encode($sftp->_rel2abs($pofh)) ) ),
  1031. int32 => $attrs_flag,
  1032. map { $arg_types[$_] => $_[$_] } 0..$#arg_types );
  1033. $sftp->_check_status_ok($id,
  1034. SFTP_ERR_REMOTE_SETSTAT_FAILED,
  1035. "Couldn't setstat remote file ($name)");
  1036. };
  1037. no strict 'refs';
  1038. *$name = $sub;
  1039. }
  1040. _gen_setstat_shortcut(truncate => 'file', SSH2_FILEXFER_ATTR_SIZE, 'int64');
  1041. _gen_setstat_shortcut(chown => 'any' , SSH2_FILEXFER_ATTR_UIDGID, 'int32', 'int32');
  1042. _gen_setstat_shortcut(chmod => 'any' , SSH2_FILEXFER_ATTR_PERMISSIONS, 'int32');
  1043. _gen_setstat_shortcut(utime => 'any' , SSH2_FILEXFER_ATTR_ACMODTIME, 'int32', 'int32');
  1044. sub _close {
  1045. @_ == 2 or croak 'Usage: $sftp->close($fh, $attrs)';
  1046. my $sftp = shift;
  1047. my $id = $sftp->_queue_rid_request(SSH2_FXP_CLOSE, @_);
  1048. defined $id or return undef;
  1049. my $ok = $sftp->_check_status_ok($id,
  1050. SFTP_ERR_REMOTE_CLOSE_FAILED,
  1051. "Couldn't close remote file");
  1052. if ($debug and $debug & 2) {
  1053. _debug sprintf("closing file handle, return: %s, rid:", (defined $ok ? $ok : '-'));
  1054. _hexdump($sftp->_rid($_[0]));
  1055. }
  1056. return $ok;
  1057. }
  1058. sub close {
  1059. @_ == 2 or croak 'Usage: $sftp->close($fh)';
  1060. my ($sftp, $rfh) = @_;
  1061. $rfh->_check_is_file;
  1062. $sftp->flush($rfh)
  1063. or return undef;
  1064. if ($sftp->_close($rfh)) {
  1065. $rfh->_close;
  1066. return 1
  1067. }
  1068. undef
  1069. }
  1070. sub closedir {
  1071. @_ == 2 or croak 'Usage: $sftp->closedir($dh)';
  1072. ${^TAINT} and &_catch_tainted_args;
  1073. my ($sftp, $rdh) = @_;
  1074. $rdh->_check_is_dir;
  1075. if ($sftp->_close($rdh)) {
  1076. $rdh->_close;
  1077. return 1;
  1078. }
  1079. undef
  1080. }
  1081. sub readdir {
  1082. @_ == 2 or croak 'Usage: $sftp->readdir($dh)';
  1083. ${^TAINT} and &_catch_tainted_args;
  1084. my ($sftp, $rdh) = @_;
  1085. my $rdid = $sftp->_rdid($rdh);
  1086. defined $rdid or return undef;
  1087. my $cache = $rdh->_cache;
  1088. while (!@$cache or wantarray) {
  1089. my $id = $sftp->_queue_str_request(SSH2_FXP_READDIR, $rdid);
  1090. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_NAME, $id,
  1091. SFTP_ERR_REMOTE_READDIR_FAILED,
  1092. "Couldn't read remote directory" )) {
  1093. my $count = $msg->get_int32 or last;
  1094. for (1..$count) {
  1095. push @$cache, { filename => $sftp->_fs_decode($msg->get_str),
  1096. longname => $sftp->_fs_decode($msg->get_str),
  1097. a => $msg->get_attributes };
  1098. }
  1099. }
  1100. else {
  1101. $sftp->_set_error if $sftp->{_status} == SSH2_FX_EOF;
  1102. last;
  1103. }
  1104. }
  1105. if (wantarray) {
  1106. my $old = $cache;
  1107. $cache = [];
  1108. return @$old;
  1109. }
  1110. shift @$cache;
  1111. }
  1112. sub _readdir {
  1113. my ($sftp, $rdh);
  1114. if (wantarray) {
  1115. my $line = $sftp->readdir($rdh);
  1116. if (defined $line) {
  1117. return $line->{filename};
  1118. }
  1119. }
  1120. else {
  1121. return map { $_->{filename} } $sftp->readdir($rdh);
  1122. }
  1123. }
  1124. sub _gen_getpath_method {
  1125. my ($code, $error, $name) = @_;
  1126. return sub {
  1127. @_ == 2 or croak 'Usage: $sftp->some_method($path)';
  1128. ${^TAINT} and &_catch_tainted_args;
  1129. my ($sftp, $path) = @_;
  1130. $path = $sftp->_rel2abs($path);
  1131. my $id = $sftp->_queue_str_request($code, $sftp->_fs_encode($path));
  1132. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_NAME, $id,
  1133. $error,
  1134. "Couldn't get $name for remote '$path'")) {
  1135. $msg->get_int32 > 0
  1136. and return $sftp->_fs_decode($msg->get_str);
  1137. $sftp->_set_error($error,
  1138. "Couldn't get $name for remote '$path', no names on reply")
  1139. }
  1140. return undef;
  1141. };
  1142. }
  1143. ## SSH2_FXP_REALPATH (16)
  1144. ## SSH2_FXP_READLINK (19)
  1145. # return path on success, undef on failure
  1146. *realpath = _gen_getpath_method(SSH2_FXP_REALPATH,
  1147. SFTP_ERR_REMOTE_REALPATH_FAILED,
  1148. "realpath");
  1149. *readlink = _gen_getpath_method(SSH2_FXP_READLINK,
  1150. SFTP_ERR_REMOTE_READLINK_FAILED,
  1151. "link target");
  1152. ## SSH2_FXP_RENAME (18)
  1153. # true on success, undef on failure
  1154. sub _rename {
  1155. my ($sftp, $old, $new) = @_;
  1156. $old = $sftp->_rel2abs($old);
  1157. $new = $sftp->_rel2abs($new);
  1158. my $id = $sftp->_queue_new_msg(SSH2_FXP_RENAME,
  1159. str => $sftp->_fs_encode($old),
  1160. str => $sftp->_fs_encode($new));
  1161. $sftp->_check_status_ok($id, SFTP_ERR_REMOTE_RENAME_FAILED,
  1162. "Couldn't rename remote file '$old' to '$new'");
  1163. }
  1164. sub rename {
  1165. (@_ & 1) or croak 'Usage: $sftp->rename($old, $new, %opts)';
  1166. ${^TAINT} and &_catch_tainted_args;
  1167. my ($sftp, $old, $new, %opts) = @_;
  1168. my $overwrite = delete $opts{overwrite};
  1169. my $numbered = delete $opts{numbered};
  1170. croak "'overwrite' and 'numbered' options can not be used together"
  1171. if ($overwrite and $numbered);
  1172. %opts and _croak_bad_options(keys %opts);
  1173. if ($overwrite) {
  1174. $sftp->atomic_rename($old, $new) and return 1;
  1175. $sftp->{_status} != SSH2_FX_OP_UNSUPPORTED and return undef;
  1176. }
  1177. for (1) {
  1178. local $sftp->{_autodie};
  1179. # we are optimistic here and try to rename it without testing
  1180. # if a file of the same name already exists first
  1181. if (!$sftp->_rename($old, $new) and
  1182. $sftp->{_status} == SSH2_FX_FAILURE) {
  1183. if ($numbered and $sftp->test_e($new)) {
  1184. _inc_numbered($new);
  1185. redo;
  1186. }
  1187. elsif ($overwrite) {
  1188. my $rp_old = $sftp->realpath($old);
  1189. my $rp_new = $sftp->realpath($new);
  1190. if (defined $rp_old and defined $rp_new and $rp_old eq $rp_new) {
  1191. $sftp->_clear_error_and_status;
  1192. }
  1193. elsif ($sftp->remove($new)) {
  1194. $overwrite = 0;
  1195. redo;
  1196. }
  1197. }
  1198. }
  1199. }
  1200. $sftp->_ok_or_autodie;
  1201. }
  1202. sub atomic_rename {
  1203. @_ == 3 or croak 'Usage: $sftp->atomic_rename($old, $new)';
  1204. ${^TAINT} and &_catch_tainted_args;
  1205. my ($sftp, $old, $new) = @_;
  1206. $sftp->_check_extension('posix-rename@openssh.com' => 1,
  1207. SFTP_ERR_REMOTE_RENAME_FAILED,
  1208. "atomic rename failed")
  1209. or return undef;
  1210. $old = $sftp->_rel2abs($old);
  1211. $new = $sftp->_rel2abs($new);
  1212. my $id = $sftp->_queue_new_msg(SSH2_FXP_EXTENDED,
  1213. str => 'posix-rename@openssh.com',
  1214. str => $sftp->_fs_encode($old),
  1215. str => $sftp->_fs_encode($new));
  1216. $sftp->_check_status_ok($id, SFTP_ERR_REMOTE_RENAME_FAILED,
  1217. "Couldn't rename remote file '$old' to '$new'");
  1218. }
  1219. ## SSH2_FXP_SYMLINK (20)
  1220. # true on success, undef on failure
  1221. sub symlink {
  1222. @_ == 3 or croak 'Usage: $sftp->symlink($sl, $target)';
  1223. ${^TAINT} and &_catch_tainted_args;
  1224. my ($sftp, $sl, $target) = @_;
  1225. $sl = $sftp->_rel2abs($sl);
  1226. my $id = $sftp->_queue_new_msg(SSH2_FXP_SYMLINK,
  1227. str => $sftp->_fs_encode($target),
  1228. str => $sftp->_fs_encode($sl));
  1229. $sftp->_check_status_ok($id, SFTP_ERR_REMOTE_SYMLINK_FAILED,
  1230. "Couldn't create symlink '$sl' pointing to '$target'");
  1231. }
  1232. sub hardlink {
  1233. @_ == 3 or croak 'Usage: $sftp->hardlink($hl, $target)';
  1234. ${^TAINT} and &_catch_tainted_args;
  1235. my ($sftp, $hl, $target) = @_;
  1236. $sftp->_check_extension('hardlink@openssh.com' => 1,
  1237. SFTP_ERR_REMOTE_HARDLINK_FAILED,
  1238. "hardlink failed")
  1239. or return undef;
  1240. $hl = $sftp->_rel2abs($hl);
  1241. $target = $sftp->_rel2abs($target);
  1242. my $id = $sftp->_queue_new_msg(SSH2_FXP_EXTENDED,
  1243. str => 'hardlink@openssh.com',
  1244. str => $sftp->_fs_encode($target),
  1245. str => $sftp->_fs_encode($hl));
  1246. $sftp->_check_status_ok($id, SFTP_ERR_REMOTE_HARDLINK_FAILED,
  1247. "Couldn't create hardlink '$hl' pointing to '$target'");
  1248. }
  1249. sub _gen_save_status_method {
  1250. my $method = shift;
  1251. sub {
  1252. my $sftp = shift;
  1253. local ($sftp->{_error}, $sftp->{_status}) if $sftp->{_error};
  1254. $sftp->$method(@_);
  1255. }
  1256. }
  1257. *_close_save_status = _gen_save_status_method('close');
  1258. *_closedir_save_status = _gen_save_status_method('closedir');
  1259. *_remove_save_status = _gen_save_status_method('remove');
  1260. sub _inc_numbered {
  1261. $_[0] =~ s{^(.*)\((\d+)\)((?:\.[^\.]*)?)$}{"$1(" . ($2+1) . ")$3"}e or
  1262. $_[0] =~ s{((?:\.[^\.]*)?)$}{(1)$1};
  1263. $debug and $debug & 128 and _debug("numbering to: $_[0]");
  1264. }
  1265. ## High-level client -> server methods.
  1266. sub abort {
  1267. my $sftp = shift;
  1268. $sftp->_set_error(SFTP_ERR_ABORTED, ($@ ? $_[0] : "Aborted"));
  1269. }
  1270. # returns true on success, undef on failure
  1271. sub get {
  1272. @_ >= 2 or croak 'Usage: $sftp->get($remote, $local, %opts)';
  1273. ${^TAINT} and &_catch_tainted_args;
  1274. my ($sftp, $remote, $local, %opts) = @_;
  1275. defined $remote or croak "remote file path is undefined";
  1276. $sftp->_clear_error_and_status;
  1277. $remote = $sftp->_rel2abs($remote);
  1278. $local = _file_part($remote) unless defined $local;
  1279. my $local_is_fh = (ref $local and $local->isa('GLOB'));
  1280. my $cb = delete $opts{callback};
  1281. my $umask = delete $opts{umask};
  1282. my $perm = delete $opts{perm};
  1283. my $copy_perm = delete $opts{exists $opts{copy_perm} ? 'copy_perm' : 'copy_perms'};
  1284. my $copy_time = delete $opts{copy_time};
  1285. my $overwrite = delete $opts{overwrite};
  1286. my $resume = delete $opts{resume};
  1287. my $append = delete $opts{append};
  1288. my $block_size = delete $opts{block_size} || $sftp->{_block_size};
  1289. my $queue_size = delete $opts{queue_size} || $sftp->{_queue_size};
  1290. my $dont_save = delete $opts{dont_save};
  1291. my $conversion = delete $opts{conversion};
  1292. my $numbered = delete $opts{numbered};
  1293. my $cleanup = delete $opts{cleanup};
  1294. my $atomic = delete $opts{atomic};
  1295. my $best_effort = delete $opts{best_effort};
  1296. my $mkpath = delete $opts{mkpath};
  1297. croak "'perm' and 'copy_perm' options can not be used simultaneously"
  1298. if (defined $perm and defined $copy_perm);
  1299. croak "'resume' and 'append' options can not be used simultaneously"
  1300. if ($resume and $append);
  1301. croak "'numbered' can not be used with 'overwrite', 'resume' or 'append'"
  1302. if ($numbered and ($overwrite or $resume or $append));
  1303. croak "'atomic' can not be used with 'resume' or 'append'"
  1304. if ($atomic and ($resume or $append));
  1305. if ($local_is_fh) {
  1306. my $append = 'option can not be used when target is a file handle';
  1307. $resume and croak "'resume' $append";
  1308. $overwrite and croak "'overwrite' $append";
  1309. $numbered and croak "'numbered' $append";
  1310. $dont_save and croak "'dont_save' $append";
  1311. $atomic and croak "'croak' $append";
  1312. }
  1313. %opts and _croak_bad_options(keys %opts);
  1314. if ($resume and $conversion) {
  1315. carp "resume option is useless when data conversion has also been requested";
  1316. undef $resume;
  1317. }
  1318. $overwrite = 1 unless (defined $overwrite or $local_is_fh or $numbered);
  1319. $copy_perm = 1 unless (defined $perm or defined $copy_perm or $local_is_fh);
  1320. $copy_time = 1 unless (defined $copy_time or $local_is_fh);
  1321. $mkpath = 1 unless defined $mkpath;
  1322. $cleanup = ($atomic || $numbered) unless defined $cleanup;
  1323. my $a = do {
  1324. local $sftp->{_autodie};
  1325. $sftp->stat($remote);
  1326. };
  1327. my ($rperm, $size, $atime, $mtime) = ($a ? ($a->perm, $a->size, $a->atime, $a->mtime) : ());
  1328. $size = -1 unless defined $size;
  1329. if ($copy_time and not defined $atime) {
  1330. if ($best_effort) {
  1331. undef $copy_time;
  1332. }
  1333. else {
  1334. $sftp->_ok_or_autodie and $sftp->_set_error(SFTP_ERR_REMOTE_STAT_FAILED,
  1335. "Not enough information on stat, amtime not included");
  1336. return undef;
  1337. }
  1338. }
  1339. $umask = (defined $perm ? 0 : umask) unless defined $umask;
  1340. if ($copy_perm) {
  1341. if (defined $rperm) {
  1342. $perm = $rperm;
  1343. }
  1344. elsif ($best_effort) {
  1345. undef $copy_perm
  1346. }
  1347. else {
  1348. $sftp->_ok_or_autodie and $sftp->_set_error(SFTP_ERR_REMOTE_STAT_FAILED,
  1349. "Not enough information on stat, mode not included");
  1350. return undef
  1351. }
  1352. }
  1353. $perm &= ~$umask if defined $perm;
  1354. $sftp->_clear_error_and_status;
  1355. if ($resume and $resume eq 'auto') {
  1356. undef $resume;
  1357. if (defined $mtime) {
  1358. if (my @lstat = CORE::stat $local) {
  1359. $resume = ($mtime <= $lstat[9]);
  1360. }
  1361. }
  1362. }
  1363. my ($atomic_numbered, $atomic_local, $atomic_cleanup);
  1364. my ($rfh, $fh);
  1365. my $askoff = 0;
  1366. my $lstart = 0;
  1367. if ($dont_save) {
  1368. $rfh = $sftp->open($remote, SSH2_FXF_READ);
  1369. defined $rfh or return undef;
  1370. }
  1371. else {
  1372. unless ($local_is_fh or $overwrite or $append or $resume or $numbered) {
  1373. if (-e $local) {
  1374. $sftp->_set_error(SFTP_ERR_LOCAL_ALREADY_EXISTS,
  1375. "local file $local already exists");
  1376. return undef
  1377. }
  1378. }
  1379. if ($atomic) {
  1380. $atomic_local = $local;
  1381. $local .= sprintf("(%d).tmp", rand(10000));
  1382. $atomic_numbered = $numbered;
  1383. $numbered = 1;
  1384. $debug and $debug & 128 and _debug("temporal local file name: $local");
  1385. }
  1386. if ($resume) {
  1387. if (CORE::open $fh, '+<', $local) {
  1388. binmode $fh;
  1389. CORE::seek($fh, 0, 2);
  1390. $askoff = CORE::tell $fh;
  1391. if ($askoff < 0) {
  1392. # something is going really wrong here, fall
  1393. # back to non-resuming mode...
  1394. $askoff = 0;
  1395. undef $fh;
  1396. }
  1397. else {
  1398. if ($size >=0 and $askoff > $size) {
  1399. $sftp->_set_error(SFTP_ERR_LOCAL_BIGGER_THAN_REMOTE,
  1400. "Couldn't resume transfer, local file is bigger than remote");
  1401. return undef;
  1402. }
  1403. $size == $askoff and return 1;
  1404. }
  1405. }
  1406. }
  1407. # we open the remote file so late in order to skip it when
  1408. # resuming an already completed transfer:
  1409. $rfh = $sftp->open($remote, SSH2_FXF_READ);
  1410. defined $rfh or return undef;
  1411. unless (defined $fh) {
  1412. if ($local_is_fh) {
  1413. $fh = $local;
  1414. local ($@, $SIG{__DIE__}, $SIG{__WARN__});
  1415. eval { $lstart = CORE::tell($fh) };
  1416. $lstart = 0 unless ($lstart and $lstart > 0);
  1417. }
  1418. else {
  1419. my $flags = Fcntl::O_CREAT|Fcntl::O_WRONLY;
  1420. $flags |= Fcntl::O_APPEND if $append;
  1421. $flags |= Fcntl::O_EXCL if ($numbered or (!$overwrite and !$append));
  1422. unlink $local if $overwrite;
  1423. my $open_perm = (defined $perm ? $perm : 0666);
  1424. my $save = _umask_save_and_set($umask);
  1425. $sftp->_mkpath_local($local, $perm|0700, 1) if $mkpath;
  1426. while (1) {
  1427. sysopen ($fh, $local, $flags, $open_perm) and last;
  1428. unless ($numbered and -e $local) {
  1429. $sftp->_set_error(SFTP_ERR_LOCAL_OPEN_FAILED,
  1430. "Can't open $local", $!);
  1431. return undef;
  1432. }
  1433. _inc_numbered($local);
  1434. }
  1435. $$numbered = $local if ref $numbered;
  1436. binmode $fh;
  1437. $lstart = sysseek($fh, 0, 1) if $append;
  1438. }
  1439. }
  1440. if (defined $perm) {
  1441. my $error;
  1442. do {
  1443. local ($@, $SIG{__DIE__}, $SIG{__WARN__});
  1444. unless (eval { CORE::chmod($perm, $local) > 0 }) {
  1445. $error = ($@ ? $@ : $!);
  1446. }
  1447. };
  1448. if ($error and !$best_effort) {
  1449. unlink $local unless $resume or $append;
  1450. $sftp->_set_error(SFTP_ERR_LOCAL_CHMOD_FAILED,
  1451. "Can't chmod $local", $error);
  1452. return undef
  1453. }
  1454. }
  1455. }
  1456. my $converter = _gen_converter $conversion;
  1457. my $rfid = $sftp->_rfid($rfh);
  1458. defined $rfid or die "internal error: rfid not defined";
  1459. my @msgid;
  1460. my @askoff;
  1461. my $loff = $askoff;
  1462. my $adjustment = 0;
  1463. local $\;
  1464. my $slow_start = ($size == -1 ? $queue_size - 1 : 0);
  1465. my $safe_block_size = $sftp->{_min_block_size} >= $block_size;
  1466. do {
  1467. # Disable autodie here in order to do not leave unhandled
  1468. # responses queued on the connection in case of failure.
  1469. local $sftp->{_autodie};
  1470. # Again, once this point is reached, all code paths should end
  1471. # through the CLEANUP block.
  1472. while (1) {
  1473. # request a new block if queue is not full
  1474. while (!@msgid or ( ($size == -1 or $size + $block_size > $askoff) and
  1475. @msgid < $queue_size - $slow_start and
  1476. $safe_block_size ) ) {
  1477. my $id = $sftp->_queue_new_msg(SSH2_FXP_READ, str=> $rfid,
  1478. int64 => $askoff, int32 => $block_size);
  1479. push @msgid, $id;
  1480. push @askoff, $askoff;
  1481. $askoff += $block_size;
  1482. }
  1483. $slow_start-- if $slow_start;
  1484. my $eid = shift @msgid;
  1485. my $roff = shift @askoff;
  1486. my $msg = $sftp->_get_msg_and_check(SSH2_FXP_DATA, $eid,
  1487. SFTP_ERR_REMOTE_READ_FAILED,
  1488. "Couldn't read from remote file");
  1489. unless ($msg) {
  1490. $sftp->_set_error if $sftp->{_status} == SSH2_FX_EOF;
  1491. last;
  1492. }
  1493. my $data = $msg->get_str;
  1494. my $len = length $data;
  1495. if ($roff != $loff or !$len) {
  1496. $sftp->_set_error(SFTP_ERR_REMOTE_BLOCK_TOO_SMALL,
  1497. "remote packet received is too small" );
  1498. last;
  1499. }
  1500. $loff += $len;
  1501. unless ($safe_block_size) {
  1502. if ($len > $sftp->{_min_block_size}) {
  1503. $sftp->{min_block_size} = $len;
  1504. if ($len < $block_size) {
  1505. # auto-adjust block size
  1506. $block_size = $len;
  1507. $askoff = $loff;
  1508. }
  1509. }
  1510. $safe_block_size = 1;
  1511. }
  1512. my $adjustment_before = $adjustment;
  1513. $adjustment += $converter->($data) if $converter;
  1514. if (length($data) and defined $cb) {
  1515. # $size = $loff if ($loff > $size and $size != -1);
  1516. local $\;
  1517. $cb->($sftp, $data,
  1518. $lstart + $roff + $adjustment_before,
  1519. $lstart + $size + $adjustment);
  1520. last if $sftp->{_error};
  1521. }
  1522. if (length($data) and !$dont_save) {
  1523. unless (print $fh $data) {
  1524. $sftp->_set_error(SFTP_ERR_LOCAL_WRITE_FAILED,
  1525. "unable to write data to local file $local", $!);
  1526. last;
  1527. }
  1528. }
  1529. }
  1530. $sftp->_get_msg for (@msgid);
  1531. goto CLEANUP if $sftp->{_error};
  1532. # if a converter is in place, and aditional call has to be
  1533. # performed in order to flush any pending buffered data
  1534. if ($converter) {
  1535. my $data = '';
  1536. my $adjustment_before = $adjustment;
  1537. $adjustment += $converter->($data);
  1538. if (length($data) and defined $cb) {
  1539. # $size = $loff if ($loff > $size and $size != -1);
  1540. local $\;
  1541. $cb->($sftp, $data, $askoff + $adjustment_before, $size + $adjustment);
  1542. goto CLEANUP if $sftp->{_error};
  1543. }
  1544. if (length($data) and !$dont_save) {
  1545. unless (print $fh $data) {
  1546. $sftp->_set_error(SFTP_ERR_LOCAL_WRITE_FAILED,
  1547. "unable to write data to local file $local", $!);
  1548. goto CLEANUP;
  1549. }
  1550. }
  1551. }
  1552. # we call the callback one last time with an empty string;
  1553. if (defined $cb) {
  1554. my $data = '';
  1555. do {
  1556. local $\;
  1557. $cb->($sftp, $data, $askoff + $adjustment, $size + $adjustment);
  1558. };
  1559. return undef if $sftp->{_error};
  1560. if (length($data) and !$dont_save) {
  1561. unless (print $fh $data) {
  1562. $sftp->_set_error(SFTP_ERR_LOCAL_WRITE_FAILED,
  1563. "unable to write data to local file $local", $!);
  1564. goto CLEANUP;
  1565. }
  1566. }
  1567. }
  1568. unless ($dont_save) {
  1569. unless ($local_is_fh or CORE::close $fh) {
  1570. $sftp->_set_error(SFTP_ERR_LOCAL_WRITE_FAILED,
  1571. "unable to write data to local file $local", $!);
  1572. goto CLEANUP;
  1573. }
  1574. # we can be running on taint mode, so some checks are
  1575. # performed to untaint data from the remote side.
  1576. if ($copy_time) {
  1577. unless (utime($atime, $mtime, $local) or $best_effort) {
  1578. $sftp->_set_error(SFTP_ERR_LOCAL_UTIME_FAILED,
  1579. "Can't utime $local", $!);
  1580. goto CLEANUP;
  1581. }
  1582. }
  1583. if ($atomic) {
  1584. if (!$overwrite) {
  1585. while (1) {
  1586. # performing a non-overwriting atomic rename is
  1587. # quite burdensome: first, link is tried, if that
  1588. # fails, non-overwriting is favoured over
  1589. # atomicity and an empty file is used to lock the
  1590. # path before atempting an overwriting rename.
  1591. if (link $local, $atomic_local) {
  1592. unlink $local;
  1593. last;
  1594. }
  1595. my $err = $!;
  1596. unless (-e $atomic_local) {
  1597. if (sysopen my $lock, $atomic_local,
  1598. Fcntl::O_CREAT|Fcntl::O_EXCL|Fcntl::O_WRONLY,
  1599. 0600) {
  1600. $atomic_cleanup = 1;
  1601. goto OVERWRITE;
  1602. }
  1603. $err = $!;
  1604. unless (-e $atomic_local) {
  1605. $sftp->_set_error(SFTP_ERR_LOCAL_OPEN_FAILED,
  1606. "Can't open $local", $err);
  1607. goto CLEANUP;
  1608. }
  1609. }
  1610. unless ($numbered) {
  1611. $sftp->_set_error(SFTP_ERR_LOCAL_ALREADY_EXISTS,
  1612. "local file $atomic_local already exists");
  1613. goto CLEANUP;
  1614. }
  1615. _inc_numbered($atomic_local);
  1616. }
  1617. }
  1618. else {
  1619. OVERWRITE:
  1620. unless (CORE::rename $local, $atomic_local) {
  1621. $sftp->_set_error(SFTP_ERR_LOCAL_RENAME_FAILED,
  1622. "Unable to rename temporal file to its final position '$atomic_local'", $!);
  1623. goto CLEANUP;
  1624. }
  1625. }
  1626. $$atomic_numbered = $local if ref $atomic_numbered;
  1627. }
  1628. }
  1629. CLEANUP:
  1630. if ($cleanup and $sftp->{_error}) {
  1631. unlink $local;
  1632. unlink $atomic_local if $atomic_cleanup;
  1633. }
  1634. }; # autodie flag is restored here!
  1635. $sftp->_ok_or_autodie;
  1636. }
  1637. # return file contents on success, undef on failure
  1638. sub get_content {
  1639. @_ == 2 or croak 'Usage: $sftp->get_content($remote)';
  1640. ${^TAINT} and &_catch_tainted_args;
  1641. my ($sftp, $name) = @_;
  1642. $name = $sftp->_rel2abs($name);
  1643. my @data;
  1644. my $rfh = $sftp->open($name)
  1645. or return undef;
  1646. scalar $sftp->readline($rfh, undef);
  1647. }
  1648. sub put {
  1649. @_ >= 2 or croak 'Usage: $sftp->put($local, $remote, %opts)';
  1650. ${^TAINT} and &_catch_tainted_args;
  1651. my ($sftp, $local, $remote, %opts) = @_;
  1652. defined $local or croak "local file path is undefined";
  1653. $sftp->_clear_error_and_status;
  1654. my $local_is_fh = (ref $local and $local->isa('GLOB'));
  1655. unless (defined $remote) {
  1656. $local_is_fh and croak "unable to infer remote file name when a file handler is passed as local";
  1657. $remote = (File::Spec->splitpath($local))[2];
  1658. }
  1659. $remote = $sftp->_rel2abs($remote);
  1660. my $cb = delete $opts{callback};
  1661. my $umask = delete $opts{umask};
  1662. my $perm = delete $opts{perm};
  1663. my $copy_perm = delete $opts{copy_perm};
  1664. $copy_perm = delete $opts{copy_perms} unless defined $copy_perm;
  1665. my $copy_time = delete $opts{copy_time};
  1666. my $overwrite = delete $opts{overwrite};
  1667. my $resume = delete $opts{resume};
  1668. my $append = delete $opts{append};
  1669. my $block_size = delete $opts{block_size} || $sftp->{_block_size};
  1670. my $queue_size = delete $opts{queue_size} || $sftp->{_queue_size};
  1671. my $conversion = delete $opts{conversion};
  1672. my $late_set_perm = delete $opts{late_set_perm};
  1673. my $numbered = delete $opts{numbered};
  1674. my $atomic = delete $opts{atomic};
  1675. my $cleanup = delete $opts{cleanup};
  1676. my $best_effort = delete $opts{best_effort};
  1677. my $sparse = delete $opts{sparse};
  1678. my $mkpath = delete $opts{mkpath};
  1679. croak "'perm' and 'umask' options can not be used simultaneously"
  1680. if (defined $perm and defined $umask);
  1681. croak "'perm' and 'copy_perm' options can not be used simultaneously"
  1682. if (defined $perm and $copy_perm);
  1683. croak "'resume' and 'append' options can not be used simultaneously"
  1684. if ($resume and $append);
  1685. croak "'resume' and 'overwrite' options can not be used simultaneously"
  1686. if ($resume and $overwrite);
  1687. croak "'numbered' can not be used with 'overwrite', 'resume' or 'append'"
  1688. if ($numbered and ($overwrite or $resume or $append));
  1689. croak "'atomic' can not be used with 'resume' or 'append'"
  1690. if ($atomic and ($resume or $append));
  1691. %opts and _croak_bad_options(keys %opts);
  1692. $overwrite = 1 unless (defined $overwrite or $numbered);
  1693. $copy_perm = 1 unless (defined $perm or defined $copy_perm or $local_is_fh);
  1694. $copy_time = 1 unless (defined $copy_time or $local_is_fh);
  1695. $late_set_perm = $sftp->{_late_set_perm} unless defined $late_set_perm;
  1696. $cleanup = ($atomic || $numbered) unless defined $cleanup;
  1697. $mkpath = 1 unless defined $mkpath;
  1698. my $neg_umask;
  1699. if (defined $perm) {
  1700. $neg_umask = $perm;
  1701. }
  1702. else {
  1703. $umask = umask unless defined $umask;
  1704. $neg_umask = 0777 & ~$umask;
  1705. }
  1706. my ($fh, $lmode, $lsize, $latime, $lmtime);
  1707. if ($local_is_fh) {
  1708. $fh = $local;
  1709. # we don't set binmode for the passed file handle on purpose
  1710. }
  1711. else {
  1712. unless (CORE::open $fh, '<', $local) {
  1713. $sftp->_set_error(SFTP_ERR_LOCAL_OPEN_FAILED,
  1714. "Unable to open local file '$local'", $!);
  1715. return undef;
  1716. }
  1717. binmode $fh;
  1718. }
  1719. {
  1720. # as $fh can come from the outside, it may be a tied object
  1721. # lacking support for some methods, so we call them wrapped
  1722. # inside eval blocks
  1723. local ($@, $SIG{__DIE__}, $SIG{__WARN__});
  1724. if ((undef, undef, $lmode, undef, undef,
  1725. undef, undef, $lsize, $latime, $lmtime) =
  1726. eval {
  1727. no warnings; # Calling stat on a tied handler
  1728. # generates a warning because the op is
  1729. # not supported by the tie API.
  1730. CORE::stat $fh;
  1731. }
  1732. ) {
  1733. $debug and $debug & 16384 and _debug "local file size is " . (defined $lsize ? $lsize : '<undef>');
  1734. # $fh can point at some place inside the file, not just at the
  1735. # begining
  1736. if ($local_is_fh and defined $lsize) {
  1737. my $tell = eval { CORE::tell $fh };
  1738. $lsize -= $tell if $tell and $tell > 0;
  1739. }
  1740. }
  1741. elsif ($copy_perm or $copy_time) {
  1742. $sftp->_set_error(SFTP_ERR_LOCAL_STAT_FAILED,
  1743. "Couldn't stat local file '$local'", $!);
  1744. return undef;
  1745. }
  1746. elsif ($resume and $resume eq 'auto') {
  1747. $debug and $debug & 16384 and _debug "not resuming because stat'ing the local file failed";
  1748. undef $resume
  1749. }
  1750. }
  1751. $perm = $lmode & $neg_umask if $copy_perm;
  1752. my $attrs = Net::SFTP::Foreign::Attributes->new;
  1753. $attrs->set_perm($perm) if defined $perm;
  1754. my $rfh;
  1755. my $writeoff = 0;
  1756. my $converter = _gen_converter $conversion;
  1757. my $converted_input = '';
  1758. my $rattrs;
  1759. if ($resume or $append) {
  1760. $rattrs = do {
  1761. local $sftp->{_autodie};
  1762. $sftp->stat($remote);
  1763. };
  1764. if ($rattrs) {
  1765. if ($resume and $resume eq 'auto' and $rattrs->mtime >= $lmtime) {
  1766. $debug and $debug & 16384 and
  1767. _debug "not resuming because local file is newer, r: ".$rattrs->mtime." l: $lmtime";
  1768. undef $resume;
  1769. }
  1770. else {
  1771. $writeoff = $rattrs->size;
  1772. $debug and $debug & 16384 and _debug "resuming from $writeoff";
  1773. }
  1774. }
  1775. else {
  1776. if ($append) {
  1777. $sftp->{_status} == SSH2_FX_NO_SUCH_FILE
  1778. or $sftp->_ok_or_autodie or return undef;
  1779. # no such file, no append
  1780. undef $append;
  1781. }
  1782. $sftp->_clear_error_and_status;
  1783. }
  1784. }
  1785. my ($atomic_numbered, $atomic_remote);
  1786. if ($writeoff) {
  1787. # one of $resume or $append is set
  1788. if ($resume) {
  1789. $debug and $debug & 16384 and _debug "resuming file transfer from $writeoff";
  1790. if ($converter) {
  1791. # as size could change, we have to read and convert
  1792. # data until we reach the given position on the local
  1793. # file:
  1794. my $off = 0;
  1795. my $eof_t;
  1796. while (1) {
  1797. my $len = length $converted_input;
  1798. my $delta = $writeoff - $off;
  1799. if ($delta <= $len) {
  1800. $debug and $debug & 16384 and _debug "discarding $delta converted bytes";
  1801. substr $converted_input, 0, $delta, '';
  1802. last;
  1803. }
  1804. else {
  1805. $off += $len;
  1806. if ($eof_t) {
  1807. $sftp->_set_error(SFTP_ERR_REMOTE_BIGGER_THAN_LOCAL,
  1808. "Couldn't resume transfer, remote file is bigger than local");
  1809. return undef;
  1810. }
  1811. my $read = CORE::read($fh, $converted_input, $block_size * 4);
  1812. unless (defined $read) {
  1813. $sftp->_set_error(SFTP_ERR_LOCAL_READ_ERROR,
  1814. "Couldn't read from local file '$local' to the resume point $writeoff", $!);
  1815. return undef;
  1816. }
  1817. $lsize += $converter->($converted_input) if defined $lsize;
  1818. utf8::downgrade($converted_input, 1)
  1819. or croak "converter introduced wide characters in data";
  1820. $read or $eof_t = 1;
  1821. }
  1822. }
  1823. }
  1824. elsif ($local_is_fh) {
  1825. # as some PerlIO layer could be installed on the $fh,
  1826. # just seeking to the resume position will not be
  1827. # enough. We have to read and discard data until the
  1828. # desired offset is reached
  1829. my $off = $writeoff;
  1830. while ($off) {
  1831. my $read = CORE::read($fh, my($buf), ($off < 16384 ? $off : 16384));
  1832. if ($read) {
  1833. $debug and $debug & 16384 and _debug "discarding $read bytes";
  1834. $off -= $read;
  1835. }
  1836. else {
  1837. $sftp->_set_error(defined $read
  1838. ? ( SFTP_ERR_REMOTE_BIGGER_THAN_LOCAL,
  1839. "Couldn't resume transfer, remote file is bigger than local")
  1840. : ( SFTP_ERR_LOCAL_READ_ERROR,
  1841. "Couldn't read from local file handler '$local' to the resume point $writeoff", $!));
  1842. }
  1843. }
  1844. }
  1845. else {
  1846. if (defined $lsize and $writeoff > $lsize) {
  1847. $sftp->_set_error(SFTP_ERR_REMOTE_BIGGER_THAN_LOCAL,
  1848. "Couldn't resume transfer, remote file is bigger than local");
  1849. return undef;
  1850. }
  1851. unless (CORE::seek($fh, $writeoff, 0)) {
  1852. $sftp->_set_error(SFTP_ERR_LOCAL_SEEK_FAILED,
  1853. "seek operation on local file failed: $!");
  1854. return undef;
  1855. }
  1856. }
  1857. if (defined $lsize and $writeoff == $lsize) {
  1858. if (defined $perm and $rattrs->perm != $perm) {
  1859. # FIXME: do copy_time here if required
  1860. return $sftp->_best_effort($best_effort, setstat => $remote, $attrs);
  1861. }
  1862. return 1;
  1863. }
  1864. }
  1865. $rfh = $sftp->open($remote, SSH2_FXF_WRITE)
  1866. or return undef;
  1867. }
  1868. else {
  1869. if ($atomic) {
  1870. # check that does not exist a file of the same name that
  1871. # would block the rename operation at the end
  1872. if (!($numbered or $overwrite) and
  1873. $sftp->test_e($remote)) {
  1874. $sftp->_set_status(SSH2_FX_FAILURE);
  1875. $sftp->_set_error(SFTP_ERR_REMOTE_ALREADY_EXISTS,
  1876. "Remote file '$remote' already exists");
  1877. return undef;
  1878. }
  1879. $atomic_remote = $remote;
  1880. $remote .= sprintf("(%d).tmp", rand(10000));
  1881. $atomic_numbered = $numbered;
  1882. $numbered = 1;
  1883. $debug and $debug & 128 and _debug("temporal remote file name: $remote");
  1884. }
  1885. local $sftp->{_autodie};
  1886. if ($numbered) {
  1887. while (1) {
  1888. $rfh = $sftp->_open_mkpath($remote,
  1889. $mkpath,
  1890. SSH2_FXF_WRITE | SSH2_FXF_CREAT | SSH2_FXF_EXCL,
  1891. $attrs);
  1892. last if ($rfh or
  1893. $sftp->{_status} != SSH2_FX_FAILURE or
  1894. !$sftp->test_e($remote));
  1895. _inc_numbered($remote);
  1896. }
  1897. $$numbered = $remote if $rfh and ref $numbered;
  1898. }
  1899. else {
  1900. # open can fail due to a remote file with the wrong
  1901. # permissions being already there. We are optimistic here,
  1902. # first we try to open the remote file and if it fails due
  1903. # to a permissions error then we remove it and try again.
  1904. for my $rep (0, 1) {
  1905. $rfh = $sftp->_open_mkpath($remote,
  1906. $mkpath,
  1907. SSH2_FXF_WRITE | SSH2_FXF_CREAT |
  1908. ($overwrite ? SSH2_FXF_TRUNC : SSH2_FXF_EXCL),
  1909. $attrs);
  1910. last if $rfh or $rep or !$overwrite or $sftp->{_status} != SSH2_FX_PERMISSION_DENIED;
  1911. $debug and $debug & 2 and _debug("retrying open after removing remote file");
  1912. local ($sftp->{_status}, $sftp->{_error});
  1913. $sftp->remove($remote);
  1914. }
  1915. }
  1916. }
  1917. $sftp->_ok_or_autodie or return undef;
  1918. # Once this point is reached and for the remaining of the sub,
  1919. # code should never return but jump into the CLEANUP block.
  1920. my $last_block_was_zeros;
  1921. do {
  1922. local $sftp->{autodie};
  1923. # In some SFTP server implementations, open does not set the
  1924. # attributes for existent files so we do it again. The
  1925. # $late_set_perm work around is for some servers that do not
  1926. # support changing the permissions of open files
  1927. if (defined $perm and !$late_set_perm) {
  1928. $sftp->_best_effort($best_effort, setstat => $rfh, $attrs) or goto CLEANUP;
  1929. }
  1930. my $rfid = $sftp->_rfid($rfh);
  1931. defined $rfid or die "internal error: rfid is undef";
  1932. # In append mode we add the size of the remote file in
  1933. # writeoff, if lsize is undef, we initialize it to $writeoff:
  1934. $lsize += $writeoff if ($append or not defined $lsize);
  1935. # when a converter is used, the EOF can become delayed by the
  1936. # buffering introduced, we use $eof_t to account for that.
  1937. my ($eof, $eof_t);
  1938. my @msgid;
  1939. OK: while (1) {
  1940. if (!$eof and @msgid < $queue_size) {
  1941. my ($data, $len);
  1942. if ($converter) {
  1943. while (!$eof_t and length $converted_input < $block_size) {
  1944. my $read = CORE::read($fh, my $input, $block_size * 4);
  1945. unless ($read) {
  1946. unless (defined $read) {
  1947. $sftp->_set_error(SFTP_ERR_LOCAL_READ_ERROR,
  1948. "Couldn't read from local file '$local'", $!);
  1949. last OK;
  1950. }
  1951. $eof_t = 1;
  1952. }
  1953. # note that the $converter is called a last time
  1954. # with an empty string
  1955. $lsize += $converter->($input);
  1956. utf8::downgrade($input, 1)
  1957. or croak "converter introduced wide characters in data";
  1958. $converted_input .= $input;
  1959. }
  1960. $data = substr($converted_input, 0, $block_size, '');
  1961. $len = length $data;
  1962. $eof = 1 if ($eof_t and !$len);
  1963. }
  1964. else {
  1965. $debug and $debug & 16384 and
  1966. _debug "reading block at offset ".CORE::tell($fh)." block_size: $block_size";
  1967. $len = CORE::read($fh, $data, $block_size);
  1968. if ($len) {
  1969. $debug and $debug & 16384 and _debug "block read, size: $len";
  1970. utf8::downgrade($data, 1)
  1971. or croak "wide characters unexpectedly read from file";
  1972. $debug and $debug & 16384 and length $data != $len and
  1973. _debug "read data changed size on downgrade to " . length($data);
  1974. }
  1975. else {
  1976. unless (defined $len) {
  1977. $sftp->_set_error(SFTP_ERR_LOCAL_READ_ERROR,
  1978. "Couldn't read from local file '$local'", $!);
  1979. last OK;
  1980. }
  1981. $eof = 1;
  1982. }
  1983. }
  1984. my $nextoff = $writeoff + $len;
  1985. if (defined $cb) {
  1986. $lsize = $nextoff if $nextoff > $lsize;
  1987. $cb->($sftp, $data, $writeoff, $lsize);
  1988. last OK if $sftp->{_error};
  1989. utf8::downgrade($data, 1) or croak "callback introduced wide characters in data";
  1990. $len = length $data;
  1991. $nextoff = $writeoff + $len;
  1992. }
  1993. if ($len) {
  1994. if ($sparse and $data =~ /^\x{00}*$/s) {
  1995. $last_block_was_zeros = 1;
  1996. $debug and $debug & 16384 and _debug "skipping zeros block at offset $writeoff, length $len";
  1997. }
  1998. else {
  1999. $debug and $debug & 16384 and _debug "writing block at offset $writeoff, length $len";
  2000. my $id = $sftp->_queue_new_msg(SSH2_FXP_WRITE, str => $rfid,
  2001. int64 => $writeoff, str => $data);
  2002. push @msgid, $id;
  2003. $last_block_was_zeros = 0;
  2004. }
  2005. $writeoff = $nextoff;
  2006. }
  2007. }
  2008. last if ($eof and !@msgid);
  2009. next unless ($eof
  2010. or @msgid >= $queue_size
  2011. or $sftp->_do_io(0));
  2012. my $id = shift @msgid;
  2013. unless ($sftp->_check_status_ok($id,
  2014. SFTP_ERR_REMOTE_WRITE_FAILED,
  2015. "Couldn't write to remote file")) {
  2016. last OK;
  2017. }
  2018. }
  2019. CORE::close $fh unless $local_is_fh;
  2020. $sftp->_get_msg for (@msgid);
  2021. $sftp->truncate($rfh, $writeoff)
  2022. if $last_block_was_zeros and not $sftp->{_error};
  2023. $sftp->_close_save_status($rfh);
  2024. goto CLEANUP if $sftp->{_error};
  2025. # set perm for servers that does not support setting
  2026. # permissions on open files and also atime and mtime:
  2027. if ($copy_time or ($late_set_perm and defined $perm)) {
  2028. $attrs->set_perm unless $late_set_perm and defined $perm;
  2029. $attrs->set_amtime($latime, $lmtime) if $copy_time;
  2030. $sftp->_best_effort($best_effort, setstat => $remote, $attrs) or goto CLEANUP
  2031. }
  2032. if ($atomic) {
  2033. $sftp->rename($remote, $atomic_remote,
  2034. overwrite => $overwrite,
  2035. numbered => $atomic_numbered) or goto CLEANUP;
  2036. }
  2037. CLEANUP:
  2038. if ($cleanup and $sftp->{_error}) {
  2039. warn "cleanup $remote";
  2040. $sftp->_remove_save_status($remote);
  2041. }
  2042. };
  2043. $sftp->_ok_or_autodie;
  2044. }
  2045. sub put_content {
  2046. @_ >= 3 or croak 'Usage: $sftp->put_content($content, $remote, %opts)';
  2047. ${^TAINT} and &_catch_tainted_args;
  2048. my ($sftp, undef, $remote, %opts) = @_;
  2049. my %put_opts = ( map { $_ => delete $opts{$_} }
  2050. qw(perm umask block_size queue_size overwrite conversion resume
  2051. numbered late_set_perm atomic best_effort mkpath));
  2052. %opts and _croak_bad_options(keys %opts);
  2053. my $fh;
  2054. unless (CORE::open $fh, '<', \$_[1]) {
  2055. $sftp->_set_error(SFTP_ERR_LOCAL_OPEN_FAILED, "Can't open scalar as file handle", $!);
  2056. return undef;
  2057. }
  2058. $sftp->put($fh, $remote, %opts);
  2059. }
  2060. sub ls {
  2061. @_ >= 1 or croak 'Usage: $sftp->ls($remote_dir, %opts)';
  2062. ${^TAINT} and &_catch_tainted_args;
  2063. my $sftp = shift;
  2064. my %opts = @_ & 1 ? (dir => @_) : @_;
  2065. my $dir = delete $opts{dir};
  2066. my $ordered = delete $opts{ordered};
  2067. my $follow_links = delete $opts{follow_links};
  2068. my $atomic_readdir = delete $opts{atomic_readdir};
  2069. my $names_only = delete $opts{names_only};
  2070. my $realpath = delete $opts{realpath};
  2071. my $queue_size = delete $opts{queue_size};
  2072. my $cheap = ($names_only and !$realpath);
  2073. my ($cheap_wanted, $wanted);
  2074. if ($cheap and
  2075. ref $opts{wanted} eq 'RegExp' and
  2076. not defined $opts{no_wanted}) {
  2077. $cheap_wanted = delete $opts{wanted}
  2078. }
  2079. else {
  2080. $wanted = (delete $opts{_wanted} ||
  2081. _gen_wanted(delete $opts{wanted},
  2082. delete $opts{no_wanted}));
  2083. undef $cheap if defined $wanted;
  2084. }
  2085. %opts and _croak_bad_options(keys %opts);
  2086. my $delayed_wanted = ($atomic_readdir and $wanted);
  2087. $queue_size = 1 if ($follow_links or $realpath or
  2088. ($wanted and not $delayed_wanted));
  2089. my $max_queue_size = $queue_size || $sftp->{_queue_size};
  2090. $queue_size ||= 2;
  2091. $dir = '.' unless defined $dir;
  2092. $dir = $sftp->_rel2abs($dir);
  2093. my $rdh = $sftp->opendir($dir);
  2094. return unless defined $rdh;
  2095. my $rdid = $sftp->_rdid($rdh);
  2096. defined $rdid or return undef;
  2097. my @dir;
  2098. my @msgid;
  2099. do {
  2100. local $sftp->{_autodie};
  2101. OK: while (1) {
  2102. push @msgid, $sftp->_queue_str_request(SSH2_FXP_READDIR, $rdid)
  2103. while (@msgid < $queue_size);
  2104. my $id = shift @msgid;
  2105. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_NAME, $id,
  2106. SFTP_ERR_REMOTE_READDIR_FAILED,
  2107. "Couldn't read directory '$dir'" )) {
  2108. my $count = $msg->get_int32 or last;
  2109. if ($cheap) {
  2110. for (1..$count) {
  2111. my $fn = $sftp->_fs_decode($msg->get_str);
  2112. push @dir, $fn if (!defined $cheap_wanted or $fn =~ $cheap_wanted);
  2113. $msg->skip_str;
  2114. Net::SFTP::Foreign::Attributes->skip_from_buffer($msg);
  2115. }
  2116. }
  2117. else {
  2118. for (1..$count) {
  2119. my $fn = $sftp->_fs_decode($msg->get_str);
  2120. my $ln = $sftp->_fs_decode($msg->get_str);
  2121. # my $a = $msg->get_attributes;
  2122. my $a = Net::SFTP::Foreign::Attributes->new_from_buffer($msg);
  2123. my $entry = { filename => $fn,
  2124. longname => $ln,
  2125. a => $a };
  2126. if ($follow_links and _is_lnk($a->perm)) {
  2127. if ($a = $sftp->stat($sftp->join($dir, $fn))) {
  2128. $entry->{a} = $a;
  2129. }
  2130. else {
  2131. $sftp->_clear_error_and_status;
  2132. }
  2133. }
  2134. if ($realpath) {
  2135. my $rp = $sftp->realpath($sftp->join($dir, $fn));
  2136. if (defined $rp) {
  2137. $fn = $entry->{realpath} = $rp;
  2138. }
  2139. else {
  2140. $sftp->_clear_error_and_status;
  2141. }
  2142. }
  2143. if (!$wanted or $delayed_wanted or $wanted->($sftp, $entry)) {
  2144. push @dir, (($names_only and !$delayed_wanted) ? $fn : $entry);
  2145. }
  2146. }
  2147. }
  2148. $queue_size ++ if $queue_size < $max_queue_size;
  2149. }
  2150. else {
  2151. $sftp->_set_error if $sftp->{_status} == SSH2_FX_EOF;
  2152. $sftp->_get_msg for @msgid;
  2153. last;
  2154. }
  2155. }
  2156. $sftp->_closedir_save_status($rdh) if $rdh;
  2157. };
  2158. unless ($sftp->{_error}) {
  2159. if ($delayed_wanted) {
  2160. @dir = grep { $wanted->($sftp, $_) } @dir;
  2161. @dir = map { defined $_->{realpath}
  2162. ? $_->{realpath}
  2163. : $_->{filename} } @dir
  2164. if $names_only;
  2165. }
  2166. if ($ordered) {
  2167. if ($names_only) {
  2168. @dir = sort @dir;
  2169. }
  2170. else {
  2171. _sort_entries \@dir;
  2172. }
  2173. }
  2174. return \@dir;
  2175. }
  2176. croak $sftp->{_error} if $sftp->{_autodie};
  2177. return undef;
  2178. }
  2179. sub rremove {
  2180. @_ >= 2 or croak 'Usage: $sftp->rremove($dirs, %opts)';
  2181. ${^TAINT} and &_catch_tainted_args;
  2182. my ($sftp, $dirs, %opts) = @_;
  2183. my $on_error = delete $opts{on_error};
  2184. local $sftp->{_autodie} if $on_error;
  2185. my $wanted = _gen_wanted( delete $opts{wanted},
  2186. delete $opts{no_wanted});
  2187. %opts and _croak_bad_options(keys %opts);
  2188. my $count = 0;
  2189. my @dirs;
  2190. $sftp->find( $dirs,
  2191. on_error => $on_error,
  2192. atomic_readdir => 1,
  2193. wanted => sub {
  2194. my $e = $_[1];
  2195. my $fn = $e->{filename};
  2196. if (_is_dir($e->{a}->perm)) {
  2197. push @dirs, $e;
  2198. }
  2199. else {
  2200. if (!$wanted or $wanted->($sftp, $e)) {
  2201. if ($sftp->remove($fn)) {
  2202. $count++;
  2203. }
  2204. else {
  2205. $sftp->_call_on_error($on_error, $e);
  2206. }
  2207. }
  2208. }
  2209. } );
  2210. _sort_entries(\@dirs);
  2211. while (@dirs) {
  2212. my $e = pop @dirs;
  2213. if (!$wanted or $wanted->($sftp, $e)) {
  2214. if ($sftp->rmdir($e->{filename})) {
  2215. $count++;
  2216. }
  2217. else {
  2218. $sftp->_call_on_error($on_error, $e);
  2219. }
  2220. }
  2221. }
  2222. return $count;
  2223. }
  2224. sub get_symlink {
  2225. @_ >= 3 or croak 'Usage: $sftp->get_symlink($remote, $local, %opts)';
  2226. my ($sftp, $remote, $local, %opts) = @_;
  2227. my $overwrite = delete $opts{overwrite};
  2228. my $numbered = delete $opts{numbered};
  2229. croak "'overwrite' and 'numbered' can not be used together"
  2230. if ($overwrite and $numbered);
  2231. %opts and _croak_bad_options(keys %opts);
  2232. $overwrite = 1 unless (defined $overwrite or $numbered);
  2233. my $a = $sftp->lstat($remote) or return undef;
  2234. unless (_is_lnk($a->perm)) {
  2235. $sftp->_set_error(SFTP_ERR_REMOTE_BAD_OBJECT,
  2236. "Remote object '$remote' is not a symlink");
  2237. return undef;
  2238. }
  2239. my $link = $sftp->readlink($remote) or return undef;
  2240. # TODO: this is too weak, may contain race conditions.
  2241. if ($numbered) {
  2242. _inc_numbered($local) while -e $local;
  2243. }
  2244. elsif (-e $local) {
  2245. if ($overwrite) {
  2246. unlink $local;
  2247. }
  2248. else {
  2249. $sftp->_set_error(SFTP_ERR_LOCAL_ALREADY_EXISTS,
  2250. "local file $local already exists");
  2251. return undef
  2252. }
  2253. }
  2254. unless (eval { CORE::symlink $link, $local }) {
  2255. $sftp->_set_error(SFTP_ERR_LOCAL_SYMLINK_FAILED,
  2256. "creation of symlink '$local' failed", $!);
  2257. return undef;
  2258. }
  2259. $$numbered = $local if ref $numbered;
  2260. 1;
  2261. }
  2262. sub put_symlink {
  2263. @_ >= 3 or croak 'Usage: $sftp->put_symlink($local, $remote, %opts)';
  2264. my ($sftp, $local, $remote, %opts) = @_;
  2265. my $overwrite = delete $opts{overwrite};
  2266. my $numbered = delete $opts{numbered};
  2267. croak "'overwrite' and 'numbered' can not be used together"
  2268. if ($overwrite and $numbered);
  2269. %opts and _croak_bad_options(keys %opts);
  2270. $overwrite = 1 unless (defined $overwrite or $numbered);
  2271. my $perm = (CORE::lstat $local)[2];
  2272. unless (defined $perm) {
  2273. $sftp->_set_error(SFTP_ERR_LOCAL_STAT_FAILED,
  2274. "Couldn't stat local file '$local'", $!);
  2275. return undef;
  2276. }
  2277. unless (_is_lnk($perm)) {
  2278. $sftp->_set_error(SFTP_ERR_LOCAL_BAD_OBJECT,
  2279. "Local file $local is not a symlink");
  2280. return undef;
  2281. }
  2282. my $target = readlink $local;
  2283. unless (defined $target) {
  2284. $sftp->_set_error(SFTP_ERR_LOCAL_READLINK_FAILED,
  2285. "Couldn't read link '$local'", $!);
  2286. return undef;
  2287. }
  2288. while (1) {
  2289. local $sftp->{_autodie};
  2290. $sftp->symlink($remote, $target);
  2291. if ($sftp->{_error} and
  2292. $sftp->{_status} == SSH2_FX_FAILURE) {
  2293. if ($numbered and $sftp->test_e($remote)) {
  2294. _inc_numbered($remote);
  2295. redo;
  2296. }
  2297. elsif ($overwrite and $sftp->_remove_save_status($remote)) {
  2298. $overwrite = 0;
  2299. redo;
  2300. }
  2301. }
  2302. last
  2303. }
  2304. $$numbered = $remote if ref $numbered;
  2305. $sftp->_ok_or_autodie;
  2306. }
  2307. sub rget {
  2308. @_ >= 2 or croak 'Usage: $sftp->rget($remote, $local, %opts)';
  2309. ${^TAINT} and &_catch_tainted_args;
  2310. my ($sftp, $remote, $local, %opts) = @_;
  2311. defined $remote or croak "remote file path is undefined";
  2312. $local = File::Spec->curdir unless defined $local;
  2313. # my $cb = delete $opts{callback};
  2314. my $umask = delete $opts{umask};
  2315. my $copy_perm = delete $opts{exists $opts{copy_perm} ? 'copy_perm' : 'copy_perms'};
  2316. my $copy_time = delete $opts{copy_time};
  2317. my $newer_only = delete $opts{newer_only};
  2318. my $on_error = delete $opts{on_error};
  2319. local $sftp->{_autodie} if $on_error;
  2320. my $ignore_links = delete $opts{ignore_links};
  2321. my $mkpath = delete $opts{mkpath};
  2322. # my $relative_links = delete $opts{relative_links};
  2323. my $wanted = _gen_wanted( delete $opts{wanted},
  2324. delete $opts{no_wanted} );
  2325. my %get_opts = (map { $_ => delete $opts{$_} }
  2326. qw(block_size queue_size overwrite conversion
  2327. resume numbered atomic best_effort));
  2328. if ($get_opts{resume} and $get_opts{conversion}) {
  2329. carp "resume option is useless when data conversion has also been requested";
  2330. delete $get_opts{resume};
  2331. }
  2332. my %get_symlink_opts = (map { $_ => $get_opts{$_} }
  2333. qw(overwrite numbered));
  2334. %opts and _croak_bad_options(keys %opts);
  2335. $remote = $sftp->join($remote, './');
  2336. my $qremote = quotemeta $remote;
  2337. my $reremote = qr/^$qremote(.*)$/i;
  2338. my $save = _umask_save_and_set $umask;
  2339. $copy_perm = 1 unless defined $copy_perm;
  2340. $copy_time = 1 unless defined $copy_time;
  2341. $mkpath = 1 unless defined $mkpath;
  2342. my $count = 0;
  2343. $sftp->find( [$remote],
  2344. descend => sub {
  2345. my $e = $_[1];
  2346. # print "descend: $e->{filename}\n";
  2347. if (!$wanted or $wanted->($sftp, $e)) {
  2348. my $fn = $e->{filename};
  2349. if ($fn =~ $reremote) {
  2350. my $lpath = File::Spec->catdir($local, $1);
  2351. ($lpath) = $lpath =~ /(.*)/ if ${^TAINT};
  2352. if (-d $lpath) {
  2353. $sftp->_set_error(SFTP_ERR_LOCAL_ALREADY_EXISTS,
  2354. "directory '$lpath' already exists");
  2355. $sftp->_call_on_error($on_error, $e);
  2356. return 1;
  2357. }
  2358. else {
  2359. my $perm = ($copy_perm ? $e->{a}->perm & 0777 : 0777);
  2360. if (CORE::mkdir($lpath, $perm) or
  2361. ($mkpath and $sftp->_mkpath_local($lpath, $perm))) {
  2362. $count++;
  2363. return 1;
  2364. }
  2365. $sftp->_set_error(SFTP_ERR_LOCAL_MKDIR_FAILED,
  2366. "mkdir '$lpath' failed", $!);
  2367. }
  2368. }
  2369. else {
  2370. $sftp->_set_error(SFTP_ERR_REMOTE_BAD_PATH,
  2371. "bad remote path '$fn'");
  2372. }
  2373. $sftp->_call_on_error($on_error, $e);
  2374. }
  2375. return undef;
  2376. },
  2377. wanted => sub {
  2378. my $e = $_[1];
  2379. # print "file fn:$e->{filename}, a:$e->{a}\n";
  2380. unless (_is_dir($e->{a}->perm)) {
  2381. if (!$wanted or $wanted->($sftp, $e)) {
  2382. my $fn = $e->{filename};
  2383. if ($fn =~ $reremote) {
  2384. my $lpath = File::Spec->catfile($local, $1);
  2385. ($lpath) = $lpath =~ /(.*)/ if ${^TAINT};
  2386. if (_is_lnk($e->{a}->perm) and !$ignore_links) {
  2387. if ($sftp->get_symlink($fn, $lpath,
  2388. # copy_time => $copy_time,
  2389. %get_symlink_opts)) {
  2390. $count++;
  2391. return undef;
  2392. }
  2393. }
  2394. elsif (_is_reg($e->{a}->perm)) {
  2395. if ($newer_only and -e $lpath
  2396. and (CORE::stat _)[9] >= $e->{a}->mtime) {
  2397. $sftp->_set_error(SFTP_ERR_LOCAL_ALREADY_EXISTS,
  2398. "newer local file '$lpath' already exists");
  2399. }
  2400. else {
  2401. if ($sftp->get($fn, $lpath,
  2402. copy_perm => $copy_perm,
  2403. copy_time => $copy_time,
  2404. %get_opts)) {
  2405. $count++;
  2406. return undef;
  2407. }
  2408. }
  2409. }
  2410. else {
  2411. $sftp->_set_error(SFTP_ERR_REMOTE_BAD_OBJECT,
  2412. ( $ignore_links
  2413. ? "remote file '$fn' is not regular file or directory"
  2414. : "remote file '$fn' is not regular file, directory or link"));
  2415. }
  2416. }
  2417. else {
  2418. $sftp->_set_error(SFTP_ERR_REMOTE_BAD_PATH,
  2419. "bad remote path '$fn'");
  2420. }
  2421. $sftp->_call_on_error($on_error, $e);
  2422. }
  2423. }
  2424. return undef;
  2425. } );
  2426. return $count;
  2427. }
  2428. sub rput {
  2429. @_ >= 2 or croak 'Usage: $sftp->rput($local, $remote, %opts)';
  2430. ${^TAINT} and &_catch_tainted_args;
  2431. my ($sftp, $local, $remote, %opts) = @_;
  2432. defined $local or croak "local path is undefined";
  2433. $remote = '.' unless defined $remote;
  2434. # my $cb = delete $opts{callback};
  2435. my $umask = delete $opts{umask};
  2436. my $perm = delete $opts{perm};
  2437. my $copy_perm = delete $opts{exists $opts{copy_perm} ? 'copy_perm' : 'copy_perms'};
  2438. my $copy_time = delete $opts{copy_time};
  2439. my $newer_only = delete $opts{newer_only};
  2440. my $on_error = delete $opts{on_error};
  2441. local $sftp->{_autodie} if $on_error;
  2442. my $ignore_links = delete $opts{ignore_links};
  2443. my $mkpath = delete $opts{mkpath};
  2444. my $wanted = _gen_wanted( delete $opts{wanted},
  2445. delete $opts{no_wanted} );
  2446. my %put_opts = (map { $_ => delete $opts{$_} }
  2447. qw(block_size queue_size overwrite
  2448. conversion resume numbered
  2449. late_set_perm atomic best_effort
  2450. sparse));
  2451. my %put_symlink_opts = (map { $_ => $put_opts{$_} }
  2452. qw(overwrite numbered));
  2453. croak "'perm' and 'umask' options can not be used simultaneously"
  2454. if (defined $perm and defined $umask);
  2455. croak "'perm' and 'copy_perm' options can not be used simultaneously"
  2456. if (defined $perm and $copy_perm);
  2457. %opts and _croak_bad_options(keys %opts);
  2458. require Net::SFTP::Foreign::Local;
  2459. my $lfs = Net::SFTP::Foreign::Local->new;
  2460. $local = $lfs->join($local, './');
  2461. my $relocal;
  2462. if ($local =~ m|^\./?$|) {
  2463. $relocal = qr/^(.*)$/;
  2464. }
  2465. else {
  2466. my $qlocal = quotemeta $local;
  2467. $relocal = qr/^$qlocal(.*)$/i;
  2468. }
  2469. $copy_perm = 1 unless defined $copy_perm;
  2470. $copy_time = 1 unless defined $copy_time;
  2471. $mkpath = 1 unless defined $mkpath;
  2472. my $mask;
  2473. if (defined $perm) {
  2474. $mask = $perm & 0777;
  2475. }
  2476. else {
  2477. $umask = umask unless defined $umask;
  2478. $mask = 0777 & ~$umask;
  2479. }
  2480. if ($on_error) {
  2481. my $on_error1 = $on_error;
  2482. $on_error = sub {
  2483. my $lfs = shift;
  2484. $sftp->_copy_error($lfs);
  2485. $sftp->_call_on_error($on_error1, @_);
  2486. }
  2487. }
  2488. my $count = 0;
  2489. $lfs->find( [$local],
  2490. descend => sub {
  2491. my $e = $_[1];
  2492. # print "descend: $e->{filename}\n";
  2493. if (!$wanted or $wanted->($lfs, $e)) {
  2494. my $fn = $e->{filename};
  2495. $debug and $debug & 32768 and _debug "rput handling $fn";
  2496. if ($fn =~ $relocal) {
  2497. my $rpath = $sftp->join($remote, File::Spec->splitdir($1));
  2498. $debug and $debug & 32768 and _debug "rpath: $rpath";
  2499. my $a = Net::SFTP::Foreign::Attributes->new;
  2500. if (defined $perm) {
  2501. $a->set_perm($mask | 0300);
  2502. }
  2503. elsif ($copy_perm) {
  2504. $a->set_perm($e->{a}->perm & $mask);
  2505. }
  2506. if ($sftp->mkdir($rpath, $a)) {
  2507. $count++;
  2508. return 1;
  2509. }
  2510. if ($mkpath and
  2511. $sftp->status == SSH2_FX_NO_SUCH_FILE) {
  2512. $sftp->_clear_error_and_status;
  2513. if ($sftp->mkpath($rpath, $a)) {
  2514. $count++;
  2515. return 1;
  2516. }
  2517. }
  2518. $lfs->_copy_error($sftp);
  2519. if ($sftp->test_d($rpath)) {
  2520. $lfs->_set_error(SFTP_ERR_REMOTE_ALREADY_EXISTS,
  2521. "Remote directory '$rpath' already exists");
  2522. $lfs->_call_on_error($on_error, $e);
  2523. return 1;
  2524. }
  2525. }
  2526. else {
  2527. $lfs->_set_error(SFTP_ERR_LOCAL_BAD_PATH,
  2528. "Bad local path '$fn'");
  2529. }
  2530. $lfs->_call_on_error($on_error, $e);
  2531. }
  2532. return undef;
  2533. },
  2534. wanted => sub {
  2535. my $e = $_[1];
  2536. # print "file fn:$e->{filename}, a:$e->{a}\n";
  2537. unless (_is_dir($e->{a}->perm)) {
  2538. if (!$wanted or $wanted->($lfs, $e)) {
  2539. my $fn = $e->{filename};
  2540. $debug and $debug & 32768 and _debug "rput handling $fn";
  2541. if ($fn =~ $relocal) {
  2542. my (undef, $d, $f) = File::Spec->splitpath($1);
  2543. my $rpath = $sftp->join($remote, File::Spec->splitdir($d), $f);
  2544. if (_is_lnk($e->{a}->perm) and !$ignore_links) {
  2545. if ($sftp->put_symlink($fn, $rpath,
  2546. %put_symlink_opts)) {
  2547. $count++;
  2548. return undef;
  2549. }
  2550. $lfs->_copy_error($sftp);
  2551. }
  2552. elsif (_is_reg($e->{a}->perm)) {
  2553. my $ra;
  2554. if ( $newer_only and
  2555. $ra = $sftp->stat($rpath) and
  2556. $ra->mtime >= $e->{a}->mtime) {
  2557. $lfs->_set_error(SFTP_ERR_REMOTE_ALREADY_EXISTS,
  2558. "Newer remote file '$rpath' already exists");
  2559. }
  2560. else {
  2561. if ($sftp->put($fn, $rpath,
  2562. ( defined($perm) ? (perm => $perm)
  2563. : $copy_perm ? (perm => $e->{a}->perm & $mask)
  2564. : (copy_perm => 0, umask => $umask) ),
  2565. copy_time => $copy_time,
  2566. %put_opts)) {
  2567. $count++;
  2568. return undef;
  2569. }
  2570. $lfs->_copy_error($sftp);
  2571. }
  2572. }
  2573. else {
  2574. $lfs->_set_error(SFTP_ERR_LOCAL_BAD_OBJECT,
  2575. ( $ignore_links
  2576. ? "Local file '$fn' is not regular file or directory"
  2577. : "Local file '$fn' is not regular file, directory or link"));
  2578. }
  2579. }
  2580. else {
  2581. $lfs->_set_error(SFTP_ERR_LOCAL_BAD_PATH,
  2582. "Bad local path '$fn'");
  2583. }
  2584. $lfs->_call_on_error($on_error, $e);
  2585. }
  2586. }
  2587. return undef;
  2588. } );
  2589. return $count;
  2590. }
  2591. sub mget {
  2592. @_ >= 2 or croak 'Usage: $sftp->mget($remote, $localdir, %opts)';
  2593. ${^TAINT} and &_catch_tainted_args;
  2594. my ($sftp, $remote, $localdir, %opts) = @_;
  2595. defined $remote or croak "remote pattern is undefined";
  2596. my $on_error = $opts{on_error};
  2597. local $sftp->{_autodie} if $on_error;
  2598. my $ignore_links = delete $opts{ignore_links};
  2599. my %glob_opts = (map { $_ => delete $opts{$_} }
  2600. qw(on_error follow_links ignore_case
  2601. wanted no_wanted strict_leading_dot));
  2602. my %get_symlink_opts = (map { $_ => $opts{$_} }
  2603. qw(overwrite numbered));
  2604. my %get_opts = (map { $_ => delete $opts{$_} }
  2605. qw(umask perm copy_perm copy_time block_size queue_size
  2606. overwrite conversion resume numbered atomic best_effort mkpath));
  2607. %opts and _croak_bad_options(keys %opts);
  2608. my @remote = map $sftp->glob($_, %glob_opts), _ensure_list $remote;
  2609. my $count = 0;
  2610. require File::Spec;
  2611. for my $e (@remote) {
  2612. my $perm = $e->{a}->perm;
  2613. if (_is_dir($perm)) {
  2614. $sftp->_set_error(SFTP_ERR_REMOTE_BAD_OBJECT,
  2615. "Remote object '$e->{filename}' is a directory");
  2616. }
  2617. else {
  2618. my $fn = $e->{filename};
  2619. my ($local) = $fn =~ m{([^\\/]*)$};
  2620. $local = File::Spec->catfile($localdir, $local)
  2621. if defined $localdir;
  2622. if (_is_lnk($perm)) {
  2623. next if $ignore_links;
  2624. $sftp->get_symlink($fn, $local, %get_symlink_opts);
  2625. }
  2626. else {
  2627. $sftp->get($fn, $local, %get_opts);
  2628. }
  2629. }
  2630. $count++ unless $sftp->{_error};
  2631. $sftp->_call_on_error($on_error, $e);
  2632. }
  2633. $count;
  2634. }
  2635. sub mput {
  2636. @_ >= 2 or croak 'Usage: $sftp->mput($local, $remotedir, %opts)';
  2637. my ($sftp, $local, $remotedir, %opts) = @_;
  2638. defined $local or die "local pattern is undefined";
  2639. my $on_error = $opts{on_error};
  2640. local $sftp->{_autodie} if $on_error;
  2641. my $ignore_links = delete $opts{ignore_links};
  2642. my %glob_opts = (map { $_ => delete $opts{$_} }
  2643. qw(on_error follow_links ignore_case
  2644. wanted no_wanted strict_leading_dot));
  2645. my %put_symlink_opts = (map { $_ => $opts{$_} }
  2646. qw(overwrite numbered));
  2647. my %put_opts = (map { $_ => delete $opts{$_} }
  2648. qw(umask perm copy_perm copy_time block_size queue_size
  2649. overwrite conversion resume numbered late_set_perm
  2650. atomic best_effort sparse mkpath));
  2651. %opts and _croak_bad_options(keys %opts);
  2652. require Net::SFTP::Foreign::Local;
  2653. my $lfs = Net::SFTP::Foreign::Local->new;
  2654. my @local = map $lfs->glob($_, %glob_opts), _ensure_list $local;
  2655. my $count = 0;
  2656. require File::Spec;
  2657. for my $e (@local) {
  2658. my $perm = $e->{a}->perm;
  2659. if (_is_dir($perm)) {
  2660. $sftp->_set_error(SFTP_ERR_REMOTE_BAD_OBJECT,
  2661. "Remote object '$e->{filename}' is a directory");
  2662. }
  2663. else {
  2664. my $fn = $e->{filename};
  2665. my $remote = (File::Spec->splitpath($fn))[2];
  2666. $remote = $sftp->join($remotedir, $remote)
  2667. if defined $remotedir;
  2668. if (_is_lnk($perm)) {
  2669. next if $ignore_links;
  2670. $sftp->put_symlink($fn, $remote, %put_symlink_opts);
  2671. }
  2672. else {
  2673. $sftp->put($fn, $remote, %put_opts);
  2674. }
  2675. }
  2676. $count++ unless $sftp->{_error};
  2677. $sftp->_call_on_error($on_error, $e);
  2678. }
  2679. $count;
  2680. }
  2681. sub fsync {
  2682. @_ == 2 or croak 'Usage: $sftp->fsync($fh)';
  2683. ${^TAINT} and &_catch_tainted_args;
  2684. my ($sftp, $fh) = @_;
  2685. $sftp->flush($fh, "out");
  2686. $sftp->_check_extension('fsync@openssh.com' => 1,
  2687. SFTP_ERR_REMOTE_FSYNC_FAILED,
  2688. "fsync failed, not implemented")
  2689. or return undef;
  2690. my $id = $sftp->_queue_new_msg(SSH2_FXP_EXTENDED,
  2691. str => 'fsync@openssh.com',
  2692. str => $sftp->_rid($fh));
  2693. if ($sftp->_check_status_ok($id,
  2694. SFTP_ERR_REMOTE_FSYNC_FAILED,
  2695. "Couldn't fsync remote file")) {
  2696. return 1;
  2697. }
  2698. return undef;
  2699. }
  2700. sub statvfs {
  2701. @_ == 2 or croak 'Usage: $sftp->statvfs($path_or_fh)';
  2702. ${^TAINT} and &_catch_tainted_args;
  2703. my ($sftp, $pofh) = @_;
  2704. my ($extension, $arg) = ( (ref $pofh and UNIVERSAL::isa($pofh, 'Net::SFTP::Foreign::FileHandle'))
  2705. ? ('fstatvfs@openssh.com', $sftp->_rid($pofh) )
  2706. : ('statvfs@openssh.com' , $sftp->_fs_encode($sftp->_rel2abs($pofh)) ) );
  2707. $sftp->_check_extension($extension => 2,
  2708. SFTP_ERR_REMOTE_STATVFS_FAILED,
  2709. "statvfs failed, not implemented")
  2710. or return undef;
  2711. my $id = $sftp->_queue_new_msg(SSH2_FXP_EXTENDED,
  2712. str => $extension,
  2713. str => $arg);
  2714. if (my $msg = $sftp->_get_msg_and_check(SSH2_FXP_EXTENDED_REPLY, $id,
  2715. SFTP_ERR_REMOTE_STATVFS_FAILED,
  2716. "Couldn't stat remote file system")) {
  2717. my %statvfs = map { $_ => $msg->get_int64 } qw(bsize frsize blocks
  2718. bfree bavail files ffree
  2719. favail fsid flag namemax);
  2720. return \%statvfs;
  2721. }
  2722. return undef;
  2723. }
  2724. sub fstatvfs {
  2725. _deprecated "fstatvfs is deprecated and will be removed on the upcomming 2.xx series, "
  2726. . "statvfs method accepts now both file handlers and paths";
  2727. goto &statvfs;
  2728. }
  2729. package Net::SFTP::Foreign::Handle;
  2730. use Tie::Handle;
  2731. our @ISA = qw(Tie::Handle);
  2732. our @CARP_NOT = qw(Net::SFTP::Foreign Tie::Handle);
  2733. my $gen_accessor = sub {
  2734. my $ix = shift;
  2735. sub {
  2736. my $st = *{shift()}{ARRAY};
  2737. if (@_) {
  2738. $st->[$ix] = shift;
  2739. }
  2740. else {
  2741. $st->[$ix]
  2742. }
  2743. }
  2744. };
  2745. my $gen_proxy_method = sub {
  2746. my $method = shift;
  2747. sub {
  2748. my $self = $_[0];
  2749. $self->_check
  2750. or return undef;
  2751. my $sftp = $self->_sftp;
  2752. if (wantarray) {
  2753. my @ret = $sftp->$method(@_);
  2754. $sftp->_set_errno unless @ret;
  2755. return @ret;
  2756. }
  2757. else {
  2758. my $ret = $sftp->$method(@_);
  2759. $sftp->_set_errno unless defined $ret;
  2760. return $ret;
  2761. }
  2762. }
  2763. };
  2764. my $gen_not_supported = sub {
  2765. sub {
  2766. $! = Errno::ENOTSUP();
  2767. undef
  2768. }
  2769. };
  2770. sub TIEHANDLE { return shift }
  2771. # sub UNTIE {}
  2772. sub _new_from_rid {
  2773. my $class = shift;
  2774. my $sftp = shift;
  2775. my $rid = shift;
  2776. my $flags = shift || 0;
  2777. my $self = Symbol::gensym;
  2778. bless $self, $class;
  2779. *$self = [ $sftp, $rid, 0, $flags, @_];
  2780. tie *$self, $self;
  2781. $self;
  2782. }
  2783. sub _close {
  2784. my $self = shift;
  2785. @{*{$self}{ARRAY}} = ();
  2786. }
  2787. sub _check {
  2788. return 1 if defined(*{shift()}{ARRAY}[0]);
  2789. $! = Errno::EBADF;
  2790. undef;
  2791. }
  2792. sub FILENO {
  2793. my $self = shift;
  2794. $self->_check
  2795. or return undef;
  2796. my $hrid = unpack 'H*' => $self->_rid;
  2797. "-1:sftp(0x$hrid)"
  2798. }
  2799. sub _sftp { *{shift()}{ARRAY}[0] }
  2800. sub _rid { *{shift()}{ARRAY}[1] }
  2801. * _pos = $gen_accessor->(2);
  2802. sub _inc_pos {
  2803. my ($self, $inc) = @_;
  2804. *{shift()}{ARRAY}[2] += $inc;
  2805. }
  2806. my %flag_bit = (append => 0x1);
  2807. sub _flag {
  2808. my $st = *{shift()}{ARRAY};
  2809. my $fn = shift;
  2810. my $flag = $flag_bit{$fn};
  2811. Carp::croak("unknown flag $fn") unless defined $flag;
  2812. if (@_) {
  2813. if (shift) {
  2814. $st->[3] |= $flag;
  2815. }
  2816. else {
  2817. $st->[3] &= ~$flag;
  2818. }
  2819. }
  2820. $st->[3] & $flag ? 1 : 0
  2821. }
  2822. sub _check_is_file {
  2823. Carp::croak("expecting remote file handler, got directory handler");
  2824. }
  2825. sub _check_is_dir {
  2826. Carp::croak("expecting remote directory handler, got file handler");
  2827. }
  2828. my $autoloaded;
  2829. sub AUTOLOAD {
  2830. my $self = shift;
  2831. our $AUTOLOAD;
  2832. if ($autoloaded) {
  2833. my $class = ref $self || $self;
  2834. Carp::croak qq|Can't locate object method "$AUTOLOAD" via package "$class|;
  2835. }
  2836. else {
  2837. $autoloaded = 1;
  2838. require IO::File;
  2839. require IO::Dir;
  2840. my ($method) = $AUTOLOAD =~ /^.*::(.*)$/;
  2841. $self->$method(@_);
  2842. }
  2843. }
  2844. package Net::SFTP::Foreign::FileHandle;
  2845. our @ISA = qw(Net::SFTP::Foreign::Handle IO::File);
  2846. sub _new_from_rid {
  2847. my $class = shift;
  2848. my $sftp = shift;
  2849. my $rid = shift;
  2850. my $flags = shift;
  2851. my $self = $class->SUPER::_new_from_rid($sftp, $rid, $flags, '', '');
  2852. }
  2853. sub _check_is_file {}
  2854. sub _bin { \(*{shift()}{ARRAY}[4]) }
  2855. sub _bout { \(*{shift()}{ARRAY}[5]) }
  2856. sub WRITE {
  2857. my ($self, undef, $length, $offset) = @_;
  2858. $self->_check
  2859. or return undef;
  2860. $offset = 0 unless defined $offset;
  2861. $offset = length $_[1] + $offset if $offset < 0;
  2862. $length = length $_[1] unless defined $length;
  2863. my $sftp = $self->_sftp;
  2864. my $ret = $sftp->write($self, substr($_[1], $offset, $length));
  2865. $sftp->_set_errno unless defined $ret;
  2866. $ret;
  2867. }
  2868. sub READ {
  2869. my ($self, undef, $len, $offset) = @_;
  2870. $self->_check
  2871. or return undef;
  2872. $_[1] = '' unless defined $_[1];
  2873. $offset ||= 0;
  2874. if ($offset > length $_[1]) {
  2875. $_[1] .= "\0" x ($offset - length $_[1])
  2876. }
  2877. if ($len == 0) {
  2878. substr($_[1], $offset) = '';
  2879. return 0;
  2880. }
  2881. my $sftp = $self->_sftp;
  2882. $sftp->_fill_read_cache($self, $len);
  2883. my $bin = $self->_bin;
  2884. if (length $$bin) {
  2885. my $data = substr($$bin, 0, $len, '');
  2886. $self->_inc_pos($len);
  2887. substr($_[1], $offset) = $data;
  2888. return length $data;
  2889. }
  2890. return 0 if $sftp->{_status} == $sftp->SSH2_FX_EOF;
  2891. $sftp->_set_errno;
  2892. undef;
  2893. }
  2894. sub EOF {
  2895. my $self = $_[0];
  2896. $self->_check or return undef;
  2897. my $sftp = $self->_sftp;
  2898. my $ret = $sftp->eof($self);
  2899. $sftp->_set_errno unless defined $ret;
  2900. $ret;
  2901. }
  2902. *GETC = $gen_proxy_method->('getc');
  2903. *TELL = $gen_proxy_method->('tell');
  2904. *SEEK = $gen_proxy_method->('seek');
  2905. *CLOSE = $gen_proxy_method->('close');
  2906. my $readline = $gen_proxy_method->('readline');
  2907. sub READLINE { $readline->($_[0], $/) }
  2908. sub OPEN {
  2909. shift->CLOSE;
  2910. undef;
  2911. }
  2912. sub DESTROY {
  2913. local ($@, $!, $?);
  2914. my $self = shift;
  2915. my $sftp = $self->_sftp;
  2916. $debug and $debug & 4 and Net::SFTP::Foreign::_debug("$self->DESTROY called (sftp: ".($sftp||'<undef>').")");
  2917. if ($self->_check and $sftp) {
  2918. local $sftp->{_autodie};
  2919. $sftp->_close_save_status($self)
  2920. }
  2921. }
  2922. package Net::SFTP::Foreign::DirHandle;
  2923. our @ISA = qw(Net::SFTP::Foreign::Handle IO::Dir);
  2924. sub _new_from_rid {
  2925. my $class = shift;
  2926. my $sftp = shift;
  2927. my $rid = shift;
  2928. my $flags = shift;
  2929. my $self = $class->SUPER::_new_from_rid($sftp, $rid, $flags, []);
  2930. }
  2931. sub _check_is_dir {}
  2932. sub _cache { *{shift()}{ARRAY}[4] }
  2933. *CLOSEDIR = $gen_proxy_method->('closedir');
  2934. *READDIR = $gen_proxy_method->('_readdir');
  2935. sub OPENDIR {
  2936. shift->CLOSEDIR;
  2937. undef;
  2938. }
  2939. *REWINDDIR = $gen_not_supported->();
  2940. *TELLDIR = $gen_not_supported->();
  2941. *SEEKDIR = $gen_not_supported->();
  2942. sub DESTROY {
  2943. local ($@, $!, $?);
  2944. my $self = shift;
  2945. my $sftp = $self->_sftp;
  2946. $debug and $debug & 4 and Net::SFTP::Foreign::_debug("$self->DESTROY called (sftp: ".($sftp||'').")");
  2947. if ($self->_check and $sftp) {
  2948. local $sftp->{_autodie};
  2949. $sftp->_closedir_save_status($self)
  2950. }
  2951. }
  2952. 1;
  2953. __END__
  2954. =head1 NAME
  2955. Net::SFTP::Foreign - SSH File Transfer Protocol client
  2956. =head1 SYNOPSIS
  2957. use Net::SFTP::Foreign;
  2958. my $sftp = Net::SFTP::Foreign->new($host);
  2959. $sftp->die_on_error("Unable to establish SFTP connection");
  2960. $sftp->setcwd($path) or die "unable to change cwd: " . $sftp->error;
  2961. $sftp->get("foo", "bar") or die "get failed: " . $sftp->error;
  2962. $sftp->put("bar", "baz") or die "put failed: " . $sftp->error;
  2963. =head1 DESCRIPTION
  2964. SFTP stands for SSH File Transfer Protocol and is a method of
  2965. transferring files between machines over a secure, encrypted
  2966. connection (as opposed to regular FTP, which functions over an
  2967. insecure connection). The security in SFTP comes through its
  2968. integration with SSH, which provides an encrypted transport layer over
  2969. which the SFTP commands are executed.
  2970. Net::SFTP::Foreign is a Perl client for the SFTP version 3 as defined
  2971. in the SSH File Transfer Protocol IETF draft, which can be found at
  2972. L<http://www.openssh.org/txt/draft-ietf-secsh-filexfer-02.txt> (also
  2973. included on this package distribution, on the C<rfc> directory).
  2974. Net::SFTP::Foreign uses any compatible C<ssh> command installed on
  2975. the system (for instance, OpenSSH C<ssh>) to establish the secure
  2976. connection to the remote server.
  2977. A wrapper module L<Net::SFTP::Foreign::Compat> is also provided for
  2978. compatibility with L<Net::SFTP>.
  2979. =head2 Net::SFTP::Foreign Vs. Net::SFTP Vs. Net::SSH2::SFTP
  2980. Why should I prefer Net::SFTP::Foreign over L<Net::SFTP>?
  2981. Well, both modules have their pros and cons:
  2982. Net::SFTP::Foreign does not require a bunch of additional modules and
  2983. external libraries to work, just the OpenBSD SSH client (or any other
  2984. client compatible enough).
  2985. I trust OpenSSH SSH client more than L<Net::SSH::Perl>, there are lots
  2986. of paranoid people ensuring that OpenSSH doesn't have security
  2987. holes!!!
  2988. If you have an SSH infrastructure already deployed, by using the same
  2989. binary SSH client, Net::SFTP::Foreign ensures a seamless integration
  2990. within your environment (configuration files, keys, etc.).
  2991. Net::SFTP::Foreign is much faster transferring files, specially over
  2992. networks with high (relative) latency.
  2993. Net::SFTP::Foreign provides several high level methods not available
  2994. from Net::SFTP as for instance C<find>, C<glob>, C<rget>, C<rput>,
  2995. C<rremove>, C<mget>, C<mput>.
  2996. On the other hand, using the external command means an additional
  2997. process being launched and running, depending on your OS this could
  2998. eat more resources than the in process pure perl implementation
  2999. provided by L<Net::SSH::Perl>.
  3000. L<Net::SSH2> is a module wrapping libssh2, an SSH version 2 client
  3001. library written in C. It is a very active project that aims to replace
  3002. L<Net::SSH::Perl>. Unfortunately, libssh2 SFTP functionality
  3003. (available in Perl via L<Net::SSH2::SFTP>) is rather limited and its
  3004. performance very poor.
  3005. Later versions of Net::SFTP::Foreign can use L<Net::SSH2> as the
  3006. transport layer via the backend module
  3007. L<Net::SFTP::Foreign::Backend::Net_SSH2>.
  3008. =head2 Error handling
  3009. Most of the methods available from this package return undef on
  3010. failure and a true value or the requested data on
  3011. success. C<$sftp-E<gt>error> should be used to check for errors
  3012. explicitly after every method call. For instance:
  3013. $sftp = Net::SFTP::Foreign->new($host);
  3014. $sftp->error and die "unable to connect to remote host: " . $sftp->error;
  3015. Also, the L</die_on_error> method provides a handy shortcut for the last line:
  3016. $sftp = Net::SFTP::Foreign->new($host);
  3017. $sftp->die_on_error("unable to connect to remote host");
  3018. Alternatively, the C<autodie> mode that makes the module die when any
  3019. error is found can be activated from the constructor. For instance:
  3020. $sftp = Net::SFTP::Foreign->new($host, autodie => 1);
  3021. my $ls = $sftp->ls("/bar");
  3022. # dies as: "Couldn't open remote dir '/bar': No such file"
  3023. The C<autodie> mode will be disabled when an C<on_error> handler is
  3024. passed to methods accepting it:
  3025. my $sftp = Net::SFTP::Foreign->new($host, autodie => 1);
  3026. # prints "foo!" and does not die:
  3027. $sftp->find("/sdfjkalshfl", # nonexistent directory
  3028. on_error => sub { print "foo!\n" });
  3029. # dies:
  3030. $sftp->find("/sdfjkalshfl");
  3031. =head2 API
  3032. The methods available from this module are described below.
  3033. Don't forget to read also the FAQ and BUGS sections at the end of this
  3034. document!
  3035. =over 4
  3036. =item Net::SFTP::Foreign->new($host, %args)
  3037. =item Net::SFTP::Foreign->new(%args)
  3038. Opens a new SFTP connection with a remote host C<$host>, and returns a
  3039. Net::SFTP::Foreign object representing that open connection.
  3040. An explicit check for errors should be included always after the
  3041. constructor call:
  3042. my $sftp = Net::SFTP::Foreign->new(...);
  3043. $sftp->die_on_error("SSH connection failed");
  3044. The optional arguments accepted are as follows:
  3045. =over 4
  3046. =item host =E<gt> $hostname
  3047. remote host name
  3048. =item user =E<gt> $username
  3049. username to log in to the remote server. This should be your SSH
  3050. login, and can be empty, in which case the username is drawn from the
  3051. user executing the process.
  3052. =item port =E<gt> $portnumber
  3053. port number where the remote SSH server is listening
  3054. =item ssh1 =E<gt> 1
  3055. use old SSH1 approach for starting the remote SFTP server.
  3056. =item more =E<gt> [@more_ssh_args]
  3057. additional args passed to C<ssh> command.
  3058. For debugging purposes you can run C<ssh> in verbose mode passing it
  3059. the C<-v> option:
  3060. my $sftp = Net::SFTP::Foreign->new($host, more => '-v');
  3061. Note that this option expects a single command argument or a reference
  3062. to an array of arguments. For instance:
  3063. more => '-v' # right
  3064. more => ['-v'] # right
  3065. more => "-c $cipher" # wrong!!!
  3066. more => [-c => $cipher] # right
  3067. =item timeout =E<gt> $seconds
  3068. when this parameter is set, the connection is dropped if no data
  3069. arrives on the SSH socket for the given time while waiting for some
  3070. command to complete.
  3071. When the timeout expires, the current method is aborted and
  3072. the SFTP connection becomes invalid.
  3073. Note that the given value is used internally to time out low level
  3074. operations. The high level operations available through the API may
  3075. take longer to expire (sometimes up to 4 times longer).
  3076. =item fs_encoding =E<gt> $encoding
  3077. Version 3 of the SFTP protocol (the one supported by this module)
  3078. knows nothing about the character encoding used on the remote
  3079. filesystem to represent file and directory names.
  3080. This option allows one to select the encoding used in the remote
  3081. machine. The default value is C<utf8>.
  3082. For instance:
  3083. $sftp = Net::SFTP::Foreign->new('user@host', fs_encoding => 'latin1');
  3084. will convert any path name passed to any method in this package to its
  3085. C<latin1> representation before sending it to the remote side.
  3086. Note that this option will not affect file contents in any way.
  3087. This feature is not supported in perl 5.6 due to incomplete Unicode
  3088. support in the interpreter.
  3089. =item key_path =E<gt> $filename
  3090. =item key_path =E<gt> \@filenames
  3091. asks C<ssh> to use the key(s) in the given file(s) for authentication.
  3092. =item password =E<gt> $password
  3093. Logs into the remote host using password authentication with the given
  3094. password.
  3095. Password authentication is only available if the module L<IO::Pty> is
  3096. installed. Note also, that on Windows this module is only available
  3097. when running the Cygwin port of Perl.
  3098. =item asks_for_username_at_login =E<gt> 0|'auto'|1
  3099. During the interactive authentication dialog, most SSH servers only
  3100. ask for the user password as the login name is passed inside the SSH
  3101. protocol. But under some uncommon servers or configurations it is
  3102. possible that a username is also requested.
  3103. When this flag is set to C<1>, the username will be send
  3104. unconditionally at the first remote prompt and then the password at
  3105. the second.
  3106. When it is set to C<auto> the module will use some heuristics in order
  3107. to determine if it is being asked for an username.
  3108. When set to C<0>, the username will never be sent during the
  3109. authentication dialog. This is the default.
  3110. =item password_prompt => $regex_or_str
  3111. The module expects the password prompt from the remote server to end
  3112. in a colon or a question mark. This seems to cover correctly 99% of
  3113. real life cases.
  3114. Otherwise this option can be used to handle the exceptional cases. For
  3115. instance:
  3116. $sftp = Net::SFTP::Foreign->new($host, password => $password,
  3117. password_prompt => qr/\bpassword>\s*$/);
  3118. Note that your script will hang at the login phase if the wrong prompt
  3119. is used.
  3120. =item passphrase =E<gt> $passphrase
  3121. Logs into the remote server using a passphrase protected private key.
  3122. Requires also the module L<IO::Pty>.
  3123. =item expect_log_user =E<gt> $bool
  3124. This feature is obsolete as Expect is not used anymore to handle
  3125. password authentication.
  3126. =item ssh_cmd =E<gt> $sshcmd
  3127. =item ssh_cmd =E<gt> \@sshcmd
  3128. name of the external SSH client. By default C<ssh> is used.
  3129. For instance:
  3130. $sftp = Net::SFTP::Foreign->new($host, ssh_cmd => 'plink');
  3131. When an array reference is used, its elements are inserted at the
  3132. beginning of the system call. That allows, for instance, to connect to
  3133. the target host through some SSH proxy:
  3134. $sftp = Net::SFTP::Foreign->new($host,
  3135. ssh_cmd => qw(ssh -l user proxy.server ssh));
  3136. But note that the module will not handle password authentication for
  3137. those proxies.
  3138. =item ssh_cmd_interface =E<gt> 'plink' or 'ssh' or 'tectia'
  3139. declares the command line interface that the SSH client used to
  3140. connect to the remote host understands. Currently C<plink>, C<ssh> and
  3141. C<tectia> are supported.
  3142. This option would be rarely required as the module infers the
  3143. interface from the SSH command name.
  3144. =item transport =E<gt> $fh
  3145. =item transport =E<gt> [$in_fh, $out_fh]
  3146. =item transport =E<gt> [$in_fh, $out_fh, $pid]
  3147. allows one to use an already open pipe or socket as the transport for
  3148. the SFTP protocol.
  3149. It can be (ab)used to make this module work with password
  3150. authentication or with keys requiring a passphrase.
  3151. C<in_fh> is the file handler used to read data from the remote server,
  3152. C<out_fh> is the file handler used to write data.
  3153. On some systems, when using a pipe as the transport, closing it, does
  3154. not cause the process at the other side to exit. The additional
  3155. C<$pid> argument can be used to instruct this module to kill that
  3156. process if it doesn't exit by itself.
  3157. =item open2_cmd =E<gt> [@cmd]
  3158. =item open2_cmd =E<gt> $cmd;
  3159. allows one to completely redefine how C<ssh> is called. Its arguments
  3160. are passed to L<IPC::Open2::open2> to open a pipe to the remote
  3161. server.
  3162. =item stderr_fh =E<gt> $fh
  3163. redirects the output sent to stderr by the SSH subprocess to the given
  3164. file handle.
  3165. It can be used to suppress banners:
  3166. open my $ssherr, '>', '/dev/null' or die "unable to open /dev/null";
  3167. my $sftp = Net::SFTP::Foreign->new($host,
  3168. stderr_fh => $ssherr);
  3169. Or to send SSH stderr to a file in order to capture errors for later
  3170. analysis:
  3171. my $ssherr = File::Temp->new or die "File::Temp->new failed";
  3172. my $sftp = Net::SFTP::Foreign->new($hostname, more => ['-v'],
  3173. stderr_fh => $ssherr);
  3174. if ($sftp->error) {
  3175. print "sftp error: ".$sftp->error."\n";
  3176. seek($ssherr, 0, 0);
  3177. while (<$ssherr>) {
  3178. print "captured stderr: $_";
  3179. }
  3180. }
  3181. =item stderr_discard =E<gt> 1
  3182. redirects stderr to /dev/null
  3183. =item block_size =E<gt> $default_block_size
  3184. =item queue_size =E<gt> $default_queue_size
  3185. default C<block_size> and C<queue_size> used for read and write
  3186. operations (see the C<put> or C<get> documentation).
  3187. =item autoflush =E<gt> $bool
  3188. by default, and for performance reasons, write operations are cached,
  3189. and only when the write buffer becomes big enough is the data written to
  3190. the remote file. Setting this flag makes the write operations immediate.
  3191. =item write_delay =E<gt> $bytes
  3192. This option determines how many bytes are buffered before the real
  3193. SFTP write operation is performed.
  3194. =item read_ahead =E<gt> $bytes
  3195. On read operations this option determines how many bytes to read in
  3196. advance so that later read operations can be fulfilled from the
  3197. buffer.
  3198. Using a high value will increase the performance of the module for a
  3199. sequential reads access pattern but degrade it for a short random
  3200. reads access pattern. It can also cause synchronization problems if
  3201. the file is concurrently modified by other parties (L</flush> can be
  3202. used to discard all the data inside the read buffer on demand).
  3203. The default value is set dynamically considering some runtime
  3204. parameters and given options, though it tends to favor the sequential
  3205. read access pattern.
  3206. =item autodisconnect =E<gt> $ad
  3207. by default, the SSH connection is closed from the DESTROY method when
  3208. the object goes out of scope. But on scripts that fork new processes,
  3209. that results on the SSH connection being closed by the first process
  3210. where the object goes out of scope, something undesirable.
  3211. This option allows one to work-around this issue to some extend.
  3212. The acceptable values for C<$ad> are:
  3213. =over 4
  3214. =item '0'
  3215. Never try to disconnect this object when exiting from any process.
  3216. On most operating systems, the SSH process will exit when the last
  3217. process connected to it ends, but this is not guaranteed.
  3218. =item '1'
  3219. Disconnect on exit from any process. This is the default.
  3220. =item '2'
  3221. Disconnect on exit from the current process only.
  3222. =back
  3223. See also the C<disconnect> and C<autodisconnect> methods.
  3224. =item late_set_perm =E<gt> $bool
  3225. See the FAQ below.
  3226. =item dirty_cleanup =E<gt> $bool
  3227. Sets the C<dirty_cleanup> flag in a per object basis (see the BUGS
  3228. section).
  3229. =item backend => $backend
  3230. From version 1.57 Net::SFTP::Foreign supports plugable backends in
  3231. order to allow other ways to communicate with the remote server in
  3232. addition to the default I<pipe-to-ssh-process>.
  3233. Custom backends may change the set of options supported by the C<new>
  3234. method.
  3235. =item autodie => $bool
  3236. Enables the autodie mode that will cause the module to die when any
  3237. error is found (a la L<autodie>).
  3238. =back
  3239. =item $sftp-E<gt>error
  3240. Returns the error code from the last executed command. The value
  3241. returned is similar to C<$!>, when used as a string it yields the
  3242. corresponding error string.
  3243. See L<Net::SFTP::Foreign::Constants> for a list of possible error
  3244. codes and how to import them on your scripts.
  3245. =item $sftp-E<gt>die_on_error($msg)
  3246. Convenience method:
  3247. $sftp->die_on_error("Something bad happened");
  3248. # is a shortcut for...
  3249. $sftp->error and die "Something bad happened: " . $sftp->error;
  3250. =item $sftp-E<gt>status
  3251. Returns the code from the last SSH2_FXP_STATUS response. It is also a
  3252. dualvar that yields the status string when used as a string.
  3253. Usually C<$sftp-E<gt>error> should be checked first to see if there was
  3254. any error and then C<$sftp-E<gt>status> to find out its low level cause.
  3255. =item $sftp-E<gt>cwd
  3256. Returns the remote current working directory.
  3257. When a relative remote path is passed to any of the methods on this
  3258. package, this directory is used to compose the absolute path.
  3259. =item $sftp-E<gt>setcwd($dir, %opts)
  3260. Changes the remote current working directory. The remote directory
  3261. should exist, otherwise the call fails.
  3262. Returns the new remote current working directory or undef on failure.
  3263. Passing C<undef> as the C<$dir> argument resets the cwd to the server
  3264. default which is usually the user home but not always.
  3265. The method accepts the following options:
  3266. =over 4
  3267. =item check => 0
  3268. By default the given target directory is checked against the remote
  3269. server to ensure that it actually exists and that it is a
  3270. directory. Some servers may fail to honor those requests even for
  3271. valid directories (i.e. when the directory has the hidden flag set).
  3272. This option allows to disable those checks and just sets the cwd to
  3273. the given value blindly.
  3274. =back
  3275. =item $sftp-E<gt>get($remote, $local, %options)
  3276. X<get>Copies remote file C<$remote> to local $local. By default file
  3277. attributes are also copied (permissions, atime and mtime). For
  3278. instance:
  3279. $sftp->get('/var/log/messages', /tmp/messages')
  3280. or die "file transfer failed: " . $sftp->error;
  3281. A file handle can also be used as the local target. In that case, the
  3282. remote file contents are retrieved and written to the given file
  3283. handle. Note also that the handle is not closed when the transmission
  3284. finish.
  3285. open F, '| gzip -c > /tmp/foo' or die ...;
  3286. $sftp->get("/etc/passwd", \*F)
  3287. or die "get failed: " . $sftp->error;
  3288. close F or die ...;
  3289. Accepted options (not all combinations are possible):
  3290. =over 4
  3291. =item copy_time =E<gt> $bool
  3292. determines if access and modification time attributes have to be
  3293. copied from remote file. Default is to copy them.
  3294. =item copy_perm =E<gt> $bool
  3295. determines if permission attributes have to be copied from remote
  3296. file. Default is to copy them after applying the local process umask.
  3297. =item umask =E<gt> $umask
  3298. allows one to select the umask to apply when setting the permissions
  3299. of the copied file. Default is to use the umask for the current
  3300. process or C<0> if the C<perm> option is also used.
  3301. =item perm =E<gt> $perm
  3302. sets the permission mask of the file to be $perm, remote
  3303. permissions are ignored.
  3304. =item resume =E<gt> 1 | 'auto'
  3305. resumes an interrupted transfer.
  3306. If the C<auto> value is given, the transfer will be resumed only when
  3307. the local file is newer than the remote one.
  3308. C<get> transfers can not be resumed when a data conversion is in
  3309. place.
  3310. =item append =E<gt> 1
  3311. appends the contents of the remote file at the end of the local one
  3312. instead of overwriting it. If the local file does not exist a new one
  3313. is created.
  3314. =item overwrite =E<gt> 0
  3315. setting this option to zero cancels the transfer when a local file of
  3316. the same name already exists.
  3317. =item numbered =E<gt> 1
  3318. modifies the local file name inserting a sequence number when required
  3319. in order to avoid overwriting local files.
  3320. For instance:
  3321. for (1..2) {
  3322. $sftp->get("data.txt", "data.txt", numbered => 1);
  3323. }
  3324. will copy the remote file as C<data.txt> the first time and as
  3325. C<data(1).txt> the second one.
  3326. If a scalar reference is passed as the numbered value, the final
  3327. target will be stored in the value pointed by the reference. For
  3328. instance:
  3329. my $target;
  3330. $sftp->get("data.txt", "data.txt", numbered => \$target);
  3331. say "file was saved as $target" unless $sftp->error
  3332. =item atomic =E<gt> 1
  3333. The remote file contents are transferred into a temporal file that
  3334. once the copy completes is renamed to the target destination.
  3335. If not-overwrite of remote files is also requested, an empty file may
  3336. appear at the target destination before the rename operation is
  3337. performed. This is due to limitations of some operating/file systems.
  3338. =item mkpath =E<gt> 0
  3339. By default the method creates any non-existent parent directory for
  3340. the given target path. That feature can be disabled setting this flag
  3341. to 0.
  3342. =item cleanup =E<gt> 1
  3343. If the transfer fails, remove the incomplete file.
  3344. This option is set to by default when there is not possible to resume
  3345. the transfer afterwards (i.e., when using `atomic` or `numbered`
  3346. options).
  3347. =item best_effort =E<gt> 1
  3348. Ignore minor errors as setting time or permissions.
  3349. =item conversion =E<gt> $conversion
  3350. on the fly data conversion of the file contents can be performed with
  3351. this option. See L</On the fly data conversion> below.
  3352. =item callback =E<gt> $callback
  3353. C<$callback> is a reference to a subroutine that will be called after
  3354. every iteration of the download process.
  3355. The callback function will receive as arguments: the current
  3356. Net::SFTP::Foreign object; the data read from the remote file; the
  3357. offset from the beginning of the file in bytes; and the total size of
  3358. the file in bytes.
  3359. This mechanism can be used to provide status messages, download
  3360. progress meters, etc.:
  3361. sub callback {
  3362. my($sftp, $data, $offset, $size) = @_;
  3363. print "Read $offset / $size bytes\r";
  3364. }
  3365. The C<abort> method can be called from inside the callback to abort
  3366. the transfer:
  3367. sub callback {
  3368. my($sftp, $data, $offset, $size) = @_;
  3369. if (want_to_abort_transfer()) {
  3370. $sftp->abort("You wanted to abort the transfer");
  3371. }
  3372. }
  3373. The callback will be called one last time with an empty data argument
  3374. to indicate the end of the file transfer.
  3375. The size argument can change between different calls as data is
  3376. transferred (for instance, when on-the-fly data conversion is being
  3377. performed or when the size of the file can not be retrieved with the
  3378. C<stat> SFTP command before the data transfer starts).
  3379. =item block_size =E<gt> $bytes
  3380. size of the blocks the file is being split on for transfer.
  3381. Incrementing this value can improve performance but most servers limit
  3382. the maximum size.
  3383. =item queue_size =E<gt> $size
  3384. read and write requests are pipelined in order to maximize transfer
  3385. throughput. This option allows one to set the maximum number of
  3386. requests that can be concurrently waiting for a server response.
  3387. =back
  3388. =item $sftp-E<gt>get_content($remote)
  3389. Returns the content of the remote file.
  3390. =item $sftp-E<gt>get_symlink($remote, $local, %opts)
  3391. copies a symlink from the remote server to the local file system
  3392. The accepted options are C<overwrite> and C<numbered>. They have the
  3393. same effect as for the C<get> method.
  3394. =item $sftp-E<gt>put($local, $remote, %opts)
  3395. Uploads a file C<$local> from the local host to the remote host saving
  3396. it as C<$remote>. By default file attributes are also copied. For
  3397. instance:
  3398. $sftp->put("test.txt", "test.txt")
  3399. or die "put failed: " . $sftp->error;
  3400. A file handle can also be passed in the C<$local> argument. In that
  3401. case, data is read from there and stored in the remote file. UTF8 data
  3402. is not supported unless a custom converter callback is used to
  3403. transform it to bytes. The method will croak if it encounters any data
  3404. in perl internal UTF8 format. Note also that the handle is not closed
  3405. when the transmission finish.
  3406. Example:
  3407. binmode STDIN;
  3408. $sftp->put(\*STDIN, "stdin.dat") or die "put failed";
  3409. close STDIN;
  3410. This method accepts several options:
  3411. =over 4
  3412. =item copy_time =E<gt> $bool
  3413. determines if access and modification time attributes have to be
  3414. copied from remote file. Default is to copy them.
  3415. =item copy_perm =E<gt> $bool
  3416. determines if permission attributes have to be copied from remote
  3417. file. Default is to copy them after applying the local process umask.
  3418. =item umask =E<gt> $umask
  3419. allows one to select the umask to apply when setting the permissions
  3420. of the copied file. Default is to use the umask for the current
  3421. process.
  3422. =item perm =E<gt> $perm
  3423. sets the permission mask of the file to be $perm, umask and local
  3424. permissions are ignored.
  3425. =item overwrite =E<gt> 0
  3426. by default C<put> will overwrite any pre-existent file with the same
  3427. name at the remote side. Setting this flag to zero will make the
  3428. method fail in that case.
  3429. =item numbered =E<gt> 1
  3430. when set, a sequence number is added to the remote file name in order
  3431. to avoid overwriting pre-existent files. Off by default.
  3432. =item append =E<gt> 1
  3433. appends the local file at the end of the remote file instead of
  3434. overwriting it. If the remote file does not exist a new one is
  3435. created. Off by default.
  3436. =item resume =E<gt> 1 | 'auto'
  3437. resumes an interrupted transfer.
  3438. If the C<auto> value is given, the transfer will be resumed only when
  3439. the remote file is newer than the local one.
  3440. =item sparse =E<gt> 1
  3441. Blocks that are all zeros are skipped possibly creating an sparse file
  3442. on the remote host.
  3443. =item mkpath =E<gt> 0
  3444. By default the method creates any non-existent parent directory for
  3445. the given target path. That feature can be disabled setting this flag
  3446. to 0.
  3447. =item atomic =E<gt> 1
  3448. The local file contents are transferred into a temporal file that
  3449. once the copy completes is renamed to the target destination.
  3450. This operation relies on the SSH server to perform an
  3451. overwriting/non-overwriting atomic rename operation free of race
  3452. conditions.
  3453. OpenSSH server does it correctly on top of Linux/UNIX native file
  3454. systems (i.e. ext[234]>, ffs or zfs) but has problems on file systems
  3455. not supporting hard links (i.e. FAT) or on operating systems with
  3456. broken POSIX semantics as Windows.
  3457. =item cleanup =E<gt> 1
  3458. If the transfer fails, attempts to remove the incomplete file. Cleanup
  3459. may fail (for example, if the SSH connection gets broken).
  3460. This option is set by default when the transfer is not resumable
  3461. (i.e., when using `atomic` or `numbered` options).
  3462. =item best_effort =E<gt> 1
  3463. Ignore minor errors, as setting time and permissions on the remote
  3464. file.
  3465. =item conversion =E<gt> $conversion
  3466. on the fly data conversion of the file contents can be performed with
  3467. this option. See L</On the fly data conversion> below.
  3468. =item callback =E<gt> $callback
  3469. C<$callback> is a reference to a subroutine that will be called after
  3470. every iteration of the upload process.
  3471. The callback function will receive as arguments: the current
  3472. Net::SFTP::Foreign object; the data that is going to be written to the
  3473. remote file; the offset from the beginning of the file in bytes; and
  3474. the total size of the file in bytes.
  3475. The callback will be called one last time with an empty data argument
  3476. to indicate the end of the file transfer.
  3477. The size argument can change between calls as data is transferred (for
  3478. instance, when on the fly data conversion is being performed).
  3479. This mechanism can be used to provide status messages, download
  3480. progress meters, etc.
  3481. The C<abort> method can be called from inside the callback to abort
  3482. the transfer.
  3483. =item block_size =E<gt> $bytes
  3484. size of the blocks the file is being split on for transfer.
  3485. Incrementing this value can improve performance but some servers limit
  3486. its size and if this limit is overpassed the command will fail.
  3487. =item queue_size =E<gt> $size
  3488. read and write requests are pipelined in order to maximize transfer
  3489. throughput. This option allows one to set the maximum number of
  3490. requests that can be concurrently waiting for a server response.
  3491. =item late_set_perm =E<gt> $bool
  3492. See the FAQ below.
  3493. =back
  3494. =item $sftp-E<gt>put_content($bytes, $remote, %opts)
  3495. Creates (or overwrites) a remote file whose content is the passed
  3496. data.
  3497. =item $sftp-E<gt>put_symlink($local, $remote, %opts)
  3498. Copies a local symlink to the remote host.
  3499. The accepted options are C<overwrite> and C<numbered>.
  3500. =item $sftp-E<gt>abort()
  3501. =item $sftp-E<gt>abort($msg)
  3502. This method, when called from inside a callback sub, causes the
  3503. current transfer to be aborted
  3504. The error state is set to SFTP_ERR_ABORTED and the optional $msg
  3505. argument is used as its textual value.
  3506. =item $sftp-E<gt>ls($remote, %opts)
  3507. Fetches a listing of the remote directory C<$remote>. If C<$remote> is
  3508. not given, the current remote working directory is listed.
  3509. Returns a reference to a list of entries. Every entry is a reference
  3510. to a hash with three keys: C<filename>, the name of the entry;
  3511. C<longname>, an entry in a "long" listing like C<ls -l>; and C<a>, a
  3512. L<Net::SFTP::Foreign::Attributes> object containing file atime, mtime,
  3513. permissions and size.
  3514. my $ls = $sftp->ls('/home/foo')
  3515. or die "unable to retrieve directory: ".$sftp->error;
  3516. print "$_->{filename}\n" for (@$ls);
  3517. The options accepted by this method are as follows (note that usage of
  3518. some of them can degrade the method performance when reading large
  3519. directories):
  3520. =over 4
  3521. =item wanted =E<gt> qr/.../
  3522. Only elements whose name matches the given regular expression are
  3523. included on the listing.
  3524. =item wanted =E<gt> sub {...}
  3525. Only elements for which the callback returns a true value are included
  3526. on the listing. The callback is called with two arguments: the
  3527. C<$sftp> object and the current entry (a hash reference as described
  3528. before). For instance:
  3529. use Fcntl ':mode';
  3530. my $files = $sftp->ls ( '/home/hommer',
  3531. wanted => sub {
  3532. my $entry = $_[1];
  3533. S_ISREG($entry->{a}->perm)
  3534. } )
  3535. or die "ls failed: ".$sftp->error;
  3536. =item no_wanted =E<gt> qr/.../
  3537. =item no_wanted =E<gt> sub {...}
  3538. those options have the opposite result to their C<wanted> counterparts:
  3539. my $no_hidden = $sftp->ls( '/home/homer',
  3540. no_wanted => qr/^\./ )
  3541. or die "ls failed";
  3542. When both C<no_wanted> and C<wanted> rules are used, the C<no_wanted>
  3543. rule is applied first and then the C<wanted> one (order is important
  3544. if the callbacks have side effects, experiment!).
  3545. =item ordered =E<gt> 1
  3546. the list of entries is ordered by filename.
  3547. =item follow_links =E<gt> 1
  3548. by default, the attributes on the listing correspond to a C<lstat>
  3549. operation, setting this option causes the method to perform C<stat>
  3550. requests instead. C<lstat> attributes will still appear for links
  3551. pointing to non existent places.
  3552. =item atomic_readdir =E<gt> 1
  3553. reading a directory is not an atomic SFTP operation and the protocol
  3554. draft does not define what happens if C<readdir> requests and write
  3555. operations (for instance C<remove> or C<open>) affecting the same
  3556. directory are intermixed.
  3557. This flag ensures that no callback call (C<wanted>, C<no_wanted>) is
  3558. performed in the middle of reading a directory and has to be set if
  3559. any of the callbacks can modify the file system.
  3560. =item realpath =E<gt> 1
  3561. for every file object, performs a realpath operation and populates the
  3562. C<realpath> entry.
  3563. =item names_only =E<gt> 1
  3564. makes the method return a simple array containing the file names from
  3565. the remote directory only. For instance, these two sentences are
  3566. equivalent:
  3567. my @ls1 = @{ $sftp->ls('.', names_only => 1) };
  3568. my @ls2 = map { $_->{filename} } @{$sftp->ls('.')};
  3569. =back
  3570. =item $sftp-E<gt>find($path, %opts)
  3571. =item $sftp-E<gt>find(\@paths, %opts)
  3572. X<find>Does a recursive search over the given directory C<$path> (or
  3573. directories C<@path>) and returns a list of the entries found or the
  3574. total number of them on scalar context.
  3575. Every entry is a reference to a hash with two keys: C<filename>, the
  3576. full path of the entry; and C<a>, a L<Net::SFTP::Foreign::Attributes>
  3577. object containing file atime, mtime, permissions and size.
  3578. This method tries to recover and continue under error conditions.
  3579. The options accepted:
  3580. =over 4
  3581. =item on_error =E<gt> sub { ... }
  3582. the callback is called when some error is detected, two arguments are
  3583. passed: the C<$sftp> object and the entry that was being processed
  3584. when the error happened. For instance:
  3585. my @find = $sftp->find( '/',
  3586. on_error => sub {
  3587. my ($sftp, $e) = @_;
  3588. print STDERR "error processing $e->{filename}: "
  3589. . $sftp->error;
  3590. } );
  3591. =item realpath =E<gt> 1
  3592. calls method C<realpath> for every entry, the result is stored under
  3593. the key C<realpath>. This option slows down the process as a new
  3594. remote query is performed for every entry, specially on networks with
  3595. high latency.
  3596. =item follow_links =E<gt> 1
  3597. By default symbolic links are not resolved and appear as that on the
  3598. final listing. This option causes then to be resolved and substituted
  3599. by the target file system object. Dangling links are ignored, though
  3600. they generate a call to the C<on_error> callback when stat fails on
  3601. them.
  3602. Following symbolic links can introduce loops on the search. Infinite
  3603. loops are detected and broken but files can still appear repeated on
  3604. the final listing under different names unless the option C<realpath>
  3605. is also active.
  3606. =item ordered =E<gt> 1
  3607. By default, the file system is searched in an implementation dependent
  3608. order (actually optimized for low memory consumption). If this option
  3609. is included, the file system is searched in a deep-first, sorted by
  3610. filename fashion.
  3611. =item wanted =E<gt> qr/.../
  3612. =item wanted =E<gt> sub { ... }
  3613. =item no_wanted =E<gt> qr/.../
  3614. =item no_wanted =E<gt> sub { ... }
  3615. These options have the same effect as on the C<ls> method, allowing to
  3616. filter out unwanted entries (note that filename keys contain B<full
  3617. paths> here).
  3618. The callbacks can also be used to perform some action instead of
  3619. creating the full listing of entries in memory (that could use huge
  3620. amounts of RAM for big file trees):
  3621. $sftp->find($src_dir,
  3622. wanted => sub {
  3623. my $fn = $_[1]->{filename}
  3624. print "$fn\n" if $fn =~ /\.p[ml]$/;
  3625. return undef # so it is discarded
  3626. });
  3627. =item descend =E<gt> qr/.../
  3628. =item descend =E<gt> sub { ... }
  3629. =item no_descend =E<gt> qr/.../
  3630. =item no_descend =E<gt> sub { ... }
  3631. These options, similar to the C<wanted> ones, allow to prune the
  3632. search, discarding full subdirectories. For instance:
  3633. use Fcntl ':mode';
  3634. my @files = $sftp->find( '.',
  3635. no_descend => qr/\.svn$/,
  3636. wanted => sub {
  3637. S_ISREG($_[1]->{a}->perm)
  3638. } );
  3639. C<descend> and C<wanted> rules are unrelated. A directory discarded by
  3640. a C<wanted> rule will still be recursively searched unless it is also
  3641. discarded on a C<descend> rule and vice versa.
  3642. =item atomic_readdir =E<gt> 1
  3643. see C<ls> method documentation.
  3644. =item names_only =E<gt> 1
  3645. makes the method return a list with the names of the files only (see C<ls>
  3646. method documentation).
  3647. equivalent:
  3648. my $ls1 = $sftp->ls('.', names_only => 1);
  3649. =back
  3650. =item $sftp-E<gt>glob($pattern, %opts)
  3651. X<glob>performs a remote glob and returns the list of matching entries
  3652. in the same format as the L</find> method.
  3653. This method tries to recover and continue under error conditions.
  3654. The given pattern can be a UNIX style pattern (see L<glob(7)>) or a
  3655. Regexp object (i.e C<qr/foo/>). In the later case, only files on the
  3656. current working directory will be matched against the Regexp.
  3657. Accepted options:
  3658. =over 4
  3659. =item ignore_case =E<gt> 1
  3660. by default the matching over the file system is carried out in a case
  3661. sensitive fashion, this flag changes it to be case insensitive.
  3662. This flag is ignored when a Regexp object is used as the pattern.
  3663. =item strict_leading_dot =E<gt> 0
  3664. by default, a dot character at the beginning of a file or directory
  3665. name is not matched by wildcards (C<*> or C<?>). Setting this flags to
  3666. a false value changes this behaviour.
  3667. This flag is ignored when a Regexp object is used as the pattern.
  3668. =item follow_links =E<gt> 1
  3669. =item ordered =E<gt> 1
  3670. =item names_only =E<gt> 1
  3671. =item realpath =E<gt> 1
  3672. =item on_error =E<gt> sub { ... }
  3673. =item wanted =E<gt> ...
  3674. =item no_wanted =E<gt> ...
  3675. these options perform as on the C<ls> method.
  3676. =back
  3677. Some usage samples:
  3678. my $files = $sftp->glob("*/lib");
  3679. my $files = $sftp->glob("/var/log/dmesg.*.gz");
  3680. $sftp->set_cwd("/var/log");
  3681. my $files = $sftp->glob(qr/^dmesg\.[\d+]\.gz$/);
  3682. my $files = $sftp->glob("*/*.pdf", strict_leading_dot => 0);
  3683. =item $sftp-E<gt>rget($remote, $local, %opts)
  3684. Recursively copies the contents of remote directory C<$remote> to
  3685. local directory C<$local>. Returns the total number of elements
  3686. (files, directories and symbolic links) successfully copied.
  3687. This method tries to recover and continue when some error happens.
  3688. The options accepted are:
  3689. =over 4
  3690. =item umask =E<gt> $umask
  3691. use umask C<$umask> to set permissions on the files and directories
  3692. created.
  3693. =item copy_perm =E<gt> $bool;
  3694. if set to a true value, file and directory permissions are copied to
  3695. the remote server (after applying the umask). On by default.
  3696. =item copy_time =E<gt> $bool;
  3697. if set to a true value, file atime and mtime are copied from the
  3698. remote server. By default it is on.
  3699. =item overwrite =E<gt> $bool
  3700. if set to a true value, when a local file with the same name
  3701. already exists it is overwritten. On by default.
  3702. =item numbered =E<gt> $bool
  3703. when required, adds a sequence number to local file names in order to
  3704. avoid overwriting pre-existent remote files. Off by default.
  3705. =item newer_only =E<gt> $bool
  3706. if set to a true value, when a local file with the same name
  3707. already exists it is overwritten only if the remote file is newer.
  3708. =item ignore_links =E<gt> $bool
  3709. if set to a true value, symbolic links are not copied.
  3710. =item on_error =E<gt> sub { ... }
  3711. the passed sub is called when some error happens. It is called with two
  3712. arguments, the C<$sftp> object and the entry causing the error.
  3713. =item wanted =E<gt> ...
  3714. =item no_wanted =E<gt> ...
  3715. This option allows one to select which files and directories have to
  3716. be copied. See also C<ls> method docs.
  3717. If a directory is discarded all of its contents are also discarded (as
  3718. it is not possible to copy child files without creating the directory
  3719. first!).
  3720. =item atomic =E<gt> 1
  3721. =item block_size =E<gt> $block_size
  3722. =item queue_size =E<gt> $queue_size
  3723. =item conversion =E<gt> $conversion
  3724. =item resume =E<gt> $resume
  3725. =item best_effort =E<gt> $best_effort
  3726. See C<get> method docs.
  3727. =back
  3728. =item $sftp-E<gt>rput($local, $remote, %opts)
  3729. Recursively copies the contents of local directory C<$local> to
  3730. remote directory C<$remote>.
  3731. This method tries to recover and continue when some error happens.
  3732. Accepted options are:
  3733. =over 4
  3734. =item umask =E<gt> $umask
  3735. use umask C<$umask> to set permissions on the files and directories
  3736. created.
  3737. =item copy_perm =E<gt> $bool;
  3738. if set to a true value, file and directory permissions are copied
  3739. to the remote server (after applying the umask). On by default.
  3740. =item copy_time =E<gt> $bool;
  3741. if set to a true value, file atime and mtime are copied to the
  3742. remote server. On by default.
  3743. =item perm =E<gt> $perm
  3744. Sets the permission of the copied files to $perm. For directories the
  3745. value C<$perm|0300> is used.
  3746. Note that when this option is used, umask and local permissions are
  3747. ignored.
  3748. =item overwrite =E<gt> $bool
  3749. if set to a true value, when a remote file with the same name already
  3750. exists it is overwritten. On by default.
  3751. =item newer_only =E<gt> $bool
  3752. if set to a true value, when a remote file with the same name already
  3753. exists it is overwritten only if the local file is newer.
  3754. =item ignore_links =E<gt> $bool
  3755. if set to a true value, symbolic links are not copied
  3756. =item on_error =E<gt> sub { ... }
  3757. the passed sub is called when some error happens. It is called with two
  3758. arguments, the C<$sftp> object and the entry causing the error.
  3759. =item wanted =E<gt> ...
  3760. =item no_wanted =E<gt> ...
  3761. This option allows one to select which files and directories have to
  3762. be copied. See also C<ls> method docs.
  3763. If a directory is discarded all of its contents are also discarded (as
  3764. it is not possible to copy child files without creating the directory
  3765. first!).
  3766. =item atomic =E<gt> 1
  3767. =item block_size =E<gt> $block_size
  3768. =item queue_size =E<gt> $queue_size
  3769. =item conversion =E<gt> $conversion
  3770. =item resume =E<gt> $resume
  3771. =item best_effort =E<gt> $best_effort
  3772. =item late_set_perm =E<gt> $bool
  3773. see C<put> method docs.
  3774. =back
  3775. =item $sftp-E<gt>rremove($dir, %opts)
  3776. =item $sftp-E<gt>rremove(\@dirs, %opts)
  3777. recursively remove directory $dir (or directories @dirs) and its
  3778. contents. Returns the number of elements successfully removed.
  3779. This method tries to recover and continue when some error happens.
  3780. The options accepted are:
  3781. =over 4
  3782. =item on_error =E<gt> sub { ... }
  3783. This callback is called when some error is occurs. The arguments
  3784. passed are the C<$sftp> object and the current entry (see C<ls> docs
  3785. for more information).
  3786. =item wanted =E<gt> ...
  3787. =item no_wanted =E<gt> ...
  3788. Allow to select which file system objects have to be deleted.
  3789. =back
  3790. =item $sftp-E<gt>mget($remote, $localdir, %opts)
  3791. =item $sftp-E<gt>mget(\@remote, $localdir, %opts)
  3792. X<mget>expands the wildcards on C<$remote> or C<@remote> and retrieves
  3793. all the matching files.
  3794. For instance:
  3795. $sftp->mget(['/etc/hostname.*', '/etc/init.d/*'], '/tmp');
  3796. The method accepts all the options valid for L</glob> and for L</get>
  3797. (except those that do not make sense :-)
  3798. C<$localdir> is optional and defaults to the process current working
  3799. directory (C<cwd>).
  3800. Files are saved with the same name they have in the remote server
  3801. excluding the directory parts.
  3802. Note that name collisions are not detected. For instance:
  3803. $sftp->mget(["foo/file.txt", "bar/file.txt"], "/tmp")
  3804. will transfer the first file to "/tmp/file.txt" and later overwrite it
  3805. with the second one. The C<numbered> option can be used to avoid this
  3806. issue.
  3807. =item $sftp-E<gt>mput($local, $remotedir, %opts)
  3808. =item $sftp-E<gt>mput(\@local, $remotedir, %opts)
  3809. similar to L</mget> but works in the opposite direction transferring
  3810. files from the local side to the remote one.
  3811. =item $sftp-E<gt>join(@paths)
  3812. returns the given path fragments joined in one path (currently the
  3813. remote file system is expected to be UNIX like).
  3814. =item $sftp-E<gt>open($path, $flags [, $attrs ])
  3815. Sends the C<SSH_FXP_OPEN> command to open a remote file C<$path>,
  3816. and returns an open handle on success. On failure returns
  3817. C<undef>.
  3818. The returned value is a tied handle (see L<Tie::Handle>) that can be
  3819. used to access the remote file both with the methods available from
  3820. this module and with perl built-ins. For instance:
  3821. # reading from the remote file
  3822. my $fh1 = $sftp->open("/etc/passwd")
  3823. or die $sftp->error;
  3824. while (<$fh1>) { ... }
  3825. # writing to the remote file
  3826. use Net::SFTP::Foreign::Constants qw(:flags);
  3827. my $fh2 = $sftp->open("/foo/bar", SSH2_FXF_WRITE|SSH2_FXF_CREAT)
  3828. or die $sftp->error;
  3829. print $fh2 "printing on the remote file\n";
  3830. $sftp->write($fh2, "writing more");
  3831. The C<$flags> bitmap determines how to open the remote file as defined
  3832. in the SFTP protocol draft (the following constants can be imported
  3833. from L<Net::SFTP::Foreign::Constants>):
  3834. =over 4
  3835. =item SSH2_FXF_READ
  3836. Open the file for reading. It is the default mode.
  3837. =item SSH2_FXF_WRITE
  3838. Open the file for writing. If both this and C<SSH2_FXF_READ> are
  3839. specified, the file is opened for both reading and writing.
  3840. =item SSH2_FXF_APPEND
  3841. Force all writes to append data at the end of the file.
  3842. As OpenSSH SFTP server implementation ignores this flag, the module
  3843. emulates it (I will appreciate receiving feedback about the
  3844. inter-operation of this module with other server implementations when
  3845. this flag is used).
  3846. =item SSH2_FXF_CREAT
  3847. If this flag is specified, then a new file will be created if one does
  3848. not already exist.
  3849. =item SSH2_FXF_TRUNC
  3850. Forces an existing file with the same name to be truncated to zero
  3851. length when creating a file. C<SSH2_FXF_CREAT> must also be specified
  3852. if this flag is used.
  3853. =item SSH2_FXF_EXCL
  3854. Causes the request to fail if the named file already exists.
  3855. C<SSH2_FXF_CREAT> must also be specified if this flag is used.
  3856. =back
  3857. When creating a new remote file, C<$attrs> allows one to set its
  3858. initial attributes. C<$attrs> has to be an object of class
  3859. L<Net::SFTP::Foreign::Attributes>.
  3860. =item $sftp-E<gt>close($handle)
  3861. Closes the remote file handle C<$handle>.
  3862. Files are automatically closed on the handle C<DESTROY> method when
  3863. not done explicitly.
  3864. Returns true on success and undef on failure.
  3865. =item $sftp-E<gt>read($handle, $length)
  3866. reads C<$length> bytes from an open file handle C<$handle>. On success
  3867. returns the data read from the remote file and undef on failure
  3868. (including EOF).
  3869. =item $sftp-E<gt>write($handle, $data)
  3870. writes C<$data> to the remote file C<$handle>. Returns the number of
  3871. bytes written or undef on failure.
  3872. =item $sftp-E<gt>readline($handle)
  3873. =item $sftp-E<gt>readline($handle, $sep)
  3874. in scalar context reads and returns the next line from the remote
  3875. file. In list context, it returns all the lines from the current
  3876. position to the end of the file.
  3877. By default "\n" is used as the separator between lines, but a
  3878. different one can be used passing it as the second method argument. If
  3879. the empty string is used, it returns all the data from the current
  3880. position to the end of the file as one line.
  3881. =item $sftp-E<gt>getc($handle)
  3882. returns the next character from the file.
  3883. =item $sftp-E<gt>seek($handle, $pos, $whence)
  3884. sets the current position for the remote file handle C<$handle>. If
  3885. C<$whence> is 0, the position is set relative to the beginning of the
  3886. file; if C<$whence> is 1, position is relative to current position and
  3887. if $<$whence> is 2, position is relative to the end of the file.
  3888. returns a trues value on success, undef on failure.
  3889. =item $sftp-E<gt>tell($fh)
  3890. returns the current position for the remote file handle C<$handle>.
  3891. =item $sftp-E<gt>eof($fh)
  3892. reports whether the remote file handler points at the end of the file.
  3893. =item $sftp-E<gt>flush($fh)
  3894. X<flush>writes to the remote file any pending data and discards the
  3895. read cache.
  3896. Note that this operation just sends data cached locally to the remote
  3897. server. You may like to call C<fsync> (when supported) afterwards to
  3898. ensure that data is actually flushed to disc.
  3899. =item $sftp-E<gt>fsync($fh)
  3900. On servers supporting the C<fsync@openssh.com> extension, this method
  3901. calls L<fysnc(2)> on the remote side, which usually flushes buffered
  3902. changes to disk.
  3903. =item $sftp-E<gt>sftpread($handle, $offset, $length)
  3904. low level method that sends a SSH2_FXP_READ request to read from an
  3905. open file handle C<$handle>, C<$length> bytes starting at C<$offset>.
  3906. Returns the data read on success and undef on failure.
  3907. Some servers (for instance OpenSSH SFTP server) limit the size of the
  3908. read requests and so the length of data returned can be smaller than
  3909. requested.
  3910. =item $sftp-E<gt>sftpwrite($handle, $offset, $data)
  3911. low level method that sends a C<SSH_FXP_WRITE> request to write to an
  3912. open file handle C<$handle>, starting at C<$offset>, and where the
  3913. data to be written is in C<$data>.
  3914. Returns true on success and undef on failure.
  3915. =item $sftp-E<gt>opendir($path)
  3916. Sends a C<SSH_FXP_OPENDIR> command to open the remote directory
  3917. C<$path>, and returns an open handle on success (unfortunately,
  3918. current versions of perl does not support directory operations via
  3919. tied handles, so it is not possible to use the returned handle as a
  3920. native one).
  3921. On failure returns C<undef>.
  3922. =item $sftp-E<gt>closedir($handle)
  3923. closes the remote directory handle C<$handle>.
  3924. Directory handles are closed from their C<DESTROY> method when not
  3925. done explicitly.
  3926. Return true on success, undef on failure.
  3927. =item $sftp-E<gt>readdir($handle)
  3928. returns the next entry from the remote directory C<$handle> (or all
  3929. the remaining entries when called in list context).
  3930. The return values are a hash with three keys: C<filename>, C<longname> and
  3931. C<a>. The C<a> value contains a L<Net::SFTP::Foreign::Attributes>
  3932. object describing the entry.
  3933. Returns undef on error or when no more entries exist on the directory.
  3934. =item $sftp-E<gt>stat($path_or_fh)
  3935. performs a C<stat> on the remote file and returns a
  3936. L<Net::SFTP::Foreign::Attributes> object with the result values. Both
  3937. paths and open remote file handles can be passed to this method.
  3938. Returns undef on failure.
  3939. =item $sftp-E<gt>fstat($handle)
  3940. this method is deprecated.
  3941. =item $sftp-E<gt>lstat($path)
  3942. this method is similar to C<stat> method but stats a symbolic link
  3943. instead of the file the symbolic links points to.
  3944. =item $sftp-E<gt>setstat($path_or_fh, $attrs)
  3945. sets file attributes on the remote file. Accepts both paths and open
  3946. remote file handles.
  3947. Returns true on success and undef on failure.
  3948. =item $sftp-E<gt>fsetstat($handle, $attrs)
  3949. this method is deprecated.
  3950. =item $sftp-E<gt>truncate($path_or_fh, $size)
  3951. =item $sftp-E<gt>chown($path_or_fh, $uid, $gid)
  3952. =item $sftp-E<gt>chmod($path_or_fh, $perm)
  3953. =item $sftp-E<gt>utime($path_or_fh, $atime, $mtime)
  3954. Shortcuts around C<setstat> method.
  3955. =item $sftp-E<gt>remove($path)
  3956. Sends a C<SSH_FXP_REMOVE> command to remove the remote file
  3957. C<$path>. Returns a true value on success and undef on failure.
  3958. =item $sftp-E<gt>mkdir($path, $attrs)
  3959. Sends a C<SSH_FXP_MKDIR> command to create a remote directory C<$path>
  3960. whose attributes are initialized to C<$attrs> (a
  3961. L<Net::SFTP::Foreign::Attributes> object).
  3962. Returns a true value on success and undef on failure.
  3963. The C<$attrs> argument is optional.
  3964. =item $sftp-E<gt>mkpath($path, $attrs, $parent)
  3965. This method is similar to C<mkdir> but also creates any non-existent
  3966. parent directories recursively.
  3967. When the optional argument C<$parent> has a true value, just the
  3968. parent directory of the given path (and its ancestors as required) is
  3969. created.
  3970. For instance:
  3971. $sftp->mkpath("/tmp/work", undef, 1);
  3972. my $fh = $sftp->open("/tmp/work/data.txt",
  3973. SSH2_FXF_WRITE|SSH2_FXF_CREAT);
  3974. =item $sftp-E<gt>rmdir($path)
  3975. Sends a C<SSH_FXP_RMDIR> command to remove a remote directory
  3976. C<$path>. Returns a true value on success and undef on failure.
  3977. =item $sftp-E<gt>realpath($path)
  3978. Sends a C<SSH_FXP_REALPATH> command to canonicalise C<$path>
  3979. to an absolute path. This can be useful for turning paths
  3980. containing C<'..'> into absolute paths.
  3981. Returns the absolute path on success, C<undef> on failure.
  3982. =item $sftp-E<gt>rename($old, $new, %opts)
  3983. Sends a C<SSH_FXP_RENAME> command to rename C<$old> to C<$new>.
  3984. Returns a true value on success and undef on failure.
  3985. Accepted options are:
  3986. =over 4
  3987. =item overwrite => $bool
  3988. By default, the rename operation fails when a file C<$new> already
  3989. exists. When this options is set, any previous existent file is
  3990. deleted first (the C<atomic_rename> operation will be used if
  3991. available).
  3992. Note than under some conditions the target file could be deleted and
  3993. afterwards the rename operation fail.
  3994. =back
  3995. =item $sftp-E<gt>atomic_rename($old, $new)
  3996. Renames a file using the C<posix-rename@openssh.com> extension when
  3997. available.
  3998. Unlike the C<rename> method, it overwrites any previous C<$new> file.
  3999. =item $sftp-E<gt>readlink($path)
  4000. Sends a C<SSH_FXP_READLINK> command to read the path where the
  4001. symbolic link is pointing.
  4002. Returns the target path on success and undef on failure.
  4003. =item $sftp-E<gt>symlink($sl, $target)
  4004. Sends a C<SSH_FXP_SYMLINK> command to create a new symbolic link
  4005. C<$sl> pointing to C<$target>.
  4006. C<$target> is stored as-is, without any path expansion taken place on
  4007. it. Use C<realpath> to normalize it:
  4008. $sftp->symlink("foo.lnk" => $sftp->realpath("../bar"))
  4009. =item $sftp-E<gt>hardlink($hl, $target)
  4010. Creates a hardlink on the server.
  4011. This command requires support for the 'hardlink@openssh.com' extension
  4012. on the server (available in OpenSSH from version 5.7).
  4013. =item $sftp-E<gt>statvfs($path)
  4014. =item $sftp-E<gt>fstatvfs($fh)
  4015. On servers supporting C<statvfs@openssh.com> and
  4016. C<fstatvfs@openssh.com> extensions respectively, these methods return
  4017. a hash reference with information about the file system where the file
  4018. named C<$path> or the open file C<$fh> resides.
  4019. The hash entries are:
  4020. bsize => file system block size
  4021. frsize => fundamental fs block size
  4022. blocks => number of blocks (unit f_frsize)
  4023. bfree => free blocks in file system
  4024. bavail => free blocks for non-root
  4025. files => total file inodes
  4026. ffree => free file inodes
  4027. favail => free file inodes for to non-root
  4028. fsid => file system id
  4029. flag => bit mask of f_flag values
  4030. namemax => maximum filename length
  4031. The values of the f_flag bit mask are as follows:
  4032. SSH2_FXE_STATVFS_ST_RDONLY => read-only
  4033. SSH2_FXE_STATVFS_ST_NOSUID => no setuid
  4034. =item $sftp-E<gt>disconnect
  4035. Closes the SSH connection to the remote host. From this point the
  4036. object becomes mostly useless.
  4037. Usually, this method should not be called explicitly, but implicitly
  4038. from the DESTROY method when the object goes out of scope.
  4039. See also the documentation for the C<autodiscconnect> constructor
  4040. argument.
  4041. =item $sftp-E<gt>autodisconnect($ad)
  4042. Sets the C<autodisconnect> behaviour.
  4043. See also the documentation for the C<autodiscconnect> constructor
  4044. argument. The values accepted here are the same as there.
  4045. =back
  4046. =head2 On the fly data conversion
  4047. Some of the methods on this module allow to perform on the fly data
  4048. conversion via the C<conversion> option that accepts the following
  4049. values:
  4050. =over 4
  4051. =item conversion =E<gt> 'dos2unix'
  4052. Converts CR+LF line endings (as commonly used under MS-DOS) to LF
  4053. (UNIX).
  4054. =item conversion =E<gt> 'unix2dos'
  4055. Converts LF line endings (UNIX) to CR+LF (DOS).
  4056. =item conversion =E<gt> sub { CONVERT $_[0] }
  4057. When a callback is given, it is invoked repeatedly as chunks of data
  4058. become available. It has to change C<$_[0]> in place in order to
  4059. perform the conversion.
  4060. Also, the subroutine is called one last time with and empty data
  4061. string to indicate that the transfer has finished, so that
  4062. intermediate buffers can be flushed.
  4063. Note that when writing conversion subroutines, special care has to be
  4064. taken to handle sequences crossing chunk borders.
  4065. =back
  4066. The data conversion is always performed before any other callback
  4067. subroutine is called.
  4068. See the Wikipedia entry on line endings
  4069. L<http://en.wikipedia.org/wiki/Newline> or the article Understanding
  4070. Newlines by Xavier Noria
  4071. (L<http://www.onlamp.com/pub/a/onlamp/2006/08/17/understanding-newlines.html>)
  4072. for details about the different conventions.
  4073. =head1 FAQ
  4074. =over 4
  4075. =item Closing the connection:
  4076. B<Q>: How do I close the connection to the remote server?
  4077. B<A>: let the C<$sftp> object go out of scope or just undefine it:
  4078. undef $sftp;
  4079. =item Using Net::SFTP::Foreign from a cron script:
  4080. B<Q>: I wrote a script for performing sftp file transfers that works
  4081. beautifully from the command line. However when I try to run the same
  4082. script from cron it fails with a broken pipe error:
  4083. open2: exec of ssh -l user some.location.com -s sftp
  4084. failed at Net/SFTP/Foreign.pm line 67
  4085. B<A>: C<ssh> is not on your cron PATH.
  4086. The remedy is either to add the location of the C<ssh> application to
  4087. your cron PATH or to use the C<ssh_cmd> option of the C<new> method to
  4088. hardcode the location of C<ssh> inside your script, for instance:
  4089. my $ssh = Net::SFTP::Foreign->new($host,
  4090. ssh_cmd => '/usr/local/ssh/bin/ssh');
  4091. =item C<more> constructor option expects an array reference:
  4092. B<Q>: I'm trying to pass in the private key file using the -i option,
  4093. but it keep saying it couldn't find the key. What I'm doing wrong?
  4094. B<A>: The C<more> argument on the constructor expects a single option
  4095. or a reference to an array of options. It will not split an string
  4096. containing several options.
  4097. Arguments to SSH options have to be also passed as different entries
  4098. on the array:
  4099. my $sftp = Net::SFTP::Foreign->new($host,
  4100. more => [qw(-i /home/foo/.ssh/id_dsa)]);
  4101. Note also that latest versions of Net::SFTP::Foreign support the
  4102. C<key_path> argument:
  4103. my $sftp = Net::SFTP::Foreign->new($host,
  4104. key_path => '/home/foo/.ssh/id_dsa');
  4105. =item Plink and password authentication
  4106. B<Q>: Why password authentication is not supported for the plink SSH
  4107. client?
  4108. B<A>: A bug in plink breaks it.
  4109. Newer versions of Net::SFTP::Foreign pass the password to C<plink>
  4110. using its C<-pw> option. As this feature is not completely secure a
  4111. warning is generated.
  4112. It can be silenced (though, don't do it without understanding why it
  4113. is there, please!) as follows:
  4114. no warnings 'Net::SFTP::Foreign';
  4115. my $sftp = Net::SFTP::Foreign->new('foo@bar',
  4116. ssh_cmd => 'plink',
  4117. password => $password);
  4118. $sftp->die_on_error;
  4119. =item Plink
  4120. B<Q>: What is C<plink>?
  4121. B<A>: Plink is a command line tool distributed with the
  4122. L<PuTTY|http://the.earth.li/~sgtatham/putty/> SSH client. Very popular
  4123. between MS Windows users, it is also available for Linux and other
  4124. UNIX now.
  4125. =item Put method fails
  4126. B<Q>: put fails with the following error:
  4127. Couldn't setstat remote file: The requested operation cannot be
  4128. performed because there is a file transfer in progress.
  4129. B<A>: Try passing the C<late_set_perm> option to the put method:
  4130. $sftp->put($local, $remote, late_set_perm => 1)
  4131. or die "unable to transfer file: " . $sftp->error;
  4132. Some servers do not support the C<fsetstat> operation on open file
  4133. handles. Setting this flag allows one to delay that operation until
  4134. the file has been completely transferred and the remote file handle
  4135. closed.
  4136. Also, send me a bug report containing a dump of your $sftp object so I
  4137. can add code for your particular server software to activate the
  4138. work-around automatically.
  4139. =item Put method fails even with late_set_perm set
  4140. B<Q>: I added C<late_set_perm =E<gt> 1> to the put call, but we are still
  4141. receiving the error C<Couldn't setstat remote file (setstat)>.
  4142. B<A>: Some servers forbid the SFTP C<setstat> operation used by the
  4143. C<put> method for replicating the file permissions and time-stamps on
  4144. the remote side.
  4145. As a work around you can just disable the feature:
  4146. $sftp->put($local_file, $remote_file,
  4147. copy_perm => 0, copy_time => 0);
  4148. =item Disable password authentication completely
  4149. B<Q>: When we try to open a session and the key either doesn't exist
  4150. or is invalid, the child SSH hangs waiting for a password to be
  4151. entered. Is there a way to make this fail back to the Perl program to
  4152. be handled?
  4153. B<A>: Disable anything but public key SSH authentication calling the
  4154. new method as follows:
  4155. $sftp = Net::SFTP::Foreign->new($host,
  4156. more => [qw(-o PreferredAuthentications=publickey)])
  4157. See L<ssh_config(5)> for the details.
  4158. =item Understanding C<$attr-E<gt>perm> bits
  4159. B<Q>: How can I know if a directory entry is a (directory|link|file|...)?
  4160. B<A>: Use the C<S_IS*> functions from L<Fcntl>. For instance:
  4161. use Fcntl qw(S_ISDIR);
  4162. my $ls = $sftp->ls or die $sftp->error;
  4163. for my $entry (@$ls) {
  4164. if (S_ISDIR($entry->{a}->perm)) {
  4165. print "$entry->{filename} is a directory\n";
  4166. }
  4167. }
  4168. =item Host key checking
  4169. B<Q>: Connecting to a remote server with password authentication fails
  4170. with the following error:
  4171. The authenticity of the target host can not be established,
  4172. connect from the command line first
  4173. B<A>: That probably means that the public key from the remote server
  4174. is not stored in the C<~/.ssh/known_hosts> file. Run an SSH Connection
  4175. from the command line as the same user as the script and answer C<yes>
  4176. when asked to confirm the key supplied.
  4177. Example:
  4178. $ ssh pluto /bin/true
  4179. The authenticity of host 'pluto (172.25.1.4)' can't be established.
  4180. RSA key fingerprint is 41:b1:a7:86:d2:a9:7b:b0:7f:a1:00:b7:26:51:76:52.
  4181. Are you sure you want to continue connecting (yes/no)? yes
  4182. Your SSH client may also support some flag to disable this check, but
  4183. doing it can ruin the security of the SSH protocol so I advise against
  4184. its usage.
  4185. Example:
  4186. # Warning: don't do that unless you fully understand
  4187. # its security implications!!!
  4188. $sftp = Net::SFTP::Foreign->new($host,
  4189. more => [-o => 'StrictHostKeyChecking no'],
  4190. ...);
  4191. =back
  4192. =head1 BUGS
  4193. These are the currently known bugs:
  4194. =over 4
  4195. =item - Doesn't work on VMS:
  4196. The problem is related to L<IPC::Open3> not working on VMS. Patches
  4197. are welcome!
  4198. =item - Dirty cleanup:
  4199. On some operating systems, closing the pipes used to communicate with
  4200. the slave SSH process does not terminate it and a work around has to
  4201. be applied. If you find that your scripts hung when the $sftp object
  4202. gets out of scope, try setting C<$Net::SFTP::Foreign::dirty_cleanup>
  4203. to a true value and also send me a report including the value of
  4204. C<$^O> on your machine and the OpenSSH version.
  4205. From version 0.90_18 upwards, a dirty cleanup is performed anyway when
  4206. the SSH process does not terminate by itself in 8 seconds or less.
  4207. =item - Reversed symlink arguments:
  4208. This package uses the non-conforming OpenSSH argument order for the
  4209. SSH_FXP_SYMLINK command that seems to be the de facto standard. When
  4210. interacting with SFTP servers that follow the SFTP specification, the
  4211. C<symlink> method will interpret its arguments in reverse order.
  4212. =item - IPC::Open3 bugs on Windows
  4213. On Windows the IPC::Open3 module is used to spawn the slave SSH
  4214. process. That module has several nasty bugs (related to STDIN, STDOUT
  4215. and STDERR being closed or not being assigned to file descriptors 0, 1
  4216. and 2 respectively) that will cause the connection to fail.
  4217. Specifically this is known to happen under mod_perl/mod_perl2.
  4218. =item - Password authentication on HP-UX
  4219. For some unknown reason, it seems that when using the module on HP-UX,
  4220. number signs (C<#>) in password need to be escaped (C<\#>). For
  4221. instance:
  4222. my $password = "foo#2014";
  4223. $password =~ s/#/\\#/g if $running_in_hp_ux;
  4224. my $ssh = Net::OpenSSH->new($host, user => $user,
  4225. password => $password);
  4226. I don't have access to an HP-UX machine, and so far nobody using it
  4227. has been able to explain this behaviour. Patches welcome!
  4228. =back
  4229. Also, the following features should be considered experimental:
  4230. - support for Tectia server
  4231. - numbered feature
  4232. - autodie mode
  4233. - best_effort feature
  4234. =head1 SUPPORT
  4235. To report bugs, send me and email or use the CPAN bug tracking system
  4236. at L<http://rt.cpan.org>.
  4237. =head2 Commercial support
  4238. Commercial support, professional services and custom software
  4239. development around this module are available through my current
  4240. company. Drop me an email with a rough description of your
  4241. requirements and we will get back to you ASAP.
  4242. =head2 My wishlist
  4243. If you like this module and you're feeling generous, take a look at my
  4244. Amazon Wish List: L<http://amzn.com/w/1WU1P6IR5QZ42>
  4245. Also consider contributing to the OpenSSH project this module builds
  4246. upon: L<http://www.openssh.org/donations.html>.
  4247. =head1 SEE ALSO
  4248. Information about the constants used on this module is available from
  4249. L<Net::SFTP::Foreign::Constants>. Information about attribute objects
  4250. is available from L<Net::SFTP::Foreign::Attributes>.
  4251. General information about SSH and the OpenSSH implementation is
  4252. available from the OpenSSH web site at L<http://www.openssh.org/> and
  4253. from the L<sftp(1)> and L<sftp-server(8)> manual pages.
  4254. Net::SFTP::Foreign integrates nicely with my other module
  4255. L<Net::OpenSSH>.
  4256. L<Net::SFTP::Foreign::Backend::Net_SSH2> allows one to run
  4257. Net::SFTP::Foreign on top of L<Net::SSH2> (nowadays, this combination
  4258. is probably the best option under Windows).
  4259. Modules offering similar functionality available from CPAN are
  4260. L<Net::SFTP> and L<Net::SSH2>.
  4261. L<Test::SFTP> allows one to run tests against a remote SFTP server.
  4262. L<autodie>.
  4263. =head1 COPYRIGHT
  4264. Copyright (c) 2005-2014 Salvador FandiE<ntilde>o (sfandino@yahoo.com).
  4265. Copyright (c) 2001 Benjamin Trott, Copyright (c) 2003 David Rolsky.
  4266. _glob_to_regex method based on code (c) 2002 Richard Clamp.
  4267. All rights reserved. This program is free software; you can
  4268. redistribute it and/or modify it under the same terms as Perl itself.
  4269. The full text of the license can be found in the LICENSE file included
  4270. with this module.
  4271. =cut