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.
25 require Convert::EBCDIC;
27 # Convert::EBCDIC->import;
31 our $VERSION = "3.08";
32 our @ISA = qw(Exporter);
33 our @EXPORT = qw(CMD_INFO CMD_OK CMD_MORE CMD_REJECT CMD_ERROR CMD_PENDING);
35 use constant CMD_INFO => 1;
36 use constant CMD_OK => 2;
37 use constant CMD_MORE => 3;
38 use constant CMD_REJECT => 4;
39 use constant CMD_ERROR => 5;
40 use constant CMD_PENDING => 0;
42 use constant DEF_REPLY_CODE => 421;
46 my $tr = $^O eq 'os390' ? Convert::EBCDIC->new() : undef;
51 unless (exists ${*$cmd}{'net_cmd_asciipeer'}) {
53 my $ebcdicstr = $tr->toebcdic($string);
54 ${*$cmd}{'net_cmd_asciipeer'} = $string !~ /^\d+/ && $ebcdicstr =~ /^\d+/;
57 ${*$cmd}{'net_cmd_asciipeer'}
58 ? $tr->toebcdic($_[0])
65 ${*$cmd}{'net_cmd_asciipeer'}
72 no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict)
83 while ($pkg = shift @do) {
84 next if defined $done{$pkg};
89 defined ${"${pkg}::VERSION"}
90 ? "(" . ${"${pkg}::VERSION"} . ")"
94 $cmd->debug_print(1, "${spc}${pkg}${v}\n");
96 if (@{"${pkg}::ISA"}) {
97 @spc{@{"${pkg}::ISA"}} = (" " . $spc{$pkg}) x @{"${pkg}::ISA"};
98 unshift(@do, @{"${pkg}::ISA"});
105 @_ == 1 or @_ == 2 or croak 'usage: $obj->debug([LEVEL])';
107 my ($cmd, $level) = @_;
108 my $pkg = ref($cmd) || $cmd;
112 $oldval = ${*$cmd}{'net_cmd_debug'} || 0;
115 $oldval = $debug{$pkg} || 0;
121 $level = $debug{$pkg} || 0
122 unless defined $level;
125 if ($level && !exists $debug{$pkg});
128 ${*$cmd}{'net_cmd_debug'} = $level;
131 $debug{$pkg} = $level;
139 @_ == 1 or croak 'usage: $obj->message()';
144 ? @{${*$cmd}{'net_cmd_resp'}}
145 : join("", @{${*$cmd}{'net_cmd_resp'}});
149 sub debug_text { $_[2] }
153 my ($cmd, $out, $text) = @_;
154 print STDERR $cmd, ($out ? '>>> ' : '<<< '), $cmd->debug_text($out, $text);
159 @_ == 1 or croak 'usage: $obj->code()';
163 ${*$cmd}{'net_cmd_code'} = $cmd->DEF_REPLY_CODE
164 unless exists ${*$cmd}{'net_cmd_code'};
166 ${*$cmd}{'net_cmd_code'};
171 @_ == 1 or croak 'usage: $obj->status()';
175 substr(${*$cmd}{'net_cmd_code'}, 0, 1);
180 @_ == 3 or croak 'usage: $obj->set_status(CODE, MESSAGE)';
183 my ($code, $resp) = @_;
185 $resp = defined $resp ? [$resp] : []
188 (${*$cmd}{'net_cmd_code'}, ${*$cmd}{'net_cmd_resp'}) = ($code, $resp);
193 sub _syswrite_with_timeout {
197 my $len = length($line);
200 vec($win, fileno($cmd), 1) = 1;
201 my $timeout = $cmd->timeout || undef;
203 my $pending = $timeout;
205 local $SIG{PIPE} = 'IGNORE' unless $^O eq 'MacOS';
209 my $nfound = select(undef, $wout = $win, undef, $pending);
210 if ((defined $nfound and $nfound > 0) or -f $cmd) # -f for testing on win32
212 my $w = syswrite($cmd, $line, $len, $offset);
213 if (! defined($w) ) {
216 $cmd->_set_status_closed($err);
222 elsif ($nfound == -1) {
224 if ( defined($timeout) ) {
225 redo if ($pending = $timeout - ( time - $initial ) ) > 0;
226 $cmd->_set_status_timeout;
233 $cmd->_set_status_closed($err);
237 $cmd->_set_status_timeout;
245 sub _set_status_timeout {
247 my $pkg = ref($cmd) || $cmd;
249 $cmd->set_status($cmd->DEF_REPLY_CODE, "[$pkg] Timeout");
250 carp(ref($cmd) . ": " . (caller(1))[3] . "(): timeout") if $cmd->debug;
253 sub _set_status_closed {
256 my $pkg = ref($cmd) || $cmd;
258 $cmd->set_status($cmd->DEF_REPLY_CODE, "[$pkg] Connection closed");
259 carp(ref($cmd) . ": " . (caller(1))[3]
260 . "(): unexpected EOF on command channel: $err") if $cmd->debug;
265 if (!defined fileno($cmd)) {
266 $cmd->_set_status_closed($!);
279 if (exists ${*$cmd}{'net_cmd_last_ch'});
286 ? do { my $n = $_; $n =~ tr/\n/ /; $n }
290 $str = $cmd->toascii($str) if $tr;
293 $cmd->debug_print(1, $str)
296 # though documented to return undef on failure, the legacy behavior
297 # was to return $cmd even on failure, so this odd construct does that
298 $cmd->_syswrite_with_timeout($str)
307 @_ == 1 or croak 'usage: $obj->ok()';
309 my $code = $_[0]->code;
310 0 < $code && $code < 400;
317 $cmd->set_status(580, 'Unsupported command');
326 ${*$cmd}{'net_cmd_lines'} ||= [];
328 return shift @{${*$cmd}{'net_cmd_lines'}}
329 if scalar(@{${*$cmd}{'net_cmd_lines'}});
331 my $partial = defined(${*$cmd}{'net_cmd_partial'}) ? ${*$cmd}{'net_cmd_partial'} : "";
336 my $fd = fileno($cmd);
338 vec($rin, $fd, 1) = 1;
342 until (scalar(@{${*$cmd}{'net_cmd_lines'}})) {
343 my $timeout = $cmd->timeout || undef;
346 my $select_ret = select($rout = $rin, undef, undef, $timeout);
347 if ($select_ret > 0) {
348 unless (sysread($cmd, $buf = "", 1024)) {
351 $cmd->_set_status_closed($err);
355 substr($buf, 0, 0) = $partial; ## prepend from last sysread
357 my @buf = split(/\015?\012/, $buf, -1); ## break into lines
361 push(@{${*$cmd}{'net_cmd_lines'}}, map {"$_\n"} @buf);
365 $cmd->_set_status_timeout;
370 ${*$cmd}{'net_cmd_partial'} = $partial;
373 foreach my $ln (@{${*$cmd}{'net_cmd_lines'}}) {
374 $ln = $cmd->toebcdic($ln);
378 shift @{${*$cmd}{'net_cmd_lines'}};
383 my ($cmd, $str) = @_;
385 ${*$cmd}{'net_cmd_lines'} ||= [];
386 unshift(@{${*$cmd}{'net_cmd_lines'}}, $str);
392 unless $_[1] =~ s/^(\d\d\d)(.?)//o;
399 my ($code, $more) = (undef) x 2;
401 $cmd->set_status($cmd->DEF_REPLY_CODE, undef); # initialize the response
404 my $str = $cmd->getline();
407 unless defined($str);
409 $cmd->debug_print(0, $str)
412 ($code, $more) = $cmd->parse_response($str);
413 unless (defined $code) {
414 carp("$cmd: response(): parse error in '$str'") if ($cmd->debug);
415 $cmd->ungetline($str);
416 $@ = $str; # $@ used as tunneling hack
420 ${*$cmd}{'net_cmd_code'} = $code;
422 push(@{${*$cmd}{'net_cmd_resp'}}, $str);
427 return unless defined $code;
438 my $str = $cmd->getline() or return;
440 $cmd->debug_print(0, $str)
441 if ($cmd->debug & 4);
443 last if ($str =~ /^\.\r?\n/o);
461 my $arr = @_ == 1 && ref($_[0]) ? $_[0] : \@_;
462 my $line = join("", @$arr);
464 # Perls < 5.10.1 (with the exception of 5.8.9) have a performance problem with
465 # the substitutions below when dealing with strings stored internally in
466 # UTF-8, so downgrade them (if possible).
467 # Data passed to datasend() should be encoded to octets upstream already so
468 # shouldn't even have the UTF-8 flag on to start with, but if it so happens
469 # that the octets are stored in an upgraded string (as can sometimes occur)
470 # then they would still downgrade without fail anyway.
471 # Only Unicode codepoints > 0xFF stored in an upgraded string will fail to
472 # downgrade. We fail silently in that case, and a "Wide character in print"
473 # warning will be emitted later by syswrite().
474 utf8::downgrade($line, 1) if $] < 5.010001 && $] != 5.008009;
479 my $last_ch = ${*$cmd}{'net_cmd_last_ch'};
481 # We have not send anything yet, so last_ch = "\012" means we are at the start of a line
482 $last_ch = ${*$cmd}{'net_cmd_last_ch'} = "\012" unless defined $last_ch;
484 return 1 unless length $line;
487 foreach my $b (split(/\n/, $line)) {
488 $cmd->debug_print(1, "$b\n");
492 $line =~ tr/\r\n/\015\012/ unless "\r" eq "\015";
496 if ($last_ch eq "\015") {
497 # Remove \012 so it does not get prefixed with another \015 below
498 # and escape the . if there is one following it because the fixup
499 # below will not find it
500 $first_ch = "\012" if $line =~ s/^\012(\.?)/$1$1/;
502 elsif ($last_ch eq "\012") {
503 # Fixup below will not find the . as the first character of the buffer
504 $first_ch = "." if $line =~ /^\./;
507 $line =~ s/\015?\012(\.?)/\015\012$1$1/sg;
509 substr($line, 0, 0) = $first_ch;
511 ${*$cmd}{'net_cmd_last_ch'} = substr($line, -1, 1);
513 $cmd->_syswrite_with_timeout($line)
522 my $arr = @_ == 1 && ref($_[0]) ? $_[0] : \@_;
523 my $line = join("", @$arr);
529 unless length($line);
533 print STDERR $b, join("\n$b", split(/\n/, $line)), "\n";
536 $cmd->_syswrite_with_timeout($line)
549 my $ch = ${*$cmd}{'net_cmd_last_ch'};
555 elsif ($ch ne "\012") {
556 $tosend = "\015\012";
559 $tosend .= ".\015\012";
561 $cmd->debug_print(1, ".\n")
564 $cmd->_syswrite_with_timeout($tosend)
567 delete ${*$cmd}{'net_cmd_last_ch'};
569 $cmd->response() == CMD_OK;
572 # read and write to tied filehandle
575 ${*$cmd}{'net_cmd_readbuf'} = '';
577 tie *$fh, ref($cmd), $cmd;
588 # Tied filehandle read. Reads requested data length, returning
589 # end-of-file when the dot is encountered.
592 my ($len, $offset) = @_[1, 2];
593 return unless exists ${*$cmd}{'net_cmd_readbuf'};
595 while (!$done and length(${*$cmd}{'net_cmd_readbuf'}) < $len) {
596 ${*$cmd}{'net_cmd_readbuf'} .= $cmd->getline() or return;
597 $done++ if ${*$cmd}{'net_cmd_readbuf'} =~ s/^\.\r?\n\Z//m;
601 substr($_[0], $offset + 0) = substr(${*$cmd}{'net_cmd_readbuf'}, 0, $len);
602 substr(${*$cmd}{'net_cmd_readbuf'}, 0, $len) = '';
603 delete ${*$cmd}{'net_cmd_readbuf'} if $done;
612 # in this context, we use the presence of readbuf to
613 # indicate that we have not yet reached the eof
614 return unless exists ${*$cmd}{'net_cmd_readbuf'};
615 my $line = $cmd->getline;
616 return if $line =~ /^\.\r?\n/;
623 my ($buf, $len, $offset) = @_;
624 $len ||= length($buf);
626 return unless $cmd->datasend(substr($buf, $offset, $len));
627 ${*$cmd}{'net_cmd_sending'}++; # flag that we should call dataend()
634 my $r = exists(${*$cmd}{'net_cmd_sending'}) ? $cmd->dataend : 1;
635 delete ${*$cmd}{'net_cmd_readbuf'};
636 delete ${*$cmd}{'net_cmd_sending'};
647 Net::Cmd - Network Command class (as used by FTP, SMTP etc)
657 C<Net::Cmd> is a collection of methods that can be inherited by a sub class
658 of C<IO::Handle>. These methods implement the functionality required for a
659 command based protocol, for example FTP and SMTP.
663 These methods provide a user interface to the C<Net::Cmd> object.
667 =item debug ( VALUE )
669 Set the level of debug information for this object. If C<VALUE> is not given
670 then the current state is returned. Otherwise the state is changed to
671 C<VALUE> and the previous state returned.
674 may implement different levels of debug but a non-zero value results in
675 copies of all commands and responses also being sent to STDERR.
677 If C<VALUE> is C<undef> then the debug level will be set to the default
678 debug level for the class.
680 This method can also be called as a I<static> method to set/get the default
681 debug level for a given class.
685 Returns the text message returned from the last command. In a scalar
686 context it returns a single string, in a list context it will return
687 each line as a separate element. (See L<PSEUDO RESPONSES> below.)
691 Returns the 3-digit code from the last command. If a command is pending
692 then the value 0 is returned. (See L<PSEUDO RESPONSES> below.)
696 Returns non-zero if the last code value was greater than zero and
697 less than 400. This holds true for most command servers. Servers
698 where this does not hold may override this method.
702 Returns the most significant digit of the current status code. If a command
703 is pending then C<CMD_PENDING> is returned.
705 =item datasend ( DATA )
707 Send data to the remote server, converting LF to CRLF. Any line starting
708 with a '.' will be prefixed with another '.'.
709 C<DATA> may be an array or a reference to an array.
710 The C<DATA> passed in must be encoded by the caller to octets of whatever
711 encoding is required, e.g. by using the Encode module's C<encode()> function.
715 End the sending of data to the remote server. This is done by ensuring that
716 the data already sent ends with CRLF then sending '.CRLF' to end the
717 transmission. Once this data has been sent C<dataend> calls C<response> and
718 returns true if C<response> returns CMD_OK.
724 These methods are not intended to be called by the user, but used or
725 over-ridden by a sub-class of C<Net::Cmd>
729 =item debug_print ( DIR, TEXT )
731 Print debugging information. C<DIR> denotes the direction I<true> being
732 data being sent to the server. Calls C<debug_text> before printing to
735 =item debug_text ( DIR, TEXT )
737 This method is called to print debugging information. TEXT is
738 the text being sent. The method should return the text to be printed.
740 This is primarily meant for the use of modules such as FTP where passwords
741 are sent, but we do not want to display them in the debugging information.
743 =item command ( CMD [, ARGS, ... ])
745 Send a command to the command server. All arguments are first joined with
746 a space character and CRLF is appended, this string is then sent to the
749 Returns undef upon failure.
753 Sets the status code to 580 and the response text to 'Unsupported command'.
758 Obtain a response from the server. Upon success the most significant digit
759 of the status code is returned. Upon failure, timeout etc., I<CMD_ERROR> is
762 =item parse_response ( TEXT )
764 This method is called by C<response> as a method with one argument. It should
765 return an array of 2 values, the 3-digit status code and a flag which is true
766 when this is part of a multi-line response and this line is not the last.
770 Retrieve one line, delimited by CRLF, from the remote server. Returns I<undef>
773 B<NOTE>: If you do use this method for any reason, please remember to add
774 some C<debug_print> calls into your method.
776 =item ungetline ( TEXT )
778 Unget a line of text from the server.
780 =item rawdatasend ( DATA )
782 Send data to the remote server without performing any conversions. C<DATA>
784 As with C<datasend()>, the C<DATA> passed in must be encoded by the caller
785 to octets of whatever encoding is required, e.g. by using the Encode module's
786 C<encode()> function.
788 =item read_until_dot ()
790 Read data from the remote server until a line consisting of a single '.'.
791 Any lines starting with '..' will have one of the '.'s removed.
793 Returns a reference to a list containing the lines, or I<undef> upon failure.
797 Returns a filehandle tied to the Net::Cmd object. After issuing a
798 command, you may read from this filehandle using read() or <>. The
799 filehandle will return EOF when the final dot is encountered.
800 Similarly, you may write to the filehandle in order to send data to
801 the server after issuing a command that expects data to be written.
803 See the Net::POP3 and Net::SMTP modules for examples of this.
807 =head1 PSEUDO RESPONSES
809 Normally the values returned by C<message()> and C<code()> are
810 obtained from the remote server, but in a few circumstances, as
811 detailed below, C<Net::Cmd> will return values that it sets. You
812 can alter this behavior by overriding DEF_REPLY_CODE() to specify
813 a different default reply code, or overriding one of the specific
814 error handling methods below.
820 Before any command has executed or if an unexpected error occurs
821 C<code()> will return "421" (temporary connection failure) and
822 C<message()> will return undef.
824 =item Connection closed
826 If the underlying C<IO::Handle> is closed, or if there are
827 any read or write failures, the file handle will be forced closed,
828 and C<code()> will return "421" (temporary connection failure)
829 and C<message()> will return "[$pkg] Connection closed"
830 (where $pkg is the name of the class that subclassed C<Net::Cmd>).
831 The _set_status_closed() method can be overridden to set a different
832 message (by calling set_status()) or otherwise trap this error.
836 If there is a read or write timeout C<code()> will return "421"
837 (temporary connection failure) and C<message()> will return
838 "[$pkg] Timeout" (where $pkg is the name of the class
839 that subclassed C<Net::Cmd>). The _set_status_timeout() method
840 can be overridden to set a different message (by calling set_status())
841 or otherwise trap this error.
847 C<Net::Cmd> exports six subroutines, five of these, C<CMD_INFO>, C<CMD_OK>,
848 C<CMD_MORE>, C<CMD_REJECT> and C<CMD_ERROR>, correspond to possible results
849 of C<response> and C<status>. The sixth is C<CMD_PENDING>.
853 Graham Barr E<lt>F<gbarr@pobox.com>E<gt>
855 Steve Hay E<lt>F<shay@cpan.org>E<gt> is now maintaining libnet as of version
860 Versions up to 2.29_1 Copyright (c) 1995-2006 Graham Barr. All rights reserved.
861 Changes in Version 2.29_2 onwards Copyright (C) 2013-2014 Steve Hay. All rights
864 This module is free software; you can redistribute it and/or modify it under the
865 same terms as Perl itself, i.e. under the terms of either the GNU General Public
866 License or the Artistic License, as specified in the F<LICENCE> file.