blib/lib/Net/SSH2/Cisco.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Net::SSH2::Cisco;
2  
3 ##################################################
4 # Michael Vincent
5 # www.VinsWorld.com
6 ##################################################
7  
8 # NOTE: This module is basically a cut/paste of:
9 # 70% Net::Telnet
10 # 20% Net::Telnet::Cisco
11 # 5% Net::SSH2(::Channel)
12 # 5% original hack to make it all work together
13 #
14 # - I tried to create a child class of Net::SSH2 to no avail due to
15 # the C-type inside-out object it returns and my lack of experience.
16 #
17 # - I tried to pass a Net::SSH2 connection to Net::Telnet(::Cisco) fhopen()
18 # method, but it returned:
19 #
20 # Not a GLOB reference at [...]/perl/vendor/lib/Net/Telnet.pm line 679.
21 #
22 # - I tried to use Net::Telnet in my @ISA with AUTOLOAD to leverage the
23 # accessors and code already written, but I'm not creating a Net::Telnet
24 # object and I couldn't get it to work.
25 #
26 # That left me the (?only?) option - to write this Franken-module "liberally
27 # borrowing" from much smarter, more talented programmers than I.
28  
29 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 our $VERSION = '0.04';
33 our @ISA;
34  
35 1 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 0 ▶use Net::SSH2 0.51;
Subroutine BEGIN: called CC=1 SCAR=2.6
37 use Socket qw(inet_ntoa AF_INET IPPROTO_TCP);
38 my $HAVE_IO_Socket_IP = 0;
39 eval "use IO::Socket::IP -register";
40 if(!$@) {
41 $HAVE_IO_Socket_IP = 1;
42 push @ISA, "IO::Socket::IP"
43 } else {
44 require IO::Socket::INET;
45 push @ISA, "IO::Socket::INET"
46 }
47  
48 my $AF_INET6 = eval { Socket::AF_INET6() };
49 my $AF_UNSPEC = eval { Socket::AF_UNSPEC() };
50 my $AI_NUMERICHOST = eval { Socket::AI_NUMERICHOST() };
51 my $NI_NUMERICHOST = eval { Socket::NI_NUMERICHOST() };
52  
53 $|++;
54  
55 ##################################################
56 # Start Public Module
57 ##################################################
58  
59 sub new {
60 my $self = shift;
61 my $class = ref($self) || $self;
62  
63 my ($fh_open, $host);
64 my %params = (
65 always_waitfor_prompt => 1,
66 autopage => 1,
67 bin_mode => 0,
68 blocking => 0,
69 buf => "",
70 cmd_prompt => '/(?m:^(?:[\w.\/]+\:)?[\w.-]+\s?(?:\(config[^\)]*\))?\s?[\$#>]\s?(?:\(enable\))?\s*$)/',
71 cmd_rm_mode => "auto",
72 dumplog => '',
73 eofile => 1,
74 errormode => "die",
75 errormsg => "",
76 fh_open => undef,
77 host => "localhost",
78 ignore_warnings => 0,
79 inputlog => '',
80 last_cmd => '',
81 last_prompt => '',
82 maxbufsize => 1_048_576,
83 more_prompt => '/(?m:^\s*--More--)/',
84 normalize_cmd => 1,
85 ofs => "",
86 opened => '',
87 outputlog => '',
88 ors => "\n",
89 peer_family => 'ipv4',
90 port => 22,
91 rs => "\n",
92 send_wakeup => 0,
93 time_out => 10,
94 timedout => '',
95 waitfor_clear => 1,
96 waitfor_pause => 0.2,
97 warnings => '/(?mx:^% Unknown VPN
98 |^%IP routing table VRF.* does not exist. Create first$
99 |^%No CEF interface information
100 |^%No matching route to delete$
101 |^%Not all config may be removed and may reappear after reactivating/
102 )/',
103 );
104  
105 $params{_SSH_} = Net::SSH2->new() or return;
106 $self = bless \%params, $class;
107  
108 my %args;
109 if (@_ == 1) {
110 ($host) = @_
111 } else {
112 %args = @_;
113 for (keys(%args)) {
114 if (/^-?always_waitfor_prompt$/i) {
115 $self->always_waitfor_prompt($args{$_});
116 } elsif (/^-?autopage$/i) {
117 $self->autopage($args{$_})
118 } elsif (/^-?binmode$/i) {
119 $self->binmode($args{$_})
120 } elsif (/^-?blocking$/i) {
121 $self->blocking($args{$_})
122 } elsif (/^-?cmd_remove_mode$/i) {
123 $self->cmd_remove_mode($args{$_})
124 } elsif (/^-?dump_log$/i) {
125 $self->dump_log($args{$_})
126 or return;
127 } elsif (/^-?errmode$/i) {
128 $self->errmode($args{$_})
129 } elsif (/^-?family$/i) {
130 $self->family($args{$_})
131 } elsif (/^-?fhopen$/i) {
132 $fh_open = $args{$_}
133 } elsif (/^-?host$/i) {
134 $host = $args{$_}
135 } elsif (/^-?ignore_warnings$/i) {
136 $self->{ignore_warnings} = $args{$_}
137 } elsif (/^-?input_log$/i) {
138 $self->input_log($args{$_})
139 or return;
140 } elsif (/^-?input_record_separator$/i or /^-?rs$/i) {
141 $self->input_record_separator($args{$_})
142 } elsif (/^-?max_buffer_length$/i) {
143 $self->max_buffer_length($args{$_})
144 } elsif (/^-?more_prompt$/i) {
145 $self->more_prompt($args{$_})
146 } elsif (/^-?normalize_cmd$/i) {
147 $self->normalize_cmd($args{$_})
148 } elsif (/^-?output_field_separator$/i or /^-?ofs$/i) {
149 $self->output_field_separator($args{$_})
150 } elsif (/^-?output_log$/i) {
151 $self->output_log($args{$_})
152 or return;
153 } elsif (/^-?output_record_separator$/i or /^-?ors$/i) {
154 $self->output_record_separator($args{$_})
155 } elsif (/^-?port$/i) {
156 $self->port($args{$_})
157 } elsif (/^-?prompt$/i) {
158 $self->prompt($args{$_})
159 } elsif (/^-?send_wakeup$/i) {
160 $self->send_wakeup($args{$_})
161 } elsif (/^-?timeout$/i) {
162 $self->timeout($args{$_})
163 } elsif (/^-?waitfor_clear$/i) {
164 $self->waitfor_clear($args{$_})
165 } elsif (/^-?waitfor_pause$/i) {
166 $self->waitfor_pause($args{$_})
167 } elsif (/^-?warnings$/i) {
168 $self->{warnings} = $args{$_}
169 } else {
170 # pass through
171 #$params{$_} = $args{$_}
172 &_croak($self, "bad named parameter \"$_\" given " .
173 "to " . ref($self) . "::new()");
174 }
175 }
176 }
177  
178 # $self->open in the if statement so open() not called
179 # if neither 'fh' nor 'host' are provided.
180 if (defined $fh_open) {
181 $self->fhopen($fh_open);
182 $self->open or return
183 } elsif (defined $host) {
184 $self->host($host);
185 $self->open or return
186 }
187  
188 return $self
189 }
190  
191 sub always_waitfor_prompt {
192 my ($self, $arg) = @_;
193 $self->{always_waitfor_prompt} = $arg if defined $arg;
194 return $self->{always_waitfor_prompt}
195 }
196  
197 sub autopage {
198 my ($self, $arg) = @_;
199 $self->{autopage} = $arg if defined $arg;
200 return $self->{autopage}
201 }
202  
203 sub binmode {
204 my ($self, $arg) = @_;
205 $self->{bin_mode} = $arg if defined $arg;
206 return $self->{bin_mode}
207 }
208  
209 sub blocking {
210 my ($self, $arg) = @_;
211 $self->{blocking} = $arg if defined $arg;
212 return $self->{blocking}
213 }
214  
215 sub close {
216 my ($self) = @_;
217  
218 $self->{eofile} = 1;
219 $self->{opened} = '';
220 if (defined $self->{_SSH_CHAN_}) {
221 $self->{_SSH_CHAN_}->close
222 }
223 if (defined $self->{_SSH_}) {
224 $self->{_SSH_}->disconnect
225 }
226 delete $self->{_SSH_CHAN_};
227 delete $self->{_SSH_};
228 1
229 }
230  
231 sub cmd {
232 my ($self, @args) = @_;
233  
234 my $string = '';
235 my $chan = $self->{_SSH_CHAN_};
236 my $clear = $self->{waitfor_clear};
237 my $normal = $self->{normalize_cmd};
238 my $ors = $self->{ors};
239 my $pause = $self->{waitfor_pause};
240 my $prompt = $self->{cmd_prompt};
241 my $rm = $self->{cmd_rm_mode};
242 my $rs = $self->{rs};
243 my $timeout = $self->{time_out};
244  
245 if (!defined $chan) {
246 &_croak($self, "no login " .
247 "for " . ref($self) . "::cmd()");
248 }
249  
250 my $ok = 1;
251 $self->{timedout} = '';
252  
253 my $arg_errmode = &_extract_arg_errmode($self, \@args);
254 local $self->{errormode} = $arg_errmode if $arg_errmode;
255  
256 my $output = [];
257 my $output_ref;
258 if (@_ == 2) {
259 ($string) = ($_[1])
260 } else {
261 my %args = @args;
262 for (keys(%args)) {
263 if (/^-?string$/i) {
264 $string = $args{$_}
265 } elsif (/^-?cmd_remove_mode$/i) {
266 $rm = _parse_cmd_remove_mode($self, $args{$_})
267 } elsif (/^-?input_record_separator$/i or /^-?rs$/i) {
268 $rs = $args{$_}
269 } elsif (/^-?normalize_cmd$/i) {
270 $normal = $args{$_}
271 } elsif (/^-?output$/i) {
272 $output_ref = $args{$_};
273 if (defined($output_ref) and ref($output_ref) eq "ARRAY") {
274 $output = $output_ref;
275 }
276 } elsif (/^-?output_record_separator$/i or /^-?ors$/i) {
277 $ors = $args{$_}
278 } elsif (/^-?prompt$/i) {
279 $prompt = &_parse_prompt($self, $args{$_})
280 or return;
281 } elsif (/^-?timeout$/i) {
282 $timeout = _parse_timeout($self, $args{$_})
283 } elsif (/^-?waitfor_clear$/i) {
284 $clear = $args{$_}
285 } elsif (/^-?waitfor_pause$/i) {
286 $pause = _parse_waitfor_pause($self, $args{$_})
287 or return
288 } else {
289 # pass through
290 #$params{$_} = $args{$_}
291 &_croak($self, "bad named parameter \"$_\" given " .
292 "to " . ref($self) . "::cmd()");
293 }
294 }
295 }
296  
297 #prep
298 local $self->{time_out} = $timeout;
299 local $self->{waitfor_clear} = $clear;
300 $self->errmsg("");
301 chomp $string;
302 $self->{last_cmd} = $string;
303  
304 my ($lines, $last_prompt);
305 {
306 local $self->{errormode} = "return";
307  
308 #send
309 $self->put($string . $ors);
310  
311 #wait
312 select(undef,undef,undef,$pause); # sleep
313  
314 #read
315 ($lines, $last_prompt) = $self->waitfor(
316 match => $prompt,
317 normalize_cmd => $normal
318 );
319 }
320  
321 return $self->error("command timed-out") if $self->timed_out;
322 return $self->error("no output") if not defined $lines;
323 return $self->error($self->errmsg) if $self->errmsg ne "";
324  
325 ## Split lines into an array, keeping record separator at end of line.
326 my $firstpos = 0;
327 my $rs_len = length $rs;
328 while ((my $lastpos = index($lines, $rs, $firstpos)) > -1) {
329 push(@$output, substr($lines, $firstpos, $lastpos - $firstpos + $rs_len));
330 $firstpos = $lastpos + $rs_len
331 }
332 if ($firstpos < length $lines) {
333 push @$output, substr($lines, $firstpos)
334 }
335  
336 # clean up
337 if ($rm eq "auto") {
338 if ((defined @$output[0]) and (@$output[0] =~ /^$string(?:\r)?(?:\n)?/)) {
339 shift @$output
340 }
341 } else {
342 while ($rm--) {
343 shift @$output
344 }
345 }
346 ## Ensure at least a null string when there's no command output - so
347 ## "true" is returned in a list context.
348 unless (@$output) {
349 @$output = ("")
350 }
351  
352 # Look for errors in output
353 for ( my ($i, $lastline) = (0, '');
354 $i <= $#{$output};
355 $lastline = $output->[$i++] ) {
356  
357 # This may have to be a pattern match instead.
358 if ( ( substr $output->[$i], 0, 1 ) eq '%' ) {
359 if ( $output->[$i] =~ /'\^' marker/ ) { # Typo & bad arg errors
360 chomp $lastline;
361 $self->error( join "\n",
362 "Last command and router error: ",
363 ( $self->last_prompt . $string ),
364 $lastline,
365 $output->[$i],
366 );
367 splice @$output, $i - 1, 3;
368 } else { # All other errors.
369 chomp $output->[$i];
370 $self->error( join "\n",
371 "Last command and router error: ",
372 ( $self->last_prompt . $string ),
373 $output->[$i],
374 );
375 splice @$output, $i, 2;
376 }
377 $ok = 0;
378 last;
379 }
380 }
381  
382 ## Return command output via named arg, if requested.
383 if (defined $output_ref) {
384 if (ref($output_ref) eq "SCALAR") {
385 $$output_ref = join "", @$output;
386 } elsif (ref($output_ref) eq "HASH") {
387 %$output_ref = @$output;
388 }
389 }
390  
391 wantarray ? @$output : $ok
392 }
393  
394 sub cmd_remove_mode {
395 my ($self, $arg) = @_;
396  
397 if (defined $arg) {
398 if (defined (my $r = _parse_cmd_remove_mode($self, $arg))) {
399 $self->{cmd_rm_mode} = $r
400 }
401 }
402 return $self->{cmd_rm_mode}
403 }
404  
405 sub connect { &open }
406  
407 sub disable {
408 my $self = shift;
409 $self->cmd('disable');
410 if ($self->is_enabled) {
411 return $self->error("Failed to exit enabled mode")
412 }
413 1
414 }
415  
416 sub dump_log {
417 my ($self, $name) = @_;
418  
419 my $fh = $self->{dumplog};
420  
421 if (@_ >= 2) {
422 if (!defined($name) or $name eq "") { # input arg is ""
423 ## Turn off logging.
424 $fh = "";
425 } elsif (&_is_open_fh($name)) { # input arg is an open fh
426 ## Use the open fh for logging.
427 $fh = $name;
428 select((select($fh), $|=1)[$[]); # don't buffer writes
429 } elsif (!ref $name) { # input arg is filename
430 ## Open the file for logging.
431 $fh = &_fname_to_handle($self, $name)
432 or return;
433 select((select($fh), $|=1)[$[]); # don't buffer writes
434 } else {
435 return $self->error("bad Dump_log argument ",
436 "\"$name\": not filename or open fh");
437 }
438 $self->{dumplog} = $fh;
439 }
440 $fh;
441 }
442  
443 sub enable {
444 my $self = shift;
445  
446 my ($en_username, $en_password, $en_passcode, $en_level) = ('','','','');
447 my ($error, $lastline, $orig_errmode, $reset, %seen);
448 my $chan = $self->{_SSH_CHAN_};
449 my $ors = $self->{ors};
450 my $timeout = $self->{time_out};
451  
452 if (!defined $chan) {
453 &_croak($self, "no login " .
454 "for " . ref($self) . "::enable()");
455 }
456  
457 $self->{timedout} = '';
458  
459 if (@_ == 1) { # just passwd given
460 ($en_password) = @_
461 } else {
462 my %args = @_;
463 foreach (keys %args) {
464 if (/^-?name$|^-?login$|^-?user/i) {
465 $en_username = $args{$_}
466 } elsif (/^-?passw/i) {
467 $en_password = $args{$_}
468 } elsif (/^-?passc/i) {
469 $en_passcode = $args{$_}
470 } elsif (/^-?level$/i) {
471 $en_level = $args{$_}
472 } elsif (/^-?timeout$/i) {
473 $timeout = $args{$_}
474 } else {
475 # pass through
476 #$params{$_} = $args{$_}
477 &_croak($self, "bad named parameter \"$_\" given " .
478 "to " . ref($self) . "::enable()");
479 }
480 }
481 }
482  
483 local $self->{time_out} = $timeout;
484  
485 ## Create a subroutine to generate an error for user.
486 # $error = sub {
487 # my($errmsg) = @_;
488  
489 # if ($self->timed_out) {
490 # return $self->error($errmsg);
491 # } elsif ($self->eof) {
492 # ($lastline = $self->lastline) =~ s/\n+//;
493 # return $self->error($errmsg, ": ", $lastline);
494 # } else {
495 # return $self->error($errmsg);
496 # }
497 # };
498  
499 # Store the old prompt without the //s around it.
500 my ($old_prompt) = _prep_regex($self->{cmd_prompt});
501  
502 # We need to expect either a Password prompt or a
503 # typical prompt. If the user doesn't have enough
504 # access to run the 'enable' command, the device
505 # won't even query for a password, it will just
506 # ignore the command and display another [boring] prompt.
507 $self->print("enable " . $en_level);
508  
509 select(undef,undef,undef,$self->{waitfor_pause}); # sleep
510  
511 {
512 my ($prematch, $match) = $self->waitfor(
513 -match => '/[Ll]ogin[:\s]*$/',
514 -match => '/[Uu]sername[:\s]*$/',
515 -match => '/[Pp]assw(?:or)?d[:\s]*$/',
516 -match => '/(?i:Passcode)[:\s]*$/',
517 -match => "/$old_prompt/",
518 ) or do {
519 return $self->error("read eof waiting for enable login or password prompt")
520 if $self->eof;
521 return $self->error("timed-out waiting for enable login or password prompt");
522 };
523  
524 if (not defined $match) {
525 return $self->error("enable failed: access denied or bad name, passwd, etc")
526 } elsif ($match =~ /sername|ogin/) {
527 if (!defined $self->print($en_username)) {
528 return $self->error("enable failed")
529 }
530 $self->{last_prompt} = $match;
531 if ($seen{login}++) {
532 return $self->error("enable failed: access denied or bad username")
533 }
534 redo
535 } elsif ($match =~ /[Pp]assw/ ) {
536 if (!defined $self->print($en_password)) {
537 return $self->error("enable failed")
538 }
539 $self->{last_prompt} = $match;
540 if ($seen{passwd}++) {
541 return $self->error("enable failed: access denied or bad password")
542 }
543 redo
544 } elsif ($match =~ /(?i:Passcode)/ ) {
545 if (!defined $self->print($en_passcode)) {
546 return $self->error("enable failed")
547 }
548 $self->{last_prompt} = $match;
549 if ($seen{passcode}++) {
550 return $self->error("enable failed: access denied or bad passcode")
551 }
552 redo
553 } elsif ($match =~ /$old_prompt/) {
554 ## Success! Exit the block.
555 $self->{last_prompt} = $match;
556 last
557 } else {
558 return $self->error("enable received unexpected prompt. Aborting.")
559 }
560 }
561  
562 if (($en_level eq '') or ($en_level =~ /^[1-9]/)) {
563 # Prompts and levels over 1 give a #/(enable) prompt.
564 if ($self->is_enabled) {
565 return 1
566 } else {
567 return $self->error("Failed to enter enable mode")
568 }
569 } else {
570 # Assume success
571 return 1
572 }
573 }
574  
575 sub eof {
576 my ($self) = @_;
577 exists $self->{_SSH_CHAN_} ? ($self->{_SSH_CHAN_}->eof or $self->{eofile}) : $self->{eofile};
578 }
579  
580 sub errmode {
581 my ($self, $arg) = @_;
582  
583 if (defined $arg) {
584 if (defined (my $r = _parse_errmode($self, $arg))) {
585 $self->{errormode} = $r
586 }
587 }
588 return $self->{errormode}
589 }
590  
591 sub errmsg {
592 my ($self, @errmsgs) = @_;
593  
594 if (@_ >= 2) {
595 $self->{errormsg} = join "", @errmsgs;
596 }
597  
598 return $self->{errormsg}
599 }
600  
601 sub error {
602 my ($self, @errmsg) = @_;
603  
604 if ($self->ignore_warnings) {
605 my $errmsg = join '', @errmsg;
606 my $warnings_re = _prep_regex($self->warnings);
607 return if $errmsg =~ /$warnings_re/;
608 }
609  
610 my ($errmsg, $func, $mode, @args);
611 local $_;
612  
613 if (@_ >= 2) {
614 ## Put error message in the object.
615 $errmsg = join "", @errmsg;
616 $self->{errormsg} = $errmsg;
617 ## Do the error action as described by error mode.
618 $mode = $self->{errormode};
619 if (ref($mode) eq "CODE") {
620 &$mode($errmsg);
621 return;
622 } elsif (ref($mode) eq "ARRAY") {
623 ($func, @args) = @$mode;
624 &$func(@args);
625 return;
626 } elsif ($mode =~ /^return$/i) {
627 return;
628 } else { # die
629 if ($errmsg =~ /\n$/) {
630 die $errmsg;
631 } else {
632 ## Die and append caller's line number to message.
633 &_croak($self, $errmsg);
634 }
635 }
636 } else {
637 return $self->{errormsg} ne "";
638 }
639 }
640  
641 sub family {
642 my ($self, $arg) = @_;
643  
644 if (defined $arg) {
645 if (defined (my $r = _parse_family($self, $arg))) {
646 $self->{peer_family} = $r
647 }
648 }
649 return $self->{peer_family}
650 }
651  
652 sub fhopen{
653 my ($self, $arg) = @_;
654 $self->{fh_open} = $arg if defined $arg;
655 return $self->{fh_open}
656 }
657  
658 sub host {
659 my ($self, $arg) = @_;
660 $self->{host} = $arg if defined $arg;
661 return $self->{host}
662 }
663  
664 sub ignore_warnings {
665 my ($self, $arg) = @_;
666 $self->{ignore_warnings} = $arg if defined $arg;
667 return $self->{ignore_warnings}
668 }
669  
670 sub input_log {
671 my ($self, $name) = @_;
672  
673 my $fh = $self->{inputlog};
674  
675 if (@_ >= 2) {
676 if (!defined($name) or $name eq "") { # input arg is ""
677 ## Turn off logging.
678 $fh = "";
679 } elsif (&_is_open_fh($name)) { # input arg is an open fh
680 ## Use the open fh for logging.
681 $fh = $name;
682 select((select($fh), $|=1)[$[]); # don't buffer writes
683 } elsif (!ref $name) { # input arg is filename
684 ## Open the file for logging.
685 $fh = &_fname_to_handle($self, $name)
686 or return;
687 select((select($fh), $|=1)[$[]); # don't buffer writes
688 } else {
689 return $self->error("bad Input_log argument ",
690 "\"$name\": not filename or open fh");
691 }
692 $self->{inputlog} = $fh;
693 }
694 $fh;
695 }
696  
697 sub input_record_separator {
698 my ($self, $arg) = @_;
699 $self->{rs} = $arg if (defined $arg and length $arg);
700 return $self->{rs}
701 }
702  
703 sub ios_break {
704 my ($self, $arg) = @_;
705  
706 my $chan = $self->{_SSH_CHAN_};
707 my $ret;
708 if (defined $arg) {
709 $ret = $self->put("\c^$arg")
710 } else {
711 $ret = $self->put("\c^")
712 }
713  
714 return $ret;
715 }
716  
717 sub is_enabled { $_[0]->last_prompt =~ /\#|enable|config/ ? 1 : undef }
718  
719 sub last_cmd {
720 my $self = shift;
721 exists $self->{last_cmd} ? $self->{last_cmd} : undef
722 }
723  
724 sub last_prompt {
725 my $self = shift;
726 exists $self->{last_prompt} ? $self->{last_prompt} : undef
727 }
728  
729 sub login {
730 my ($self, @args) = @_;
731  
732 if (!$self->{opened}) {
733 &_croak($self, "no connect " .
734 "for " . ref($self) . "::login()");
735 }
736  
737 my $block = $self->{blocking};
738 my $prompt = $self->{cmd_prompt};
739 my $timeout = $self->{time_out};
740 my $ssh = $self->{_SSH_};
741 my $sent_wakeup = 0;
742 my ($user, $pass);
743  
744 $self->{timedout} = '';
745  
746 my $arg_errmode = &_extract_arg_errmode($self, \@args);
747 local $self->{errormode} = $arg_errmode if $arg_errmode;
748  
749 if (@_ == 3) { # just username and passwd given
750 ($user, $pass) = (@_[1,2])
751 } else {
752 my %args = @args;
753 for (keys(%args)) {
754 if (/^-?(?:user)?name$/i) {
755 $user = $args{$_}
756 } elsif (/^-?passw(?:ord)?$/i) {
757 $pass = $args{$_}
758 } elsif (/^-?prompt$/i) {
759 $prompt = _parse_prompt($self, $args{$_})
760 or return
761 } elsif (/^-?timeout$/i) {
762 $timeout = _parse_timeout($self, $args{$_})
763 } else {
764 # pass through
765 #$params{$_} = $args{$_}
766 &_croak($self, "bad named parameter \"$_\" given ",
767 "to " . ref($self) . "::login()");
768 }
769 }
770 }
771  
772 if (!defined $user) {
773 &_croak($self,"username argument not given to " . ref($self) . "::login()")
774 }
775 if (!defined $pass) {
776 &_croak($self,"password argument not given to " . ref($self) . "::login()")
777 }
778  
779 local $self->{time_out} = $timeout;
780  
781 # This is where we'd do 'connect' send_wakeup if Net::SSH2 supported
782 if ($self->{send_wakeup} eq 'connect') {
783 $sent_wakeup = 1;
784  
785 # my $old_sep = $self->output_record_separator;
786 # $self->output_record_separator("\n");
787 # $self->print('');
788 # $self->output_record_separator($old_sep);
789 }
790  
791 AUTH:
792 if ($ssh->auth_password($user, $pass)) {
793 my $chan = $ssh->channel();
794 $chan->blocking($block); # 0 Needed on Windows
795 $chan->shell();
796 $self->{_SSH_CHAN_} = $chan;
797  
798 # flush buffer, read off first prompt
799 if ($sent_wakeup == 0 && $self->{send_wakeup} eq 'noflush') {
800  
801 # do nothing
802 $sent_wakeup = 1;
803 } else {
804 $sent_wakeup = 1;
805 $self->waitfor($self->{cmd_prompt});
806 }
807 } else {
808 # This is where we'd do 'timeout' send_wakeup if Net::SSH2 supported
809 if ($sent_wakeup == 0 && $self->{send_wakeup} eq 'timeout') {
810 $sent_wakeup = 1;
811  
812 # my $old_sep = $self->output_record_separator;
813 # $self->output_record_separator("\n");
814 # $self->print('');
815 # $self->output_record_separator($old_sep);
816  
817 # goto AUTH;
818 }
819 my ($errcode, $errname, $errstr) = $ssh->error;
820 return $self->error("Net::SSH2 error $errcode:$errname [$errstr]\nauthentication failed for user - `$user'")
821 }
822 1
823 }
824  
825 sub max_buffer_length {
826 my ($self, $arg) = @_;
827  
828 my $minbufsize = 512;
829  
830 if (defined $arg) {
831 if ($arg =~ /^\d+$/) {
832 $self->{maxbufsize} = $arg
833 } else {
834 &_carp($self, "ignoring bad Max_buffer_length " .
835 "argument \"$arg\": it's not a positive integer");
836 }
837 }
838  
839 ## Adjust up values that are too small.
840 if ($self->{maxbufsize} < $minbufsize) {
841 $self->{maxbufsize} = $minbufsize;
842 }
843  
844 return $self->{maxbufsize}
845 }
846  
847 sub more_prompt {
848 my ($self, $arg) = @_;
849  
850 if (defined $arg) {
851 $self->_match_check($arg);
852 $self->{more_prompt} = $arg;
853 }
854 return $self->{more_prompt};
855 }
856  
857 sub normalize_cmd {
858 my ($self, $arg) = @_;
859 $self->{normalize_cmd} = $arg if defined $arg;
860 return $self->{normalize_cmd}
861 }
862  
863 sub ofs { &output_field_separator; }
864  
865 sub open {
866 my ($self, @args) = @_;
867  
868 return 1 if $self->{opened};
869  
870 my $ssh = $self->{_SSH_};
871 my $family = $self->{peer_family};
872 my $fh = $self->{fh_open};
873 my $host = $self->{host};
874 my $port = $self->{port};
875 my $timeout = $self->{time_out};
876  
877 $self->{timedout} = '';
878  
879 my $arg_errmode = &_extract_arg_errmode($self, \@args);
880 local $self->{errormode} = $arg_errmode if $arg_errmode;
881  
882 if (@_ == 2) {
883 ($host) = $_[1]
884 } else {
885 my %args = @args;
886 for (keys(%args)) {
887 if (/^-?fhopen$/i) {
888 $fh = $args{$_}
889 } elsif (/^-?host$/i) {
890 $host = $args{$_}
891 } elsif (/^-?family$/i) {
892 $family = _parse_family($self, $args{$_})
893 } elsif (/^-?port$/i) {
894 $port = _parse_port($self, $args{$_})
895 } elsif (/^-?timeout$/i) {
896 $timeout = _parse_timeout($self, $args{$_})
897 } else {
898 # pass through
899 #$params{$_} = $args{$_}
900 &_croak($self, "bad named parameter \"$_\" given ",
901 "to " . ref($self) . "::connect()");
902 }
903 }
904 }
905  
906 local $self->{time_out} = $timeout;
907  
908 my $r;
909 # IO::Socket object provided
910 if (defined $fh) {
911 $r = $ssh->connect($fh)
912 # host provided
913 } else {
914 # resolve
915 if (defined(my $res = _resolv($self, $host, _parse_family_to_num($self, $family)))) {
916 $host = $res->{addr};
917 $port = $res->{port} || $port
918 } else {
919 return $self->error($self->errmsg)
920 }
921 # connect if IPv4
922 if ($family eq 'ipv4') {
923 $ssh->timeout($timeout*1000); # timeout is in millisecs
924 $r = $ssh->connect($host, $port)
925  
926 # if IPv6, Net::SSH2 doesn't yet support,
927 # so need to create our own IO::Socket::IP
928 } else {
929 my $socket = IO::Socket::IP->new(
930 PeerHost => $host,
931 PeerPort => $port,
932 Timeout => $timeout,
933 Family => _parse_family_to_num($self, $family)
934 );
935 if (!$socket) {
936 return $self->error("unable to connect to [$family] host - `$host:$port'")
937 }
938 $r = $ssh->connect($socket);
939 }
940 }
941 if (! $r) {
942 my ($errcode, $errname, $errstr) = $ssh->error;
943 return $self->error("Net::SSH2 error - $errcode:$errname = $errstr\nunable to connect to host - `$host:$port'")
944 }
945  
946 $self->{buf} = "";
947 $self->{eofile} = '';
948 $self->{errormsg} = "";
949 $self->{opened} = 1;
950 $self->{timedout} = '';
951 1
952 }
953  
954 sub ors { &output_record_separator }
955  
956 sub output_field_separator {
957 my ($self, $arg) = @_;
958 $self->{ofs} = $arg if (defined $arg and length $arg);
959 return $self->{ofs}
960 }
961  
962 sub output_log {
963 my ($self, $name) = @_;
964  
965 my $fh = $self->{outputlog};
966  
967 if (@_ >= 2) {
968 if (!defined($name) or $name eq "") { # input arg is ""
969 ## Turn off logging.
970 $fh = "";
971 } elsif (&_is_open_fh($name)) { # input arg is an open fh
972 ## Use the open fh for logging.
973 $fh = $name;
974 select((select($fh), $|=1)[$[]); # don't buffer writes
975 } elsif (!ref $name) { # input arg is filename
976 ## Open the file for logging.
977 $fh = &_fname_to_handle($self, $name)
978 or return;
979 select((select($fh), $|=1)[$[]); # don't buffer writes
980 } else {
981 return $self->error("bad Output_log argument ",
982 "\"$name\": not filename or open fh");
983 }
984 $self->{outputlog} = $fh;
985 }
986 $fh;
987 }
988  
989 sub output_record_separator {
990 my ($self, $arg) = @_;
991 $self->{ors} = $arg if (defined $arg and length $arg);
992 return $self->{ors}
993 }
994  
995 sub port {
996 my ($self, $arg) = @_;
997  
998 if (defined $arg) {
999 if (defined (my $r = _parse_port($self, $arg))) {
1000 $self->{port} = $r
1001 }
1002 }
1003 return $self->{port}
1004 }
1005  
1006 sub print {
1007 my ($self) = shift;
1008  
1009 $self->{timedout} = '';
1010  
1011 return $self->error("write error: filehandle isn't open")
1012 unless $self->{opened};
1013  
1014 ## Add field and record separators.
1015 my $buf = join($self->{"ofs"}, @_) . $self->{"ors"};
1016  
1017 if ($self->{outputlog}) {
1018 &_log_print($self->{outputlog}, $buf);
1019 }
1020  
1021 ## Convert native newlines to CR LF.
1022 # if (!$self->{bin_mode}) {
1023 # $buf =~ s(\n)(\015\012)g;
1024 # }
1025  
1026 &_put($self, \$buf, "print");
1027 }
1028  
1029 sub prompt {
1030 my ($self, $arg) = @_;
1031  
1032 if (defined $arg) {
1033 if (defined (my $r = _parse_prompt($self, $arg))) {
1034 $self->{cmd_prompt} = $r
1035 }
1036 }
1037 return $self->{cmd_prompt}
1038 }
1039  
1040 sub put {
1041 my ($self, @args) = @_;
1042  
1043 local $_;
1044  
1045 my $binmode = $self->{bin_mode};
1046 my $timeout = $self->{time_out};
1047 $self->{timedout} = '';
1048  
1049 my $arg_errmode = &_extract_arg_errmode($self, \@args);
1050 local $self->{errormode} = $arg_errmode if $arg_errmode;
1051  
1052 my $buf;
1053 if (@_ == 2) {
1054 $buf = $_[1];
1055 } elsif (@_ > 2) {
1056 my (undef, %args) = @_;
1057 foreach (keys %args) {
1058 if (/^-?binmode$/i) {
1059 $binmode = $args{$_};
1060 } elsif (/^-?string$/i) {
1061 $buf = $args{$_};
1062 } elsif (/^-?timeout$/i) {
1063 $timeout = &_parse_timeout($self, $args{$_});
1064 } else {
1065 &_croak($self, "bad named parameter \"$_\" given ",
1066 "to " . ref($self) . "::put()");
1067 }
1068 }
1069 }
1070  
1071 ## If any args given, override corresponding instance data.
1072 local $self->{bin_mode} = $binmode;
1073 local $self->{time_out} = $timeout;
1074  
1075 ## Check for errors.
1076 return $self->error("write error: filehandle isn't open")
1077 unless $self->{opened};
1078  
1079 if ($self->{outputlog}) {
1080 &_log_print($self->{outputlog}, $buf);
1081 }
1082  
1083 ## Convert native newlines to CR LF.
1084 # if (!$self->{bin_mode}) {
1085 # $buf =~ s(\n)(\015\012)g;
1086 # }
1087  
1088 &_put($self, \$buf, "put");
1089 }
1090  
1091 sub rs { &input_record_separator }
1092  
1093 sub send_wakeup {
1094 my ($self, $arg) = @_;
1095 $self->{send_wakeup} = $arg if defined $arg;
1096 return $self->{send_wakeup}
1097 }
1098  
1099 sub sock {
1100 my $self = shift;
1101 exists $self->{_SSH_} ? $self->{_SSH_}->sock : undef
1102 }
1103  
1104 sub ssh2 {
1105 my $self = shift;
1106 exists $self->{_SSH_} ? $self->{_SSH_} : undef
1107 }
1108  
1109 sub ssh2_chan {
1110 my $self = shift;
1111 exists $self->{_SSH_CHAN_} ? $self->{_SSH_CHAN_} : undef
1112 }
1113  
1114 sub timed_out {
1115 my $self = shift;
1116 exists $self->{timedout} ? $self->{timedout} : undef
1117 }
1118  
1119 sub timeout {
1120 my ($self, $arg) = @_;
1121  
1122 if (defined $arg) {
1123 if (defined (my $r = _parse_timeout($self, $arg))) {
1124 $self->{time_out} = $r
1125 }
1126 }
1127 return $self->{time_out}
1128 }
1129  
1130 sub waitfor {
1131 my ($self, @args) = @_;
1132  
1133 my $ap = $self->{autopage};
1134 my $awfp = $self->{always_waitfor_prompt};
1135 my $binmode = $self->{bin_mode};
1136 my $chan = $self->{_SSH_CHAN_};
1137 my $clear = $self->{waitfor_clear};
1138 my $cmd = $self->{last_cmd};
1139 my $normal = $self->{normalize_cmd};
1140 my $rm = $self->{cmd_rm_mode};
1141 my $timeout = $self->{time_out};
1142  
1143 if (!defined $chan) {
1144 &_croak($self, "no login " .
1145 "for " . ref($self) . "::waitfor()");
1146 }
1147  
1148 local $@;
1149 local $_;
1150 my $DONE = 0;
1151 my $MORE = _prep_regex($self->{more_prompt});
1152 my $PROMPT = _prep_regex($self->{cmd_prompt});
1153 my ($match, $buffer, $errmode);
1154 my @matches;
1155 if ($awfp) {
1156 push @matches, $PROMPT
1157 }
1158  
1159 $self->{timedout} = '';
1160 return if $self->{eofile};
1161 return unless @args;
1162  
1163 if (@_ == 2) {
1164 push @matches, _prep_regex($_[1])
1165 } else {
1166 my $arg;
1167 while (($_, $arg) = splice @args, 0, 2 ) {
1168 if (/^-?binmode$/i) {
1169 $binmode = $arg
1170 } elsif (/^-?errmode$/i) {
1171 $errmode = &_parse_errmode($self, $arg);
1172 } elsif (/^-?match$/i) {
1173 push @matches, _prep_regex($arg)
1174 } elsif (/^-?normalize_cmd$/i) {
1175 $normal = $arg
1176 } elsif (/^-?string$/i) {
1177 $arg =~ s/'/\\'/g; # quote ticks
1178 push @matches, $arg
1179 } elsif (/^-?timeout$/i) {
1180 $timeout = _parse_timeout($self, $arg)
1181 } elsif (/^-?waitfor_clear$/i) {
1182 $clear = $arg
1183 } else {
1184 # pass through
1185 #$params{$_} = $args{$_}
1186 &_croak($self, "bad named parameter \"$_\" given " .
1187 "to " . ref($self) . "::waitfor()");
1188 }
1189 }
1190 }
1191  
1192 local $self->{errormode} = $errmode if defined $errmode;
1193 local $self->{waitfor_clear} = $clear;
1194  
1195 eval {
1196 local $SIG{ALRM} = sub { die "timed-out\n" };
1197 alarm $timeout;
1198  
1199 if ($self->{waitfor_clear}) {
1200 $chan->flush;
1201 }
1202  
1203 # Read until $DONE
1204 while (1) {
1205 last if $DONE;
1206 last if $self->eof;
1207 # Read chunk
1208 while (defined (
1209 my $len = $chan->read($self->{buf},$self->{maxbufsize}))) {
1210  
1211 ## Display network traffic if requested.
1212 if ($self->{dumplog} and ($self->{buf} ne '')) {
1213 &_log_dump('<', $self->{dumplog}, \$self->{buf}, 0, $len);
1214 }
1215  
1216 # behave like Net::Telnet(::Cisco) CRLF
1217 _interpret_cr($self, 0);
1218  
1219 # input logging
1220 if ($self->{inputlog}) {
1221 &_log_print($self->{inputlog}, $self->{buf});
1222 }
1223  
1224 # Found match then $DONE
1225 for my $m (@matches) {
1226 if ($self->{buf} =~ /($m)/) {
1227 $match = $1;
1228 $self->{buf} =~ s/$m//;
1229 $DONE++
1230 }
1231 }
1232  
1233 # autopage
1234 if ($ap and ($self->{buf} =~ /($MORE)/)) {
1235 $self->put(" ");
1236 }
1237  
1238 $buffer .= $self->{buf}
1239 }
1240 }
1241  
1242 if ($ap and $normal and defined $buffer) {
1243 $buffer = _normalize($buffer);
1244 }
1245 };
1246 alarm 0;
1247 if ($@ =~ /^timed-out$/) {
1248 $self->errmsg("timed-out during read");
1249 $self->{timedout} = 1;
1250 # If previous call to waitfor timed out, there may still be
1251 # stuff in the channel - e.g., "show run" takes time to "build
1252 # configuration" and that may time out, but the output will fill
1253 # the channel after the return and if term length is a finite
1254 # value - like the default 24 - a MORE prompt is waiting. So
1255 # we need to send a character to cancel that; otherwise, the first
1256 # character of the subsequent $chan->write() (usually from cmd())
1257 # will "disappear" from the output - satisfying the MORE prompt
1258 # and being lost forever.
1259 # The following is 'Control-Shift-Z', which breaks a MORE and
1260 # returns the prompt.
1261 #$chan->write("\cZ")
1262 if ($self->{waitfor_clear}) {
1263 $self->ios_break("Z")
1264 }
1265 }
1266  
1267 if ($self->{waitfor_clear}) {
1268 $chan->flush;
1269 }
1270  
1271 if (defined $match and ($match =~ /$PROMPT/)) {
1272 $self->{last_prompt} = $match
1273 }
1274  
1275 wantarray ? ($buffer, $match) : 1;
1276 }
1277  
1278 sub waitfor_clear {
1279 my ($self, $arg) = @_;
1280 $self->{waitfor_clear} = $arg if defined $arg;
1281 return $self->{waitfor_clear}
1282 }
1283  
1284 sub waitfor_pause {
1285 my ($self, $arg) = @_;
1286  
1287 if (defined $arg) {
1288 if (defined (my $r = _parse_waitfor_pause($self, $arg))) {
1289 $self->{waitfor_pause} = $r
1290 }
1291 }
1292 return $self->{waitfor_pause}
1293 }
1294  
1295 sub warnings {
1296 my ($self, $arg) = @_;
1297 $self->{warnings} = $arg if defined $arg;
1298 return $self->{warnings}
1299 }
1300  
1301 #### PRIVATE ####
1302  
1303 sub _append_lineno {
1304 my ($obj, @msgs) = @_;
1305  
1306 my ( $file, $line, $pkg);
1307  
1308 ## Find the caller that's not in object's class or one of its base classes.
1309 ($pkg, $file , $line) = &_user_caller($obj);
1310 join("", @msgs, " at ", $file, " line ", $line, "\n");
1311 }
1312  
1313 sub _carp {
1314 my ($self) = @_;
1315  
1316 $self->{errormsg} = &_append_lineno(@_);
1317 warn $self->{errormsg}, "\n";
1318 }
1319  
1320 sub _croak {
1321 my ($self) = @_;
1322  
1323 $self->{errormsg} = &_append_lineno(@_);
1324 die $self->{errormsg}, "\n";
1325 }
1326  
1327 sub _extract_arg_errmode {
1328 my ($self, $args) = @_;
1329 my (%args);
1330 local $_;
1331 my $errmode = '';
1332  
1333 ## Check for named parameters.
1334 return '' unless @$args >= 2;
1335  
1336 ## Rebuild args without errmode parameter.
1337 %args = @$args;
1338 @$args = ();
1339  
1340 ## Extract errmode arg.
1341 foreach (keys %args) {
1342 if (/^-?errmode$/i) {
1343 $errmode = &_parse_errmode($self, $args{$_});
1344 } else {
1345 push @$args, $_, $args{$_};
1346 }
1347 }
1348 $errmode;
1349 }
1350  
1351 sub _fname_to_handle {
1352 my ($self, $filename) = @_;
1353  
1354 no strict "refs";
1355  
1356 my $fh = &_new_handle();
1357 CORE::open $fh, ">", $filename
1358 or return $self->error("problem creating $filename: $!");
1359  
1360 $fh;
1361 }
1362  
1363 sub _interpret_cr {
1364 my ($s, $pos) = @_;
1365 my (
1366 $nextchar,
1367 );
1368  
1369 while (($pos = index($s->{buf}, "\015", $pos)) > -1) {
1370 $nextchar = substr($s->{buf}, $pos + 1, 1);
1371 if ($nextchar eq "\0") {
1372 ## Convert CR NULL to CR when in telnet mode.
1373 if ($s->{telnet_mode}) {
1374 substr($s->{buf}, $pos + 1, 1) = "";
1375 }
1376 }
1377 elsif ($nextchar eq "\012") {
1378 ## Convert CR LF to newline when not in binary mode.
1379 if (!$s->{bin_mode}) {
1380 substr($s->{buf}, $pos, 2) = "\n";
1381 }
1382 }
1383 elsif (!length($nextchar) and ($s->{telnet_mode} or !$s->{bin_mode})) {
1384 ## Save CR in alt buffer for possible CR LF or CR NULL conversion.
1385 $s->{pushback_buf} .= "\015";
1386 chop $s->{buf};
1387 }
1388  
1389 $pos++;
1390 }
1391  
1392 1;
1393 } # end sub _interpret_cr
1394  
1395 sub _is_open_fh {
1396 my ($fh) = @_;
1397 my $is_open = '';
1398 local $@;
1399  
1400 eval {
1401 local $SIG{"__DIE__"} = "DEFAULT";
1402 $is_open = defined(fileno $fh);
1403 };
1404  
1405 $is_open;
1406 }
1407  
1408 sub _log_dump {
1409 my ($direction, $fh, $data, $offset, $len) = @_;
1410  
1411 my $addr = 0;
1412 $len = length($$data) - $offset
1413 if !defined $len;
1414 return 1 if $len <= 0;
1415  
1416 my ($hexvals, $line);
1417 ## Print data in dump format.
1418 while ($len > 0) {
1419 ## Convert up to the next 16 chars to hex, padding w/ spaces.
1420 if ($len >= 16) {
1421 $line = substr $$data, $offset, 16;
1422 } else {
1423 $line = substr $$data, $offset, 16;
1424 }
1425 $hexvals = unpack("H*", $line);
1426 $hexvals .= ' ' x (32 - length $hexvals);
1427  
1428 ## Place in 16 columns, each containing two hex digits.
1429 $hexvals = sprintf("%s %s %s %s " x 4, unpack("a2" x 16, $hexvals));
1430  
1431 ## For the ASCII column, change unprintable chars to a period.
1432 $line =~ s/[\000-\037,\177-\237]/./g;
1433  
1434 ## Print the line in dump format.
1435 &_log_print($fh, sprintf("%s 0x%5.5lx: %s%s\n",
1436 $direction, $addr, $hexvals, $line));
1437  
1438 $addr += 16;
1439 $offset += 16;
1440 $len -= 16;
1441 }
1442  
1443 &_log_print($fh, "\n");
1444  
1445 1;
1446 }
1447  
1448 sub _log_print {
1449 my ($fh, $buf) = @_;
1450 local $\ = '';
1451  
1452 if (ref($fh) eq "GLOB") { # fh is GLOB ref
1453 print $fh $buf;
1454 } else { # fh isn't GLOB ref
1455 $fh->print($buf);
1456 }
1457 }
1458  
1459 sub _match_check {
1460 my ($self, $code) = @_;
1461 my $error;
1462 my @warns = ();
1463 local $@;
1464  
1465 ## Use eval to check for syntax errors or warnings.
1466 {
1467 local $SIG{"__DIE__"} = "DEFAULT";
1468 local $SIG{"__WARN__"} = sub { push @warns, @_ };
1469 local $^W = 1;
1470 local $_ = '';
1471 eval "\$_ =~ $code;";
1472 }
1473 if ($@) {
1474 ## Remove useless lines numbers from message.
1475 ($error = $@) =~ s/ at \(eval \d+\) line \d+.?//;
1476 chomp $error;
1477 return $self->error("bad match operator: $error");
1478 } elsif (@warns) {
1479 ## Remove useless lines numbers from message.
1480 ($error = shift @warns) =~ s/ at \(eval \d+\) line \d+.?//;
1481 $error =~ s/ while "strict subs" in use//;
1482 chomp $error;
1483 return $self->error("bad match operator: $error");
1484 }
1485  
1486 1;
1487 }
1488  
1489 sub _new_handle {
1490 if ($INC{"IO/Handle.pm"}) {
1491 return IO::Handle->new;
1492 } else {
1493 require FileHandle;
1494 return FileHandle->new;
1495 }
1496 }
1497  
1498 sub _normalize {
1499 $_ = join "", @_;
1500  
1501 1 while s/[^\cH\c?][\cH\c?]//mg; # ^H ^?
1502 s/^.*\cU//mg; # ^U
1503  
1504 return wantarray ? split /^/, $_ : $_; # ORS instead?
1505 }
1506  
1507 sub _parse_cmd_remove_mode {
1508 my ($self, $arg) = @_;
1509  
1510 my $crm;
1511 if ($arg =~ /^\d+$/) {
1512 $crm = $arg
1513 } elsif ($arg =~ /^\s*auto\s*$/i) {
1514 $crm = "auto"
1515 } else {
1516 &_carp($self, "ignoring bad Cmd_remove_mode " .
1517 "argument \"$arg\": it's not \"auto\" or a " .
1518 "non-negative integer");
1519 $crm = $self->{cmd_rm_mode}
1520 }
1521 $crm
1522 }
1523  
1524 sub _parse_errmode {
1525 my ($self, $errmode) = @_;
1526  
1527 ## Set the error mode.
1528 if (!defined $errmode) {
1529 &_carp($self, "ignoring undefined Errmode argument");
1530 $errmode = $self->{errormode};
1531 } elsif ($errmode =~ /^\s*return\s*$/i) {
1532 $errmode = "return";
1533 } elsif ($errmode =~ /^\s*die\s*$/i) {
1534 $errmode = "die";
1535 } elsif (ref($errmode) eq "CODE") {
1536 } elsif (ref($errmode) eq "ARRAY") {
1537 unless (ref($errmode->[0]) eq "CODE") {
1538 &_carp($self, "ignoring bad Errmode argument: " .
1539 "first list item isn't a code ref");
1540 $errmode = $self->{errormode};
1541 }
1542 } else {
1543 &_carp($self, "ignoring bad Errmode argument \"$errmode\"");
1544 $errmode = $self->{errormode};
1545 }
1546 $errmode;
1547 }
1548  
1549 sub _parse_family {
1550 my ($self, $arg) = @_;
1551  
1552 my $family;
1553 if ($arg =~ /^(?:(?:(:?ip)?v?(?:4|6))|${\AF_INET}|$AF_INET6)$/) {
1554 if ($arg =~ /^(?:(?:(:?ip)?v?4)|${\AF_INET})$/) {
1555 $family = 'ipv4' # AF_INET
1556 } else {
1557 if (!$HAVE_IO_Socket_IP) {
1558 return $self->error("IO::Socket::IP required for IPv6")
1559 }
1560 $family = 'ipv6' # $AF_INET6
1561 }
1562 } else {
1563 return $self->error("bad Family argument \"$arg\": " .
1564 "must be \"ipv4\" or \"ipv6\"");
1565 }
1566 $family
1567 }
1568  
1569 sub _parse_family_to_num {
1570 my ($self, $arg) = @_;
1571 if ($arg eq 'ipv4') {
1572 return AF_INET
1573 } elsif ($arg eq 'ipv6') {
1574 return $AF_INET6
1575 } else {
1576 return $self->error("invalid address family - `$arg'");
1577 }
1578 }
1579  
1580 sub _parse_port {
1581 my ($self, $arg) = @_;
1582  
1583 my $port;
1584 if ($arg =~ /^\d{1,5}$/) {
1585 if (($arg > 0) and ($arg < 65536)) {
1586 $port = $arg
1587 } else {
1588 return $self->error("not a valid port - `$arg'")
1589 }
1590 } else {
1591 return $self->error("port not a valid number - `$arg'")
1592 }
1593 $port
1594 }
1595  
1596 sub _parse_prompt {
1597 my ($self, $prompt) = @_;
1598  
1599 unless (defined $prompt) {
1600 $prompt = "";
1601 }
1602  
1603 return $self->error("bad Prompt argument \"$prompt\": " .
1604 "missing opening delimiter of match operator")
1605 unless $prompt =~ m(^\s*/) or $prompt =~ m(^\s*m\s*\W);
1606  
1607 $prompt;
1608 }
1609  
1610 sub _parse_timeout {
1611 my ($self, $arg) = @_;
1612  
1613 my $timeout;
1614 if ($arg =~ /^\d+$/) {
1615 $timeout = $arg
1616 } else {
1617 return $self->error("not a valid timeout - `$arg'")
1618 }
1619 $timeout
1620 }
1621  
1622 sub _parse_waitfor_pause {
1623 my ($self, $arg) = @_;
1624  
1625 my $wfp;
1626 if ($arg =~ /^[0-9]*\.?[0-9]+$/) {
1627 $wfp = $arg
1628 } else {
1629 return $self->error("not a valid waitfor_pause - `$arg'")
1630 }
1631 $wfp
1632 }
1633  
1634 sub _put {
1635 my ($self, $buf, $subname) = @_;
1636  
1637 return $self->error("write error: filehandle isn't open")
1638 unless $self->{opened};
1639  
1640 if (exists $self->{_SSH_CHAN_}) {
1641 my $nwrote = $self->{_SSH_CHAN_}->write($$buf);
1642  
1643 ## Display network traffic if requested.
1644 if ($self->{dumplog}) {
1645 &_log_dump('>', $self->{dumplog}, $buf, 0, $nwrote);
1646 }
1647 } else {
1648 return $self->error("Net::SSH2::Channel not created")
1649 }
1650 1
1651 }
1652  
1653 sub _prep_regex {
1654 my ($regex) = @_;
1655 # strip leading / if found
1656 $regex =~ s/^\///;
1657 # strip trailing / if found
1658 $regex =~ s/\/$//;
1659  
1660 return $regex
1661 }
1662  
1663 ##################################################
1664 # DNS hostname resolution
1665 # return:
1666 # $host->{name} = host - as passed in
1667 # $host->{host} = host - as passed in without :port
1668 # $host->{port} = OPTIONAL - if :port, then value of port
1669 # $host->{addr} = resolved numeric address
1670 # $host->{family} = AF_INET/6
1671 ############################
1672 sub _resolv {
1673 my ($self, $name, $family) = @_;
1674  
1675 my %h;
1676 $h{name} = $name;
1677  
1678 # Default to IPv4 for backward compatiblity
1679 # THIS MAY CHANGE IN THE FUTURE!!!
1680 if (!defined $family) {
1681 $family = AF_INET
1682 }
1683  
1684 # START - host:port
1685 my $cnt = 0;
1686  
1687 # Count ":"
1688 $cnt++ while ($name =~ m/:/g);
1689  
1690 # 0 = hostname or IPv4 address
1691 if ($cnt == 0) {
1692 $h{host} = $name
1693 # 1 = IPv4 address with port
1694 } elsif ($cnt == 1) {
1695 ($h{host}, $h{port}) = split /:/, $name
1696 # >=2 = IPv6 address
1697 } elsif ($cnt >= 2) {
1698 #IPv6 with port - [2001::1]:port
1699 if ($name =~ /^\[.*\]:\d{1,5}$/) {
1700 ($h{host}, $h{port}) = split /:([^:]+)$/, $name # split after last :
1701 # IPv6 without port
1702 } else {
1703 $h{host} = $name
1704 }
1705 }
1706  
1707 # Clean up host
1708 $h{host} =~ s/\[//g;
1709 $h{host} =~ s/\]//g;
1710 # Clean up port
1711 if (defined $h{port} && (($h{port} !~ /^\d{1,5}$/) || ($h{port} < 1) || ($h{port} > 65535))) {
1712 $self->errmsg("Invalid port `$h{port}' in `$name'");
1713 return undef
1714 }
1715 # END - host:port
1716  
1717 # address check
1718 # new way
1719 if (version->parse($Socket::VERSION) >= version->parse(1.94)) {
1720 my %hints = (
1721 family => $AF_UNSPEC,
1722 protocol => IPPROTO_TCP,
1723 flags => $AI_NUMERICHOST
1724 );
1725  
1726 # numeric address, return
1727 my ($err, @getaddr) = Socket::getaddrinfo($h{host}, undef, \%hints);
1728 if (defined $getaddr[0]) {
1729 $h{addr} = $h{host};
1730 $h{family} = $getaddr[0]->{family};
1731 return \%h
1732 }
1733 # old way
1734 } else {
1735 # numeric address, return
1736 my $ret = gethostbyname($h{host});
1737 if (defined $ret && (inet_ntoa($ret) eq $h{host})) {
1738 $h{addr} = $h{host};
1739 $h{family} = AF_INET;
1740 return \%h
1741 }
1742 }
1743  
1744 # resolve
1745 # new way
1746 if (version->parse($Socket::VERSION) >= version->parse(1.94)) {
1747 my %hints = (
1748 family => $family,
1749 protocol => IPPROTO_TCP
1750 );
1751  
1752 my ($err, @getaddr) = Socket::getaddrinfo($h{host}, undef, \%hints);
1753 if (defined $getaddr[0]) {
1754 my ($err, $address) = Socket::getnameinfo($getaddr[0]->{addr}, $NI_NUMERICHOST);
1755 if (defined $address) {
1756 $h{addr} = $address;
1757 $h{addr} =~ s/\%(.)*$//; # remove %ifID if IPv6
1758 $h{family} = $getaddr[0]->{family};
1759 return \%h
1760 } else {
1761 $self->errmsg("getnameinfo($getaddr[0]->{addr}) failed - $err");
1762 return undef
1763 }
1764 } else {
1765 my $LASTERROR = sprintf "getaddrinfo($h{host},,%s) failed - $err", ($family == AF_INET) ? "AF_INET" : "AF_INET6";
1766 $self->errmsg($LASTERROR);
1767 return undef
1768 }
1769 # old way
1770 } else {
1771 if ($family == $AF_INET6) {
1772 $self->errmsg("Socket >= 1.94 required for IPv6 - found Socket $Socket::VERSION");
1773 return undef
1774 }
1775  
1776 my @gethost = gethostbyname($h{host});
1777 if (defined $gethost[4]) {
1778 $h{addr} = inet_ntoa($gethost[4]);
1779 $h{family} = AF_INET;
1780 return \%h
1781 } else {
1782 $self->errmsg("gethostbyname($h{host}) failed - $^E");
1783 return undef
1784 }
1785 }
1786 }
1787  
1788 sub _user_caller {
1789 my ($obj) = @_;
1790  
1791 my ($class, $curr_pkg, $file, $i, $line, $pkg, %isa, @isa);
1792 local $@;
1793 local $_;
1794  
1795 ## Create a boolean hash to test for isa. Make sure current
1796 ## package and the object's class are members.
1797 $class = ref $obj;
1798 @isa = eval "\@${class}::ISA";
1799 push @isa, $class;
1800 ($curr_pkg) = caller 1;
1801 push @isa, $curr_pkg;
1802 %isa = map { $_ => 1 } @isa;
1803  
1804 ## Search back in call frames for a package that's not in isa.
1805 $i = 1;
1806 while (($pkg, $file, $line) = caller ++$i) {
1807 next if $isa{$pkg};
1808  
1809 return ($pkg, $file, $line);
1810 }
1811  
1812 ## If not found, choose outer most call frame.
1813 ($pkg, $file, $line) = caller --$i;
1814 return ($pkg, $file, $line);
1815 }
1816  
1817 1;
1818  
1819 __END__
↑ Summary