3 # Versions up to 2.29_1 Copyright (c) 1995-2006 Graham Barr <gbarr@pobox.com>.
5 # Changes in Version 2.29_2 onwards Copyright (C) 2013-2015 Steve Hay. All
7 # This module is free software; you can redistribute it and/or modify it under
8 # the same terms as Perl itself, i.e. under the terms of either the GNU General
9 # Public License or the Artistic License, as specified in the F<LICENCE> file.
24 require Convert::EBCDIC;
26 # Convert::EBCDIC->import;
30 our $VERSION = "3.07";
31 our @ISA = qw(Exporter);
32 our @EXPORT = qw(CMD_INFO CMD_OK CMD_MORE CMD_REJECT CMD_ERROR CMD_PENDING);
34 use constant CMD_INFO => 1;
35 use constant CMD_OK => 2;
36 use constant CMD_MORE => 3;
37 use constant CMD_REJECT => 4;
38 use constant CMD_ERROR => 5;
39 use constant CMD_PENDING => 0;
41 use constant DEF_REPLY_CODE => 421;
45 my $tr = $^O eq 'os390' ? Convert::EBCDIC->new() : undef;
50 unless (exists ${*$cmd}{'net_cmd_asciipeer'}) {
52 my $ebcdicstr = $tr->toebcdic($string);
53 ${*$cmd}{'net_cmd_asciipeer'} = $string !~ /^\d+/ && $ebcdicstr =~ /^\d+/;
56 ${*$cmd}{'net_cmd_asciipeer'}
57 ? $tr->toebcdic($_[0])
64 ${*$cmd}{'net_cmd_asciipeer'}
71 no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict)
82 while ($pkg = shift @do) {
83 next if defined $done{$pkg};
88 defined ${"${pkg}::VERSION"}
89 ? "(" . ${"${pkg}::VERSION"} . ")"
93 $cmd->debug_print(1, "${spc}${pkg}${v}\n");
95 if (@{"${pkg}::ISA"}) {
96 @spc{@{"${pkg}::ISA"}} = (" " . $spc{$pkg}) x @{"${pkg}::ISA"};
97 unshift(@do, @{"${pkg}::ISA"});
104 @_ == 1 or @_ == 2 or croak 'usage: $obj->debug([LEVEL])';
106 my ($cmd, $level) = @_;
107 my $pkg = ref($cmd) || $cmd;
111 $oldval = ${*$cmd}{'net_cmd_debug'} || 0;
114 $oldval = $debug{$pkg} || 0;
120 $level = $debug{$pkg} || 0
121 unless defined $level;
124 if ($level && !exists $debug{$pkg});
127 ${*$cmd}{'net_cmd_debug'} = $level;
130 $debug{$pkg} = $level;
138 @_ == 1 or croak 'usage: $obj->message()';
143 ? @{${*$cmd}{'net_cmd_resp'}}
144 : join("", @{${*$cmd}{'net_cmd_resp'}});
148 sub debug_text { $_[2] }
152 my ($cmd, $out, $text) = @_;
153 print STDERR $cmd, ($out ? '>>> ' : '<<< '), $cmd->debug_text($out, $text);
158 @_ == 1 or croak 'usage: $obj->code()';
162 ${*$cmd}{'net_cmd_code'} = $cmd->DEF_REPLY_CODE
163 unless exists ${*$cmd}{'net_cmd_code'};
165 ${*$cmd}{'net_cmd_code'};
170 @_ == 1 or croak 'usage: $obj->status()';
174 substr(${*$cmd}{'net_cmd_code'}, 0, 1);
179 @_ == 3 or croak 'usage: $obj->set_status(CODE, MESSAGE)';
182 my ($code, $resp) = @_;
184 $resp = defined $resp ? [$resp] : []
187 (${*$cmd}{'net_cmd_code'}, ${*$cmd}{'net_cmd_resp'}) = ($code, $resp);
194 sub _set_status_timeout {
196 my $pkg = ref($cmd) || $cmd;
198 $cmd->set_status($cmd->DEF_REPLY_CODE, "[$pkg] Timeout");
199 carp(ref($cmd) . ": " . (caller(1))[3] . "(): timeout") if $cmd->debug;
202 sub _set_status_closed {
204 my $pkg = ref($cmd) || $cmd;
206 $cmd->set_status($cmd->DEF_REPLY_CODE, "[$pkg] Connection closed");
207 carp(ref($cmd) . ": " . (caller(1))[3]
208 . "(): unexpected EOF on command channel: $!") if $cmd->debug;
213 if (!defined fileno($cmd)) {
214 $cmd->_set_status_closed;
227 if (exists ${*$cmd}{'net_cmd_last_ch'});
230 local $SIG{PIPE} = 'IGNORE' unless $^O eq 'MacOS';
236 ? do { my $n = $_; $n =~ tr/\n/ /; $n }
240 $str = $cmd->toascii($str) if $tr;
243 my $len = length $str;
246 $cmd->debug_print(1, $str)
249 unless (defined($swlen = syswrite($cmd,$str,$len)) && $swlen == $len) {
251 $cmd->_set_status_closed;
261 @_ == 1 or croak 'usage: $obj->ok()';
263 my $code = $_[0]->code;
264 0 < $code && $code < 400;
271 $cmd->set_status(580, 'Unsupported command');
280 ${*$cmd}{'net_cmd_lines'} ||= [];
282 return shift @{${*$cmd}{'net_cmd_lines'}}
283 if scalar(@{${*$cmd}{'net_cmd_lines'}});
285 my $partial = defined(${*$cmd}{'net_cmd_partial'}) ? ${*$cmd}{'net_cmd_partial'} : "";
290 my $fd = fileno($cmd);
292 vec($rin, $fd, 1) = 1;
296 until (scalar(@{${*$cmd}{'net_cmd_lines'}})) {
297 my $timeout = $cmd->timeout || undef;
300 my $select_ret = select($rout = $rin, undef, undef, $timeout);
301 if ($select_ret > 0) {
302 unless (sysread($cmd, $buf = "", 1024)) {
304 $cmd->_set_status_closed;
308 substr($buf, 0, 0) = $partial; ## prepend from last sysread
310 my @buf = split(/\015?\012/, $buf, -1); ## break into lines
314 push(@{${*$cmd}{'net_cmd_lines'}}, map {"$_\n"} @buf);
318 $cmd->_set_status_timeout;
323 ${*$cmd}{'net_cmd_partial'} = $partial;
326 foreach my $ln (@{${*$cmd}{'net_cmd_lines'}}) {
327 $ln = $cmd->toebcdic($ln);
331 shift @{${*$cmd}{'net_cmd_lines'}};
336 my ($cmd, $str) = @_;
338 ${*$cmd}{'net_cmd_lines'} ||= [];
339 unshift(@{${*$cmd}{'net_cmd_lines'}}, $str);
345 unless $_[1] =~ s/^(\d\d\d)(.?)//o;
352 my ($code, $more) = (undef) x 2;
354 $cmd->set_status($cmd->DEF_REPLY_CODE, undef); # initialize the response
357 my $str = $cmd->getline();
360 unless defined($str);
362 $cmd->debug_print(0, $str)
365 ($code, $more) = $cmd->parse_response($str);
366 unless (defined $code) {
367 carp("$cmd: response(): parse error in '$str'") if ($cmd->debug);
368 $cmd->ungetline($str);
369 $@ = $str; # $@ used as tunneling hack
373 ${*$cmd}{'net_cmd_code'} = $code;
375 push(@{${*$cmd}{'net_cmd_resp'}}, $str);
380 return unless defined $code;
391 my $str = $cmd->getline() or return;
393 $cmd->debug_print(0, $str)
394 if ($cmd->debug & 4);
396 last if ($str =~ /^\.\r?\n/o);
414 my $arr = @_ == 1 && ref($_[0]) ? $_[0] : \@_;
415 my $line = join("", @$arr);
417 # Perls < 5.10.1 (with the exception of 5.8.9) have a performance problem with
418 # the substitutions below when dealing with strings stored internally in
419 # UTF-8, so downgrade them (if possible).
420 # Data passed to datasend() should be encoded to octets upstream already so
421 # shouldn't even have the UTF-8 flag on to start with, but if it so happens
422 # that the octets are stored in an upgraded string (as can sometimes occur)
423 # then they would still downgrade without fail anyway.
424 # Only Unicode codepoints > 0xFF stored in an upgraded string will fail to
425 # downgrade. We fail silently in that case, and a "Wide character in print"
426 # warning will be emitted later by syswrite().
427 utf8::downgrade($line, 1) if $] < 5.010001 && $] != 5.008009;
432 my $last_ch = ${*$cmd}{'net_cmd_last_ch'};
434 # We have not send anything yet, so last_ch = "\012" means we are at the start of a line
435 $last_ch = ${*$cmd}{'net_cmd_last_ch'} = "\012" unless defined $last_ch;
437 return 1 unless length $line;
440 foreach my $b (split(/\n/, $line)) {
441 $cmd->debug_print(1, "$b\n");
445 $line =~ tr/\r\n/\015\012/ unless "\r" eq "\015";
449 if ($last_ch eq "\015") {
450 # Remove \012 so it does not get prefixed with another \015 below
451 # and escape the . if there is one following it because the fixup
452 # below will not find it
453 $first_ch = "\012" if $line =~ s/^\012(\.?)/$1$1/;
455 elsif ($last_ch eq "\012") {
456 # Fixup below will not find the . as the first character of the buffer
457 $first_ch = "." if $line =~ /^\./;
460 $line =~ s/\015?\012(\.?)/\015\012$1$1/sg;
462 substr($line, 0, 0) = $first_ch;
464 ${*$cmd}{'net_cmd_last_ch'} = substr($line, -1, 1);
466 my $len = length($line);
469 vec($win, fileno($cmd), 1) = 1;
470 my $timeout = $cmd->timeout || undef;
472 local $SIG{PIPE} = 'IGNORE' unless $^O eq 'MacOS';
476 my $s = select(undef, $wout = $win, undef, $timeout);
477 if ((defined $s and $s > 0) or -f $cmd) # -f for testing on win32
479 my $w = syswrite($cmd, $line, $len, $offset);
480 unless (defined($w) && $w == $len) {
482 $cmd->_set_status_closed;
489 $cmd->_set_status_timeout;
500 my $arr = @_ == 1 && ref($_[0]) ? $_[0] : \@_;
501 my $line = join("", @$arr);
507 unless length($line);
511 print STDERR $b, join("\n$b", split(/\n/, $line)), "\n";
514 my $len = length($line);
517 vec($win, fileno($cmd), 1) = 1;
518 my $timeout = $cmd->timeout || undef;
520 local $SIG{PIPE} = 'IGNORE' unless $^O eq 'MacOS';
523 if (select(undef, $wout = $win, undef, $timeout) > 0) {
524 my $w = syswrite($cmd, $line, $len, $offset);
525 unless (defined($w) && $w == $len) {
527 $cmd->_set_status_closed;
534 $cmd->_set_status_timeout;
549 my $ch = ${*$cmd}{'net_cmd_last_ch'};
555 elsif ($ch ne "\012") {
556 $tosend = "\015\012";
559 $tosend .= ".\015\012";
561 local $SIG{PIPE} = 'IGNORE' unless $^O eq 'MacOS';
563 $cmd->debug_print(1, ".\n")
566 my $len = length $tosend;
567 my $w = syswrite($cmd, $tosend, $len);
568 unless (defined($w) && $w == $len)
571 $cmd->_set_status_closed;
575 delete ${*$cmd}{'net_cmd_last_ch'};
577 $cmd->response() == CMD_OK;
580 # read and write to tied filehandle
583 ${*$cmd}{'net_cmd_readbuf'} = '';
585 tie *$fh, ref($cmd), $cmd;
596 # Tied filehandle read. Reads requested data length, returning
597 # end-of-file when the dot is encountered.
600 my ($len, $offset) = @_[1, 2];
601 return unless exists ${*$cmd}{'net_cmd_readbuf'};
603 while (!$done and length(${*$cmd}{'net_cmd_readbuf'}) < $len) {
604 ${*$cmd}{'net_cmd_readbuf'} .= $cmd->getline() or return;
605 $done++ if ${*$cmd}{'net_cmd_readbuf'} =~ s/^\.\r?\n\Z//m;
609 substr($_[0], $offset + 0) = substr(${*$cmd}{'net_cmd_readbuf'}, 0, $len);
610 substr(${*$cmd}{'net_cmd_readbuf'}, 0, $len) = '';
611 delete ${*$cmd}{'net_cmd_readbuf'} if $done;
620 # in this context, we use the presence of readbuf to
621 # indicate that we have not yet reached the eof
622 return unless exists ${*$cmd}{'net_cmd_readbuf'};
623 my $line = $cmd->getline;
624 return if $line =~ /^\.\r?\n/;
631 my ($buf, $len, $offset) = @_;
632 $len ||= length($buf);
634 return unless $cmd->datasend(substr($buf, $offset, $len));
635 ${*$cmd}{'net_cmd_sending'}++; # flag that we should call dataend()
642 my $r = exists(${*$cmd}{'net_cmd_sending'}) ? $cmd->dataend : 1;
643 delete ${*$cmd}{'net_cmd_readbuf'};
644 delete ${*$cmd}{'net_cmd_sending'};
655 Net::Cmd - Network Command class (as used by FTP, SMTP etc)
665 C<Net::Cmd> is a collection of methods that can be inherited by a sub class
666 of C<IO::Handle>. These methods implement the functionality required for a
667 command based protocol, for example FTP and SMTP.
671 These methods provide a user interface to the C<Net::Cmd> object.
675 =item debug ( VALUE )
677 Set the level of debug information for this object. If C<VALUE> is not given
678 then the current state is returned. Otherwise the state is changed to
679 C<VALUE> and the previous state returned.
682 may implement different levels of debug but a non-zero value results in
683 copies of all commands and responses also being sent to STDERR.
685 If C<VALUE> is C<undef> then the debug level will be set to the default
686 debug level for the class.
688 This method can also be called as a I<static> method to set/get the default
689 debug level for a given class.
693 Returns the text message returned from the last command. In a scalar
694 context it returns a single string, in a list context it will return
695 each line as a separate element. (See L<PSEUDO RESPONSES> below.)
699 Returns the 3-digit code from the last command. If a command is pending
700 then the value 0 is returned. (See L<PSEUDO RESPONSES> below.)
704 Returns non-zero if the last code value was greater than zero and
705 less than 400. This holds true for most command servers. Servers
706 where this does not hold may override this method.
710 Returns the most significant digit of the current status code. If a command
711 is pending then C<CMD_PENDING> is returned.
713 =item datasend ( DATA )
715 Send data to the remote server, converting LF to CRLF. Any line starting
716 with a '.' will be prefixed with another '.'.
717 C<DATA> may be an array or a reference to an array.
718 The C<DATA> passed in must be encoded by the caller to octets of whatever
719 encoding is required, e.g. by using the Encode module's C<encode()> function.
723 End the sending of data to the remote server. This is done by ensuring that
724 the data already sent ends with CRLF then sending '.CRLF' to end the
725 transmission. Once this data has been sent C<dataend> calls C<response> and
726 returns true if C<response> returns CMD_OK.
732 These methods are not intended to be called by the user, but used or
733 over-ridden by a sub-class of C<Net::Cmd>
737 =item debug_print ( DIR, TEXT )
739 Print debugging information. C<DIR> denotes the direction I<true> being
740 data being sent to the server. Calls C<debug_text> before printing to
743 =item debug_text ( DIR, TEXT )
745 This method is called to print debugging information. TEXT is
746 the text being sent. The method should return the text to be printed.
748 This is primarily meant for the use of modules such as FTP where passwords
749 are sent, but we do not want to display them in the debugging information.
751 =item command ( CMD [, ARGS, ... ])
753 Send a command to the command server. All arguments are first joined with
754 a space character and CRLF is appended, this string is then sent to the
757 Returns undef upon failure.
761 Sets the status code to 580 and the response text to 'Unsupported command'.
766 Obtain a response from the server. Upon success the most significant digit
767 of the status code is returned. Upon failure, timeout etc., I<CMD_ERROR> is
770 =item parse_response ( TEXT )
772 This method is called by C<response> as a method with one argument. It should
773 return an array of 2 values, the 3-digit status code and a flag which is true
774 when this is part of a multi-line response and this line is not the last.
778 Retrieve one line, delimited by CRLF, from the remote server. Returns I<undef>
781 B<NOTE>: If you do use this method for any reason, please remember to add
782 some C<debug_print> calls into your method.
784 =item ungetline ( TEXT )
786 Unget a line of text from the server.
788 =item rawdatasend ( DATA )
790 Send data to the remote server without performing any conversions. C<DATA>
792 As with C<datasend()>, the C<DATA> passed in must be encoded by the caller
793 to octets of whatever encoding is required, e.g. by using the Encode module's
794 C<encode()> function.
796 =item read_until_dot ()
798 Read data from the remote server until a line consisting of a single '.'.
799 Any lines starting with '..' will have one of the '.'s removed.
801 Returns a reference to a list containing the lines, or I<undef> upon failure.
805 Returns a filehandle tied to the Net::Cmd object. After issuing a
806 command, you may read from this filehandle using read() or <>. The
807 filehandle will return EOF when the final dot is encountered.
808 Similarly, you may write to the filehandle in order to send data to
809 the server after issuing a command that expects data to be written.
811 See the Net::POP3 and Net::SMTP modules for examples of this.
815 =head1 PSEUDO RESPONSES
817 Normally the values returned by C<message()> and C<code()> are
818 obtained from the remote server, but in a few circumstances, as
819 detailed below, C<Net::Cmd> will return values that it sets. You
820 can alter this behavior by overriding DEF_REPLY_CODE() to specify
821 a different default reply code, or overriding one of the specific
822 error handling methods below.
828 Before any command has executed or if an unexpected error occurs
829 C<code()> will return "421" (temporary connection failure) and
830 C<message()> will return undef.
832 =item Connection closed
834 If the underlying C<IO::Handle> is closed, or if there are
835 any read or write failures, the file handle will be forced closed,
836 and C<code()> will return "421" (temporary connection failure)
837 and C<message()> will return "[$pkg] Connection closed"
838 (where $pkg is the name of the class that subclassed C<Net::Cmd>).
839 The _set_status_closed() method can be overridden to set a different
840 message (by calling set_status()) or otherwise trap this error.
844 If there is a read or write timeout C<code()> will return "421"
845 (temporary connection failure) and C<message()> will return
846 "[$pkg] Timeout" (where $pkg is the name of the class
847 that subclassed C<Net::Cmd>). The _set_status_timeout() method
848 can be overridden to set a different message (by calling set_status())
849 or otherwise trap this error.
855 C<Net::Cmd> exports six subroutines, five of these, C<CMD_INFO>, C<CMD_OK>,
856 C<CMD_MORE>, C<CMD_REJECT> and C<CMD_ERROR>, correspond to possible results
857 of C<response> and C<status>. The sixth is C<CMD_PENDING>.
861 Graham Barr E<lt>F<gbarr@pobox.com>E<gt>
863 Steve Hay E<lt>F<shay@cpan.org>E<gt> is now maintaining libnet as of version
868 Versions up to 2.29_1 Copyright (c) 1995-2006 Graham Barr. All rights reserved.
869 Changes in Version 2.29_2 onwards Copyright (C) 2013-2014 Steve Hay. All rights
872 This module is free software; you can redistribute it and/or modify it under the
873 same terms as Perl itself, i.e. under the terms of either the GNU General Public
874 License or the Artistic License, as specified in the F<LICENCE> file.