blib/lib/Games/Axmud/Obj/Telnet.pm untested

filter: Statementstmt 0.0% 0 / 1643 Branchbran 0.0% 0 / 896 Conditioncond 0.0% 0 / 291 MC/DCmcdc 0.0% 0 / 173 Subroutinesub 0.0% 0 / 194 Podpod 0.0% 0 / 182 totaltotal 0.0% 0 / 3379 CC 448 SCAR 58.1
CC
448
Cov
0%
new
1406.0
_fillbuf
1406.0
open
1122.0
CRAP 332.6
1 # Copyright (C) 2011-2024 A S Lewis
2 #
3 # This program is free software: you can redistribute it and/or modify it under the terms of the GNU
4 # Lesser Public License as published by the Free Software Foundation, either version 3 of the
5 # License, or (at your option) any later version.
6 #
7 # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
8 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9 # Lesser Public License for more details.
10 #
11 # You should have received a copy of the GNU Lesser Public License along with this program. If not,
12 # see <http://www.gnu.org/licenses/>.
13 #
14 # Games::Axmud::Obj::Telnet, a modification of Net::Telnet (v3.04) by Jay Rogers
15 #
16 # List of changes (besides cosmetic ones):
17 # - Removed user documentation
18 # - 'use warnings' and 'use diagnostics' added
19 # - Fixed apparent problem in ->_optimal_blksize, which caused a warning
20 # - Fixed apparent problem in ->_negotiate_recv_disable and ->_negotiate_recv_enable, which causes
21 # errors when the $$state argument was 'undef'
22 # - Removed 'require 5.002', since Axmud requires 5.008 anyway
23 # - Removed 'require FileHandle' for the same reason
24 # - Implemented MCCP (Mud Client Compression Protocol, http://tintin.sourceforge.io/mccp/)
25 # - Added 'use Compress::Zlib'
26 # - Added new IVs to ->new() : ->axmud_mccp_mode, ->axmud_zlib_obj and ->axmud_session
27 # - Modified _>_fillbuf to decompress text when MCCP enabled
28 # - Added new function ->_disable_mccp, called by ->_fillbuf
29 # - Added new function ->axmud_session, called by ->new
30 # - In ->new, commented out automatic handling of TELOPT_ECHO and TELOPT_SGA, which are now
31 # handled by Axmud itself
32 # - Added some new constants to @EXPORT_OK and %Axmud_Telopts describing various MUD protocols,
33 # and modified ->_log_option to use them
34 # - Modified ->localfamily, ->_parse_family and ->_parse_localfamily to cope with the error seen
35 # on Debian/Ubuntu:
36 # 'WARNING: Argument "2.020_03" isn't numeric in numeric ge (>=)'
37 # - Commented out $VERSION as it causes Kwalitee errors
38 # - Modified ->open to enable TCP keepalive packets on all connections
39 # - Modified ->_interpret_tcmd so it doesn't gobble up IAC GA
40  
41 { package Games::Axmud::Obj::Telnet;
42  
43 use strict;
44 use warnings;
45 # use diagnostics;
46  
47 ## Module export.
48 use vars qw(@EXPORT_OK);
49 @EXPORT_OK = qw(
50 TELNET_IAC TELNET_DONT TELNET_DO TELNET_WONT TELNET_WILL
51 TELNET_SB TELNET_GA TELNET_EL TELNET_EC TELNET_AYT TELNET_AO
52 TELNET_IP TELNET_BREAK TELNET_DM TELNET_NOP TELNET_SE
53 TELNET_EOR TELNET_ABORT TELNET_SUSP TELNET_EOF TELNET_SYNCH
54 TELOPT_BINARY TELOPT_ECHO TELOPT_RCP TELOPT_SGA TELOPT_NAMS
55 TELOPT_STATUS TELOPT_TM TELOPT_RCTE TELOPT_NAOL TELOPT_NAOP
56 TELOPT_NAOCRD TELOPT_NAOHTS TELOPT_NAOHTD TELOPT_NAOFFD
57 TELOPT_NAOVTS TELOPT_NAOVTD TELOPT_NAOLFD TELOPT_XASCII
58 TELOPT_LOGOUT TELOPT_BM TELOPT_DET TELOPT_SUPDUP
59 TELOPT_SUPDUPOUTPUT TELOPT_SNDLOC TELOPT_TTYPE TELOPT_EOR
60 TELOPT_TUID TELOPT_OUTMRK TELOPT_TTYLOC TELOPT_3270REGIME
61 TELOPT_X3PAD TELOPT_NAWS TELOPT_TSPEED TELOPT_LFLOW
62 TELOPT_LINEMODE TELOPT_XDISPLOC TELOPT_OLD_ENVIRON
63 TELOPT_AUTHENTICATION TELOPT_ENCRYPT TELOPT_NEW_ENVIRON
64 TELOPT_TN3270E TELOPT_CHARSET TELOPT_COMPORT TELOPT_KERMIT
65 TELOPT_EXOPL
66  
67 TELOPT_MSDP TELOPT_MSSP TELOPT_MCCP1 TELOPT_MCCP2 TELOPT_MSP
68 TELOPT_MXP TELOPT_ZMP TELOPT_AARD102 TELOPT_ATCP TELOPT_GMCP
69 );
70  
71 ## Module import.
72 use Exporter ();
73 use Compress::Zlib;
74 # use Socket qw(AF_INET SOCK_STREAM inet_aton sockaddr_in);
75 use Socket qw(AF_INET SOCK_STREAM SOL_SOCKET SO_KEEPALIVE inet_aton sockaddr_in);
76 use Symbol qw(qualify);
77  
78 ## Base classes.
79 use vars qw(@ISA);
80 @ISA = qw(Exporter);
81 if (&_io_socket_include) { # successfully required module IO::Socket
82 push @ISA, "IO::Socket::INET";
83 }
84 my $AF_INET6 = &_import_af_inet6();
85 my $AF_UNSPEC = &_import_af_unspec() || 0;
86 my $AI_ADDRCONFIG = &_import_ai_addrconfig() || 0;
87 my $EAI_BADFLAGS = &_import_eai_badflags() || -1;
88 my $EINTR = &_import_eintr();
89  
90 ## Global variables.
91 # use vars qw($VERSION @Telopts %Axmud_Telopts);
92 # $VERSION = "3.04";
93 use vars qw(@Telopts %Axmud_Telopts);
94 @Telopts = ("BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", "NAMS", "STATUS",
95 "TIMING MARK", "RCTE", "NAOL", "NAOP", "NAOCRD", "NAOHTS",
96 "NAOHTD", "NAOFFD", "NAOVTS", "NAOVTD", "NAOLFD", "EXTEND ASCII",
97 "LOGOUT", "BYTE MACRO", "DATA ENTRY TERMINAL", "SUPDUP",
98 "SUPDUP OUTPUT", "SEND LOCATION", "TERMINAL TYPE", "END OF RECORD",
99 "TACACS UID", "OUTPUT MARKING", "TTYLOC", "3270 REGIME", "X.3 PAD",
100 "NAWS", "TSPEED", "LFLOW", "LINEMODE", "XDISPLOC", "OLD-ENVIRON",
101 "AUTHENTICATION", "ENCRYPT", "NEW-ENVIRON", "TN3270E", "XAUTH",
102 "CHARSET", "RSP", "COMPORT", "SUPPRESS LOCAL ECHO", "START TLS",
103 "KERMIT");
104  
105 %Axmud_Telopts = (
106 69 => 'MSDP',
107 70 => 'MSSP',
108 85 => 'MCCP1',
109 86 => 'MCCP2',
110 90 => 'MSP',
111 91 => 'MXP',
112 93 => 'ZMP',
113 102 => 'AARD192',
114 200 => 'ATCP',
115 201 => 'GMCP',
116 );
117  
118 ########################### Public Methods ###########################
119  
120  
121 sub new {
122 my ($class) = @_;
123 my (
124 $dump_log,
125 $errmode,
126 $family,
127 $fh_open,
128 $host,
129 $input_log,
130 $localfamily,
131 $option_log,
132 $output_log,
133 $port,
134 $prompt,
135 $axmud_session,
136 $self,
137 %args,
138 );
139 local $_;
140  
141 ## Create a new object with defaults.
142 $self = $class->SUPER::new;
143 *$self->{net_telnet} = {
144 bin_mode => 0,
145 blksize => &_optimal_blksize(),
146 buf => "",
147 cmd_prompt => '/[\$%#>] $/',
148 cmd_rm_mode => "auto",
149 dumplog => '',
150 eofile => 1,
151 errormode => "die",
152 errormsg => "",
153 fdmask => '',
154 host => "localhost",
155 inputlog => '',
156 last_line => "",
157 last_prompt => "",
158 local_family => "ipv4",
159 local_host => "",
160 maxbufsize => 1_048_576,
161 num_wrote => 0,
162 ofs => "",
163 opened => '',
164 opt_cback => '',
165 opt_log => '',
166 opts => {},
167 ors => "\n",
168 outputlog => '',
169 peer_family => "ipv4",
170 pending_errormsg => "",
171 port => 23,
172 pushback_buf => "",
173 rs => "\n",
174 select_supported => 1,
175 sock_family => 0,
176 subopt_cback => '',
177 telnet_mode => 1,
178 time_out => 10,
179 timedout => '',
180 unsent_opts => "",
181 # New variables for Axmud
182 axmud_session => '',
183 axmud_mccp_mode => 0,
184 axmud_zlib_obj => '',
185 # End of new variables
186 };
187  
188 # TELOPT_ECHO and TELOPT_SGA are now handled directly by Axmud
189 # ## Indicate that we'll accept an offer from remote side for it to echo
190 # ## and suppress go aheads.
191 # &_opt_accept($self,
192 # { option => &TELOPT_ECHO,
193 # is_remote => 1,
194 # is_enable => 1 },
195 # { option => &TELOPT_SGA,
196 # is_remote => 1,
197 # is_enable => 1 },
198 # );
199  
200 ## Parse the args.
201 if (@_ == 2) { # one positional arg given
202 $host = $_[1];
203 }
204 elsif (@_ > 2) { # named args given
205 ## Get the named args.
206 (undef, %args) = @_;
207  
208 ## Parse all other named args.
209 foreach (keys %args) {
210 if (/^-?binmode$/i) {
211 $self->binmode($args{$_});
212 }
213 elsif (/^-?cmd_remove_mode$/i) {
214 $self->cmd_remove_mode($args{$_});
215 }
216 elsif (/^-?dump_log$/i) {
217 $dump_log = $args{$_};
218 }
219 elsif (/^-?errmode$/i) {
220 $errmode = $args{$_};
221 }
222 elsif (/^-?family$/i) {
223 $family = $args{$_};
224 }
225 elsif (/^-?fhopen$/i) {
226 $fh_open = $args{$_};
227 }
228 elsif (/^-?host$/i) {
229 $host = $args{$_};
230 }
231 elsif (/^-?input_log$/i) {
232 $input_log = $args{$_};
233 }
234 elsif (/^-?input_record_separator$/i or /^-?rs$/i) {
235 $self->input_record_separator($args{$_});
236 }
237 elsif (/^-?localfamily$/i) {
238 $localfamily = $args{$_};
239 }
240 elsif (/^-?localhost$/i) {
241 $self->localhost($args{$_});
242 }
243 elsif (/^-?max_buffer_length$/i) {
244 $self->max_buffer_length($args{$_});
245 }
246 elsif (/^-?option_log$/i) {
247 $option_log = $args{$_};
248 }
249 elsif (/^-?output_field_separator$/i or /^-?ofs$/i) {
250 $self->output_field_separator($args{$_});
251 }
252 elsif (/^-?output_log$/i) {
253 $output_log = $args{$_};
254 }
255 elsif (/^-?output_record_separator$/i or /^-?ors$/i) {
256 $self->output_record_separator($args{$_});
257 }
258 elsif (/^-?port$/i) {
259 $port = $args{$_};
260 }
261 elsif (/^-?prompt$/i) {
262 $prompt = $args{$_};
263 }
264 elsif (/^-?telnetmode$/i) {
265 $self->telnetmode($args{$_});
266 }
267 elsif (/^-?timeout$/i) {
268 $self->timeout($args{$_});
269 }
270 # New args for Axmud
271 elsif (/^-?axmud_session$/i) {
272 $axmud_session = $args{$_};
273 }
274 # End of new args
275 else {
276 &_croak($self, "bad named parameter \"$_\" given " .
277 "to " . ref($self) . "::new()");
278 }
279 }
280 }
281  
282 if (defined $errmode) { # user wants to set errmode
283 $self->errmode($errmode);
284 }
285  
286 if (defined $host) { # user wants to set host
287 $self->host($host);
288 }
289  
290 if (defined $port) { # user wants to set port
291 $self->port($port)
292 or return;
293 }
294  
295 if (defined $family) { # user wants to set family
296 $self->family($family)
297 or return;
298 }
299  
300 if (defined $localfamily) { # user wants to set localfamily
301 $self->localfamily($localfamily)
302 or return;
303 }
304  
305 if (defined $prompt) { # user wants to set prompt
306 $self->prompt($prompt)
307 or return;
308 }
309  
310 if (defined $dump_log) { # user wants to set dump_log
311 $self->dump_log($dump_log)
312 or return;
313 }
314  
315 if (defined $input_log) { # user wants to set input_log
316 $self->input_log($input_log)
317 or return;
318 }
319  
320 if (defined $option_log) { # user wants to set option_log
321 $self->option_log($option_log)
322 or return;
323 }
324  
325 if (defined $output_log) { # user wants to set output_log
326 $self->output_log($output_log)
327 or return;
328 }
329  
330 if (defined $fh_open) { # user wants us to attach to existing filehandle
331 $self->fhopen($fh_open)
332 or return;
333 }
334 elsif (defined $host) { # user wants us to open a connection to host
335 $self->open
336 or return;
337 }
338  
339 # New args for Axmud
340 if (defined $axmud_session) { # user wants to set axmud_session
341 $self->axmud_session($axmud_session)
342 or return;
343 }
344 # End of new args
345  
346 $self;
347 } # end sub new
348  
349  
350 sub DESTROY {
351 } # end sub DESTROY
352  
353  
354 sub axmud_session {
355 my ($self, $session) = @_;
356 my (
357 $prev,
358 $s,
359 );
360  
361 $s = *$self->{net_telnet};
362 $prev = $s->{axmud_session};
363  
364 if (@_ >= 2) {
365 unless (defined $session) {
366 $session = "";
367 }
368  
369 $s->{axmud_session} = $session;
370 }
371  
372 1;
373 } # end sub axmud_session
374  
375  
376 sub binmode {
377 my ($self, $mode) = @_;
378 my (
379 $prev,
380 $s,
381 );
382  
383 $s = *$self->{net_telnet};
384 $prev = $s->{bin_mode};
385  
386 if (@_ >= 2) {
387 unless (defined $mode) {
388 $mode = 0;
389 }
390  
391 $s->{bin_mode} = $mode;
392 }
393  
394 $prev;
395 } # end sub binmode
396  
397  
398 sub break {
399 my ($self) = @_;
400 my $s = *$self->{net_telnet};
401 my $break_cmd = "\xff\xf3";
402  
403 $s->{timedout} = '';
404  
405 &_put($self, \$break_cmd, "break");
406 } # end sub break
407  
408  
409 sub buffer {
410 my ($self) = @_;
411 my $s = *$self->{net_telnet};
412  
413 \$s->{buf};
414 } # end sub buffer
415  
416  
417 sub buffer_empty {
418 my ($self) = @_;
419 my (
420 $buffer,
421 );
422  
423 $buffer = $self->buffer;
424 $$buffer = "";
425 } # end sub buffer_empty
426  
427  
428 sub close {
429 my ($self) = @_;
430 my $s = *$self->{net_telnet};
431  
432 $s->{eofile} = 1;
433 $s->{opened} = '';
434 $s->{sock_family} = 0;
435 close $self
436 if defined fileno($self);
437  
438 1;
439 } # end sub close
440  
441  
442 sub cmd {
443 my ($self, @args) = @_;
444 my (
445 $arg_errmode,
446 $cmd_remove_mode,
447 $firstpos,
448 $last_prompt,
449 $lastpos,
450 $lines,
451 $ors,
452 $output,
453 $output_ref,
454 $prompt,
455 $remove_echo,
456 $rs,
457 $rs_len,
458 $s,
459 $telopt_echo,
460 $timeout,
461 %args,
462 );
463 my $cmd = "";
464 local $_;
465  
466 ## Init.
467 $self->timed_out('');
468 $self->last_prompt("");
469 $s = *$self->{net_telnet};
470 $output = [];
471 $cmd_remove_mode = $self->cmd_remove_mode;
472 $ors = $self->output_record_separator;
473 $prompt = $self->prompt;
474 $rs = $self->input_record_separator;
475 $timeout = $self->timeout;
476  
477 ## Override errmode first, if specified.
478 $arg_errmode = &_extract_arg_errmode($self, \@args);
479 local $s->{errormode} = $arg_errmode
480 if $arg_errmode;
481  
482 ## Parse args.
483 if (@args == 1) { # one positional arg given
484 $cmd = $args[0];
485 }
486 elsif (@args >= 2) { # named args given
487 ## Get the named args.
488 %args = @args;
489  
490 ## Parse the named args.
491 foreach (keys %args) {
492 if (/^-?cmd_remove/i) {
493 $cmd_remove_mode = &_parse_cmd_remove_mode($self, $args{$_});
494 }
495 elsif (/^-?input_record_separator$/i or /^-?rs$/i) {
496 $rs = &_parse_input_record_separator($self, $args{$_});
497 }
498 elsif (/^-?output$/i) {
499 $output_ref = $args{$_};
500 if (defined($output_ref) and ref($output_ref) eq "ARRAY") {
501 $output = $output_ref;
502 }
503 }
504 elsif (/^-?output_record_separator$/i or /^-?ors$/i) {
505 $ors = $args{$_};
506 }
507 elsif (/^-?prompt$/i) {
508 $prompt = &_parse_prompt($self, $args{$_})
509 or return;
510 }
511 elsif (/^-?string$/i) {
512 $cmd = $args{$_};
513 }
514 elsif (/^-?timeout$/i) {
515 $timeout = &_parse_timeout($self, $args{$_});
516 }
517 else {
518 &_croak($self, "bad named parameter \"$_\" given " .
519 "to " . ref($self) . "::cmd()");
520 }
521 }
522 }
523  
524 ## Override some user settings.
525 local $s->{time_out} = &_endtime($timeout);
526 $self->errmsg("");
527  
528 ## Send command and wait for the prompt.
529 {
530 local $s->{errormode} = "return";
531  
532 $self->put($cmd . $ors)
533 and ($lines, $last_prompt) = $self->waitfor($prompt);
534 }
535  
536 ## Check for failure.
537 return $self->error("command timed-out") if $self->timed_out;
538 return $self->error($self->errmsg) if $self->errmsg ne "";
539  
540 ## Save the most recently matched prompt.
541 $self->last_prompt($last_prompt);
542  
543 ## Split lines into an array, keeping record separator at end of line.
544 $firstpos = 0;
545 $rs_len = length $rs;
546 while (($lastpos = index($lines, $rs, $firstpos)) > -1) {
547 push(@$output,
548 substr($lines, $firstpos, $lastpos - $firstpos + $rs_len));
549 $firstpos = $lastpos + $rs_len;
550 }
551  
552 if ($firstpos < length $lines) {
553 push @$output, substr($lines, $firstpos);
554 }
555  
556 ## Determine if we should remove the first line of output based
557 ## on the assumption that it's an echoed back command.
558 if ($cmd_remove_mode eq "auto") {
559 ## See if remote side told us they'd echo.
560 $telopt_echo = $self->option_state(&TELOPT_ECHO);
561 $remove_echo = $telopt_echo->{remote_enabled};
562 }
563 else { # user explicitly told us how many lines to remove.
564 $remove_echo = $cmd_remove_mode;
565 }
566  
567 ## Get rid of possible echo back command.
568 while ($remove_echo--) {
569 shift @$output;
570 }
571  
572 ## Ensure at least a null string when there's no command output - so
573 ## "true" is returned in a list context.
574 unless (@$output) {
575 @$output = ("");
576 }
577  
578 ## Return command output via named arg, if requested.
579 if (defined $output_ref) {
580 if (ref($output_ref) eq "SCALAR") {
581 $$output_ref = join "", @$output;
582 }
583 elsif (ref($output_ref) eq "HASH") {
584 %$output_ref = @$output;
585 }
586 }
587  
588 wantarray ? @$output : 1;
589 } # end sub cmd
590  
591  
592 sub cmd_remove_mode {
593 my ($self, $mode) = @_;
594 my (
595 $prev,
596 $s,
597 );
598  
599 $s = *$self->{net_telnet};
600 $prev = $s->{cmd_rm_mode};
601  
602 if (@_ >= 2) {
603 $s->{cmd_rm_mode} = &_parse_cmd_remove_mode($self, $mode);
604 }
605  
606 $prev;
607 } # end sub cmd_remove_mode
608  
609  
610 sub dump_log {
611 my ($self, $name) = @_;
612 my (
613 $fh,
614 $s,
615 );
616  
617 $s = *$self->{net_telnet};
618 $fh = $s->{dumplog};
619  
620 if (@_ >= 2) {
621 if (!defined($name) or $name eq "") { # input arg is ""
622 ## Turn off logging.
623 $fh = "";
624 }
625 elsif (&_is_open_fh($name)) { # input arg is an open fh
626 ## Use the open fh for logging.
627 $fh = $name;
628 select((select($fh), $|=1)[$[]); # don't buffer writes
629 }
630 elsif (!ref $name) { # input arg is filename
631 ## Open the file for logging.
632 $fh = &_fname_to_handle($self, $name)
633 or return;
634 select((select($fh), $|=1)[$[]); # don't buffer writes
635 }
636 else {
637 return $self->error("bad Dump_log argument ",
638 "\"$name\": not filename or open fh");
639 }
640  
641 $s->{dumplog} = $fh;
642 }
643  
644 $fh;
645 } # end sub dump_log
646  
647  
648 sub eof {
649 my ($self) = @_;
650  
651 *$self->{net_telnet}{eofile};
652 } # end sub eof
653  
654  
655 sub errmode {
656 my ($self, $mode) = @_;
657 my (
658 $prev,
659 $s,
660 );
661  
662 $s = *$self->{net_telnet};
663 $prev = $s->{errormode};
664  
665 if (@_ >= 2) {
666 $s->{errormode} = &_parse_errmode($self, $mode);
667 }
668  
669 $prev;
670 } # end sub errmode
671  
672  
673 sub errmsg {
674 my ($self, @errmsgs) = @_;
675 my (
676 $prev,
677 $s,
678 );
679  
680 $s = *$self->{net_telnet};
681 $prev = $s->{errormsg};
682  
683 if (@_ >= 2) {
684 $s->{errormsg} = join "", @errmsgs;
685 }
686  
687 $prev;
688 } # end sub errmsg
689  
690  
691 sub error {
692 my ($self, @errmsg) = @_;
693 my (
694 $errmsg,
695 $func,
696 $mode,
697 $s,
698 @args,
699 );
700 local $_;
701  
702 $s = *$self->{net_telnet};
703  
704 if (@_ >= 2) {
705 ## Put error message in the object.
706 $errmsg = join "", @errmsg;
707 $s->{errormsg} = $errmsg;
708  
709 ## Do the error action as described by error mode.
710 $mode = $s->{errormode};
711 if (ref($mode) eq "CODE") {
712 &$mode($errmsg);
713 return;
714 }
715 elsif (ref($mode) eq "ARRAY") {
716 ($func, @args) = @$mode;
717 &$func(@args);
718 return;
719 }
720 elsif ($mode =~ /^return$/i) {
721 return;
722 }
723 else { # die
724 if ($errmsg =~ /\n$/) {
725 die $errmsg;
726 }
727 else {
728 ## Die and append caller's line number to message.
729 &_croak($self, $errmsg);
730 }
731 }
732 }
733 else {
734 return $s->{errormsg} ne "";
735 }
736 } # end sub error
737  
738  
739 sub family {
740 my ($self, $family) = @_;
741 my (
742 $prev,
743 $s,
744 );
745  
746 $s = *$self->{net_telnet};
747 $prev = $s->{peer_family};
748  
749 if (@_ >= 2) {
750 $family = &_parse_family($self, $family)
751 or return;
752  
753 $s->{peer_family} = $family;
754 }
755  
756 $prev;
757 } # end sub family
758  
759  
760 sub fhopen {
761 my ($self, $fh) = @_;
762 my (
763 $globref,
764 $s,
765 );
766  
767 ## Convert given filehandle to a typeglob reference, if necessary.
768 $globref = &_qualify_fh($self, $fh);
769  
770 ## Ensure filehandle is already open.
771 return $self->error("fhopen filehandle isn't already open")
772 unless defined($globref) and defined(fileno $globref);
773  
774 ## Ensure we're closed.
775 $self->close;
776  
777 ## Save our private data.
778 $s = *$self->{net_telnet};
779  
780 ## Switch ourself with the given filehandle.
781 *$self = *$globref;
782  
783 ## Restore our private data.
784 *$self->{net_telnet} = $s;
785  
786 ## Re-initialize ourself.
787 select((select($self), $|=1)[$[]); # don't buffer writes
788 $s = *$self->{net_telnet};
789 $s->{blksize} = &_optimal_blksize((stat $self)[11]);
790 $s->{buf} = "";
791 $s->{eofile} = '';
792 $s->{errormsg} = "";
793 vec($s->{fdmask}='', fileno($self), 1) = 1;
794 $s->{host} = "";
795 $s->{last_line} = "";
796 $s->{last_prompt} = "";
797 $s->{num_wrote} = 0;
798 $s->{opened} = 1;
799 $s->{pending_errormsg} = "";
800 $s->{port} = '';
801 $s->{pushback_buf} = "";
802 $s->{select_supported} = $^O ne "MSWin32" || -S $self;
803 $s->{timedout} = '';
804 $s->{unsent_opts} = "";
805 &_reset_options($s->{opts});
806  
807 1;
808 } # end sub fhopen
809  
810  
811 sub get {
812 my ($self, %args) = @_;
813 my (
814 $binmode,
815 $endtime,
816 $errmode,
817 $line,
818 $s,
819 $telnetmode,
820 $timeout,
821 );
822 local $_;
823  
824 ## Init.
825 $s = *$self->{net_telnet};
826 $timeout = $s->{time_out};
827 $s->{timedout} = '';
828 return if $s->{eofile};
829  
830 ## Parse the named args.
831 foreach (keys %args) {
832 if (/^-?binmode$/i) {
833 $binmode = $args{$_};
834 unless (defined $binmode) {
835 $binmode = 0;
836 }
837 }
838 elsif (/^-?errmode$/i) {
839 $errmode = &_parse_errmode($self, $args{$_});
840 }
841 elsif (/^-?telnetmode$/i) {
842 $telnetmode = $args{$_};
843 unless (defined $telnetmode) {
844 $telnetmode = 0;
845 }
846 }
847 elsif (/^-?timeout$/i) {
848 $timeout = &_parse_timeout($self, $args{$_});
849 }
850 else {
851 &_croak($self, "bad named parameter \"$_\" given " .
852 "to " . ref($self) . "::get()");
853 }
854 }
855  
856 ## If any args given, override corresponding instance data.
857 local $s->{errormode} = $errmode
858 if defined $errmode;
859 local $s->{bin_mode} = $binmode
860 if defined $binmode;
861 local $s->{telnet_mode} = $telnetmode
862 if defined $telnetmode;
863  
864 ## Set wall time when we time out.
865 $endtime = &_endtime($timeout);
866  
867 ## Try to send any waiting option negotiation.
868 if (length $s->{unsent_opts}) {
869 &_flush_opts($self);
870 }
871  
872 ## Try to read just the waiting data using return error mode.
873 {
874 local $s->{errormode} = "return";
875 $s->{errormsg} = "";
876 &_fillbuf($self, $s, 0);
877 }
878  
879 ## We're done if we timed-out and timeout value is set to "poll".
880 return $self->error($s->{errormsg})
881 if ($s->{timedout} and defined($timeout) and $timeout == 0
882 and !length $s->{buf});
883  
884 ## We're done if we hit an error other than timing out.
885 if ($s->{errormsg} and !$s->{timedout}) {
886 if (!length $s->{buf}) {
887 return $self->error($s->{errormsg});
888 }
889 else { # error encountered but there's some data in buffer
890 $s->{pending_errormsg} = $s->{errormsg};
891 }
892 }
893  
894 ## Clear time-out error from first read.
895 $s->{timedout} = '';
896 $s->{errormsg} = "";
897  
898 ## If buffer is still empty, try to read according to user's timeout.
899 if (!length $s->{buf}) {
900 &_fillbuf($self, $s, $endtime)
901 or do {
902 return if $s->{timedout};
903  
904 ## We've reached end-of-file.
905 $self->close;
906 return;
907 };
908 }
909  
910 ## Extract chars from buffer.
911 $line = $s->{buf};
912 $s->{buf} = "";
913  
914 $line;
915 } # end sub get
916  
917  
918 sub getline {
919 my ($self, %args) = @_;
920 my (
921 $binmode,
922 $endtime,
923 $errmode,
924 $len,
925 $line,
926 $offset,
927 $pos,
928 $rs,
929 $s,
930 $telnetmode,
931 $timeout,
932 );
933 local $_;
934  
935 ## Init.
936 $s = *$self->{net_telnet};
937 $s->{timedout} = '';
938 return if $s->{eofile};
939 $rs = $s->{"rs"};
940 $timeout = $s->{time_out};
941  
942 ## Parse the named args.
943 foreach (keys %args) {
944 if (/^-?binmode$/i) {
945 $binmode = $args{$_};
946 unless (defined $binmode) {
947 $binmode = 0;
948 }
949 }
950 elsif (/^-?errmode$/i) {
951 $errmode = &_parse_errmode($self, $args{$_});
952 }
953 elsif (/^-?input_record_separator$/i or /^-?rs$/i) {
954 $rs = &_parse_input_record_separator($self, $args{$_});
955 }
956 elsif (/^-?telnetmode$/i) {
957 $telnetmode = $args{$_};
958 unless (defined $telnetmode) {
959 $telnetmode = 0;
960 }
961 }
962 elsif (/^-?timeout$/i) {
963 $timeout = &_parse_timeout($self, $args{$_});
964 }
965 else {
966 &_croak($self, "bad named parameter \"$_\" given " .
967 "to " . ref($self) . "::getline()");
968 }
969 }
970  
971 ## If any args given, override corresponding instance data.
972 local $s->{bin_mode} = $binmode
973 if defined $binmode;
974 local $s->{errormode} = $errmode
975 if defined $errmode;
976 local $s->{telnet_mode} = $telnetmode
977 if defined $telnetmode;
978  
979 ## Set wall time when we time out.
980 $endtime = &_endtime($timeout);
981  
982 ## Try to send any waiting option negotiation.
983 if (length $s->{unsent_opts}) {
984 &_flush_opts($self);
985 }
986  
987 ## Keep reading into buffer until end-of-line is read.
988 $offset = 0;
989 while (($pos = index($s->{buf}, $rs, $offset)) == -1) {
990 $offset = length $s->{buf};
991 &_fillbuf($self, $s, $endtime)
992 or do {
993 return if $s->{timedout};
994  
995 ## We've reached end-of-file.
996 $self->close;
997 if (length $s->{buf}) {
998 return $s->{buf};
999 }
1000 else {
1001 return;
1002 }
1003 };
1004 }
1005  
1006 ## Extract line from buffer.
1007 $len = $pos + length $rs;
1008 $line = substr($s->{buf}, 0, $len);
1009 substr($s->{buf}, 0, $len) = "";
1010  
1011 $line;
1012 } # end sub getline
1013  
1014  
1015 sub getlines {
1016 my ($self, %args) = @_;
1017 my (
1018 $binmode,
1019 $errmode,
1020 $line,
1021 $rs,
1022 $s,
1023 $telnetmode,
1024 $timeout,
1025 );
1026 my $all = 1;
1027 my @lines = ();
1028 local $_;
1029  
1030 ## Init.
1031 $s = *$self->{net_telnet};
1032 $s->{timedout} = '';
1033 return if $s->{eofile};
1034 $timeout = $s->{time_out};
1035  
1036 ## Parse the named args.
1037 foreach (keys %args) {
1038 if (/^-?all$/i) {
1039 $all = $args{$_};
1040 unless (defined $all) {
1041 $all = '';
1042 }
1043 }
1044 elsif (/^-?binmode$/i) {
1045 $binmode = $args{$_};
1046 unless (defined $binmode) {
1047 $binmode = 0;
1048 }
1049 }
1050 elsif (/^-?errmode$/i) {
1051 $errmode = &_parse_errmode($self, $args{$_});
1052 }
1053 elsif (/^-?input_record_separator$/i or /^-?rs$/i) {
1054 $rs = &_parse_input_record_separator($self, $args{$_});
1055 }
1056 elsif (/^-?telnetmode$/i) {
1057 $telnetmode = $args{$_};
1058 unless (defined $telnetmode) {
1059 $telnetmode = 0;
1060 }
1061 }
1062 elsif (/^-?timeout$/i) {
1063 $timeout = &_parse_timeout($self, $args{$_});
1064 }
1065 else {
1066 &_croak($self, "bad named parameter \"$_\" given " .
1067 "to " . ref($self) . "::getlines()");
1068 }
1069 }
1070  
1071 ## If any args given, override corresponding instance data.
1072 local $s->{bin_mode} = $binmode
1073 if defined $binmode;
1074 local $s->{errormode} = $errmode
1075 if defined $errmode;
1076 local $s->{"rs"} = $rs
1077 if defined $rs;
1078 local $s->{telnet_mode} = $telnetmode
1079 if defined $telnetmode;
1080 local $s->{time_out} = &_endtime($timeout);
1081  
1082 ## User requested only the currently available lines.
1083 if (! $all) {
1084 return &_next_getlines($self, $s);
1085 }
1086  
1087 ## Read lines until eof or error.
1088 while (1) {
1089 $line = $self->getline
1090 or last;
1091 push @lines, $line;
1092 }
1093  
1094 ## Check for error.
1095 return if ! $self->eof;
1096  
1097 @lines;
1098 } # end sub getlines
1099  
1100  
1101 sub host {
1102 my ($self, $host) = @_;
1103 my (
1104 $prev,
1105 $s,
1106 );
1107  
1108 $s = *$self->{net_telnet};
1109 $prev = $s->{host};
1110  
1111 if (@_ >= 2) {
1112 unless (defined $host) {
1113 $host = "";
1114 }
1115  
1116 $s->{host} = $host;
1117 }
1118  
1119 $prev;
1120 } # end sub host
1121  
1122  
1123 sub input_log {
1124 my ($self, $name) = @_;
1125 my (
1126 $fh,
1127 $s,
1128 );
1129  
1130 $s = *$self->{net_telnet};
1131 $fh = $s->{inputlog};
1132  
1133 if (@_ >= 2) {
1134 if (!defined($name) or $name eq "") { # input arg is ""
1135 ## Turn off logging.
1136 $fh = "";
1137 }
1138 elsif (&_is_open_fh($name)) { # input arg is an open fh
1139 ## Use the open fh for logging.
1140 $fh = $name;
1141 select((select($fh), $|=1)[$[]); # don't buffer writes
1142 }
1143 elsif (!ref $name) { # input arg is filename
1144 ## Open the file for logging.
1145 $fh = &_fname_to_handle($self, $name)
1146 or return;
1147 select((select($fh), $|=1)[$[]); # don't buffer writes
1148 }
1149 else {
1150 return $self->error("bad Input_log argument ",
1151 "\"$name\": not filename or open fh");
1152 }
1153  
1154 $s->{inputlog} = $fh;
1155 }
1156  
1157 $fh;
1158 } # end sub input_log
1159  
1160  
1161 sub input_record_separator {
1162 my ($self, $rs) = @_;
1163 my (
1164 $prev,
1165 $s,
1166 );
1167  
1168 $s = *$self->{net_telnet};
1169 $prev = $s->{"rs"};
1170  
1171 if (@_ >= 2) {
1172 $s->{"rs"} = &_parse_input_record_separator($self, $rs);
1173 }
1174  
1175 $prev;
1176 } # end sub input_record_separator
1177  
1178  
1179 sub last_prompt {
1180 my ($self, $string) = @_;
1181 my (
1182 $prev,
1183 $s,
1184 );
1185  
1186 $s = *$self->{net_telnet};
1187 $prev = $s->{last_prompt};
1188  
1189 if (@_ >= 2) {
1190 unless (defined $string) {
1191 $string = "";
1192 }
1193  
1194 $s->{last_prompt} = $string;
1195 }
1196  
1197 $prev;
1198 } # end sub last_prompt
1199  
1200  
1201 sub lastline {
1202 my ($self, $line) = @_;
1203 my (
1204 $prev,
1205 $s,
1206 );
1207  
1208 $s = *$self->{net_telnet};
1209 $prev = $s->{last_line};
1210  
1211 if (@_ >= 2) {
1212 unless (defined $line) {
1213 $line = "";
1214 }
1215  
1216 $s->{last_line} = $line;
1217 }
1218  
1219 $prev;
1220 } # end sub lastline
1221  
1222  
1223 sub localfamily {
1224 my ($self, $family) = @_;
1225 my (
1226 $prev,
1227 $s,
1228 $socket_version,
1229 );
1230  
1231 $s = *$self->{net_telnet};
1232 $prev = $s->{local_family};
1233 $socket_version = $Socket::VERSION; # replace '2.020_03' with '2.020'
1234 $socket_version =~ s/\_.*$//;
1235  
1236 if (@_ >= 2) {
1237 unless (defined $family) {
1238 $family = "";
1239 }
1240  
1241 if ($family =~ /^\s*ipv4\s*$/i) { # family arg is "ipv4"
1242 $s->{local_family} = "ipv4";
1243 }
1244 elsif ($family =~ /^\s*any\s*$/i) { # family arg is "any"
1245 if ($socket_version >= 1.94 and defined $AF_INET6) { # has IPv6
1246 $s->{local_family} = "any";
1247 }
1248 else { # IPv6 not supported on this machine
1249 $s->{local_family} = "ipv4";
1250 }
1251 }
1252 elsif ($family =~ /^\s*ipv6\s*$/i) { # family arg is "ipv6"
1253 return $self->error("Localfamily arg ipv6 not supported when " .
1254 "Socket.pm version < 1.94")
1255 unless $socket_version >= 1.94;
1256 return $self->error("Localfamily arg ipv6 not supported by " .
1257 "this OS: AF_INET6 not in Socket.pm")
1258 unless defined $AF_INET6;
1259  
1260 $s->{local_family} = "ipv6";
1261 }
1262 else {
1263 return $self->error("bad Localfamily argument \"$family\": " .
1264 "must be \"ipv4\", \"ipv6\", or \"any\"");
1265 }
1266 }
1267  
1268 $prev;
1269 } # end sub localfamily
1270  
1271  
1272 sub localhost {
1273 my ($self, $localhost) = @_;
1274 my (
1275 $prev,
1276 $s,
1277 );
1278  
1279 $s = *$self->{net_telnet};
1280 $prev = $s->{local_host};
1281  
1282 if (@_ >= 2) {
1283 unless (defined $localhost) {
1284 $localhost = "";
1285 }
1286  
1287 $s->{local_host} = $localhost;
1288 }
1289  
1290 $prev;
1291 } # end sub localhost
1292  
1293  
1294 sub login {
1295 my ($self, @args) = @_;
1296 my (
1297 $arg_errmode,
1298 $error,
1299 $is_passwd_arg,
1300 $is_username_arg,
1301 $lastline,
1302 $match,
1303 $ors,
1304 $passwd,
1305 $prematch,
1306 $prompt,
1307 $s,
1308 $timeout,
1309 $username,
1310 %args,
1311 );
1312 local $_;
1313  
1314 ## Init.
1315 $self->timed_out('');
1316 $self->last_prompt("");
1317 $s = *$self->{net_telnet};
1318 $timeout = $self->timeout;
1319 $ors = $self->output_record_separator;
1320 $prompt = $self->prompt;
1321  
1322 ## Parse positional args.
1323 if (@args == 2) { # just username and passwd given
1324 $username = $args[0];
1325 $passwd = $args[1];
1326  
1327 $is_username_arg = 1;
1328 $is_passwd_arg = 1;
1329 }
1330  
1331 ## Override errmode first, if specified.
1332 $arg_errmode = &_extract_arg_errmode($self, \@args);
1333 local $s->{errormode} = $arg_errmode
1334 if $arg_errmode;
1335  
1336 ## Parse named args.
1337 if (@args > 2) {
1338 ## Get the named args.
1339 %args = @args;
1340  
1341 ## Parse the named args.
1342 foreach (keys %args) {
1343 if (/^-?name$/i) {
1344 $username = $args{$_};
1345 unless (defined $username) {
1346 $username = "";
1347 }
1348  
1349 $is_username_arg = 1;
1350 }
1351 elsif (/^-?pass/i) {
1352 $passwd = $args{$_};
1353 unless (defined $passwd) {
1354 $passwd = "";
1355 }
1356  
1357 $is_passwd_arg = 1;
1358 }
1359 elsif (/^-?prompt$/i) {
1360 $prompt = &_parse_prompt($self, $args{$_})
1361 or return;
1362 }
1363 elsif (/^-?timeout$/i) {
1364 $timeout = &_parse_timeout($self, $args{$_});
1365 }
1366 else {
1367 &_croak($self, "bad named parameter \"$_\" given ",
1368 "to " . ref($self) . "::login()");
1369 }
1370 }
1371 }
1372  
1373 ## Ensure both username and password argument given.
1374 &_croak($self,"Name argument not given to " . ref($self) . "::login()")
1375 unless $is_username_arg;
1376 &_croak($self,"Password argument not given to " . ref($self) . "::login()")
1377 unless $is_passwd_arg;
1378  
1379 ## Set timeout for this invocation.
1380 local $s->{time_out} = &_endtime($timeout);
1381  
1382 ## Create a subroutine to generate an error.
1383 $error
1384 = sub {
1385 my ($errmsg) = @_;
1386  
1387 if ($self->timed_out) {
1388 return $self->error($errmsg);
1389 }
1390 elsif ($self->eof) {
1391 ($lastline = $self->lastline) =~ s/\n+//;
1392 return $self->error($errmsg, ": ", $lastline);
1393 }
1394 else {
1395 return $self->error($self->errmsg);
1396 }
1397 };
1398  
1399  
1400 return $self->error("login failed: filehandle isn't open")
1401 if $self->eof;
1402  
1403 ## Wait for login prompt.
1404 $self->waitfor(Match => '/login[: ]*$/i',
1405 Match => '/username[: ]*$/i',
1406 Errmode => "return")
1407 or do {
1408 return &$error("eof read waiting for login prompt")
1409 if $self->eof;
1410 return &$error("timed-out waiting for login prompt");
1411 };
1412  
1413 ## Delay sending response because of bug in Linux login program.
1414 &_sleep(0.01);
1415  
1416 ## Send login name.
1417 $self->put(String => $username . $ors,
1418 Errmode => "return")
1419 or return &$error("login disconnected");
1420  
1421 ## Wait for password prompt.
1422 $self->waitfor(Match => '/password[: ]*$/i',
1423 Errmode => "return")
1424 or do {
1425 return &$error("eof read waiting for password prompt")
1426 if $self->eof;
1427 return &$error("timed-out waiting for password prompt");
1428 };
1429  
1430 ## Delay sending response because of bug in Linux login program.
1431 &_sleep(0.01);
1432  
1433 ## Send password.
1434 $self->put(String => $passwd . $ors,
1435 Errmode => "return")
1436 or return &$error("login disconnected");
1437  
1438 ## Wait for command prompt or another login prompt.
1439 ($prematch, $match) = $self->waitfor(Match => '/login[: ]*$/i',
1440 Match => '/username[: ]*$/i',
1441 Match => $prompt,
1442 Errmode => "return")
1443 or do {
1444 return &$error("eof read waiting for command prompt")
1445 if $self->eof;
1446 return &$error("timed-out waiting for command prompt");
1447 };
1448  
1449 ## It's a bad login if we got another login prompt.
1450 return $self->error("login failed: bad name or password")
1451 if $match =~ /login[: ]*$/i or $match =~ /username[: ]*$/i;
1452  
1453 ## Save the most recently matched command prompt.
1454 $self->last_prompt($match);
1455  
1456 1;
1457 } # end sub login
1458  
1459  
1460 sub max_buffer_length {
1461 my ($self, $maxbufsize) = @_;
1462 my (
1463 $prev,
1464 $s,
1465 );
1466 my $minbufsize = 512;
1467  
1468 $s = *$self->{net_telnet};
1469 $prev = $s->{maxbufsize};
1470  
1471 if (@_ >= 2) {
1472 ## Ensure a positive integer value.
1473 unless (defined $maxbufsize
1474 and $maxbufsize =~ /^\d+$/
1475 and $maxbufsize)
1476 {
1477 &_carp($self, "ignoring bad Max_buffer_length " .
1478 "argument \"$maxbufsize\": it's not a positive integer");
1479 $maxbufsize = $prev;
1480 }
1481  
1482 ## Adjust up values that are too small.
1483 if ($maxbufsize < $minbufsize) {
1484 $maxbufsize = $minbufsize;
1485 }
1486  
1487 $s->{maxbufsize} = $maxbufsize;
1488 }
1489  
1490 $prev;
1491 } # end sub max_buffer_length
1492  
1493  
1494 ## Make ofs() synonymous with output_field_separator().
1495 sub ofs { &output_field_separator; }
1496  
1497  
1498 sub open {
1499 my ($self, @args) = @_;
1500 my (
1501 $af,
1502 $arg_errmode,
1503 $err,
1504 $errno,
1505 $family,
1506 $flags_hint,
1507 $host,
1508 $ip_addr,
1509 $lfamily,
1510 $localhost,
1511 $port,
1512 $s,
1513 $timeout,
1514 %args,
1515 @ai,
1516 );
1517 local $@;
1518 local $_;
1519 my $local_addr = '';
1520 my $remote_addr = '';
1521 my %af = (
1522 ipv4 => AF_INET,
1523 ipv6 => defined($AF_INET6) ? $AF_INET6 : undef,
1524 any => $AF_UNSPEC,
1525 );
1526  
1527 ## Init.
1528 $s = *$self->{net_telnet};
1529 $s->{timedout} = '';
1530 $s->{sock_family} = 0;
1531 $port = $self->port;
1532 $family = $self->family;
1533 $localhost = $self->localhost;
1534 $lfamily = $self->localfamily;
1535 $timeout = $self->timeout;
1536  
1537 ## Override errmode first, if specified.
1538 $arg_errmode = &_extract_arg_errmode($self, \@args);
1539 local $s->{errormode} = $arg_errmode
1540 if $arg_errmode;
1541  
1542 if (@args == 1) { # one positional arg given
1543 $self->host($args[0]);
1544 }
1545 elsif (@args >= 2) { # named args given
1546 ## Get the named args.
1547 %args = @args;
1548  
1549 ## Parse the named args.
1550 foreach (keys %args) {
1551 if (/^-?family$/i) {
1552 $family = &_parse_family($self, $args{$_});
1553 }
1554 elsif (/^-?host$/i) {
1555 $self->host($args{$_});
1556 }
1557 elsif (/^-?localfamily$/i) {
1558 $lfamily = &_parse_localfamily($self, $args{$_});
1559 }
1560 elsif (/^-?localhost$/i) {
1561 $args{$_} = "" unless defined $args{$_};
1562 $localhost = $args{$_};
1563 }
1564 elsif (/^-?port$/i) {
1565 $port = &_parse_port($self, $args{$_});
1566 }
1567 elsif (/^-?timeout$/i) {
1568 $timeout = &_parse_timeout($self, $args{$_});
1569 }
1570 else {
1571 &_croak($self, "bad named parameter \"$_\" given ",
1572 "to " . ref($self) . "::open()");
1573 }
1574 }
1575 }
1576  
1577 ## Get hostname/ip address.
1578 $host = $self->host;
1579  
1580 ## Ensure we're already closed.
1581 $self->close;
1582  
1583 ## Connect with or without a timeout.
1584 if (defined($timeout) and &_have_alarm) { # use a timeout
1585 ## Convert possible absolute timeout to relative timeout.
1586 if ($timeout >= $^T) { # it's an absolute time
1587 $timeout = $timeout - time;
1588 }
1589  
1590 ## Ensure a valid timeout value for alarm.
1591 if ($timeout < 1) {
1592 $timeout = 1;
1593 }
1594 $timeout = int($timeout + 0.5);
1595  
1596 ## Connect to server, timing out if it takes too long.
1597 eval {
1598 ## Turn on timer.
1599 local $SIG{"__DIE__"} = "DEFAULT";
1600 local $SIG{ALRM} = sub { die "timed-out\n" };
1601 alarm $timeout;
1602  
1603 if ($family eq "ipv4") {
1604 ## Lookup server's IP address.
1605 $ip_addr = inet_aton $host
1606 or die "unknown remote host: $host\n";
1607 $af = AF_INET;
1608 $remote_addr = sockaddr_in($port, $ip_addr);
1609 }
1610 else { # family is "ipv6" or "any"
1611 ## Lookup server's IP address.
1612 $flags_hint = $family eq "any" ? $AI_ADDRCONFIG : 0;
1613 ($err, @ai) = Socket::getaddrinfo($host, $port,
1614 { socktype => SOCK_STREAM,
1615 "family" => $af{$family},
1616 "flags" => $flags_hint });
1617 if ($err == $EAI_BADFLAGS) {
1618 ## Try again with no flags.
1619 ($err, @ai) = Socket::getaddrinfo($host, $port,
1620 {socktype => SOCK_STREAM,
1621 "family"=> $af{$family},
1622 "flags" => 0 });
1623 }
1624 die "unknown remote host: $host: $err\n"
1625 if $err or !@ai;
1626 $af = $ai[0]{"family"};
1627 $remote_addr = $ai[0]{addr};
1628 }
1629  
1630 ## Create a socket and attach the filehandle to it.
1631 socket $self, $af, SOCK_STREAM, 0
1632 or die "problem creating socket: $!\n";
1633  
1634 ## Bind to a local network interface.
1635 if (length $localhost) {
1636 if ($lfamily eq "ipv4") {
1637 ## Lookup server's IP address.
1638 $ip_addr = inet_aton $localhost
1639 or die "unknown local host: $localhost\n";
1640 $local_addr = sockaddr_in(0, $ip_addr);
1641 }
1642 else { # local family is "ipv6" or "any"
1643 ## Lookup local IP address.
1644 ($err, @ai) = Socket::getaddrinfo($localhost, 0,
1645 {socktype => SOCK_STREAM,
1646 "family"=>$af{$lfamily},
1647 "flags" => 0 });
1648 die "unknown local host: $localhost: $err\n"
1649 if $err or !@ai;
1650 $local_addr = $ai[0]{addr};
1651 }
1652  
1653 bind $self, $local_addr
1654 or die "problem binding to \"$localhost\": $!\n";
1655 }
1656  
1657 ## Enable keepalive packets
1658 setsockopt($self, SOL_SOCKET, SO_KEEPALIVE, 1);
1659  
1660 ## Open connection to server.
1661 connect $self, $remote_addr
1662 or die "problem connecting to \"$host\", port $port: $!\n";
1663 };
1664 alarm 0;
1665  
1666 ## Check for error.
1667 if ($@ =~ /^timed-out$/) { # time out failure
1668 $s->{timedout} = 1;
1669 $self->close;
1670 if (!$remote_addr) {
1671 return $self->error("unknown remote host: $host: ",
1672 "name lookup timed-out");
1673 }
1674 elsif (length($localhost) and !$local_addr) {
1675 return $self->error("unknown local host: $localhost: ",
1676 "name lookup timed-out");
1677 }
1678 else {
1679 return $self->error("problem connecting to \"$host\", ",
1680 "port $port: connect timed-out");
1681 }
1682 }
1683 elsif ($@) { # hostname lookup or connect failure
1684 $self->close;
1685 chomp $@;
1686 return $self->error($@);
1687 }
1688 }
1689 else { # don't use a timeout
1690 $timeout = undef;
1691  
1692 if ($family eq "ipv4") {
1693 ## Lookup server's IP address.
1694 $ip_addr = inet_aton $host
1695 or return $self->error("unknown remote host: $host");
1696 $af = AF_INET;
1697 $remote_addr = sockaddr_in($port, $ip_addr);
1698 }
1699 else { # family is "ipv6" or "any"
1700 ## Lookup server's IP address.
1701 $flags_hint = $family eq "any" ? $AI_ADDRCONFIG : 0;
1702 ($err, @ai) = Socket::getaddrinfo($host, $port,
1703 { socktype => SOCK_STREAM,
1704 "family" => $af{$family},
1705 "flags" => $flags_hint });
1706 if ($err == $EAI_BADFLAGS) {
1707 ## Try again with no flags.
1708 ($err, @ai) = Socket::getaddrinfo($host, $port,
1709 { socktype => SOCK_STREAM,
1710 "family"=> $af{$family},
1711 "flags" => 0 });
1712 }
1713 return $self->error("unknown remote host: $host")
1714 if $err or !@ai;
1715 $af = $ai[0]{"family"};
1716 $remote_addr = $ai[0]{addr};
1717 }
1718  
1719 ## Create a socket and attach the filehandle to it.
1720 socket $self, $af, SOCK_STREAM, 0
1721 or return $self->error("problem creating socket: $!");
1722  
1723 ## Bind to a local network interface.
1724 if (length $localhost) {
1725 if ($lfamily eq "ipv4") {
1726 ## Lookup server's IP address.
1727 $ip_addr = inet_aton $localhost
1728 or return $self->error("unknown local host: $localhost");
1729 $local_addr = sockaddr_in(0, $ip_addr);
1730 }
1731 else { # local family is "ipv6" or "any"
1732 ## Lookup local IP address.
1733 ($err, @ai) = Socket::getaddrinfo($localhost, 0,
1734 { socktype => SOCK_STREAM,
1735 "family"=>$af{$lfamily},
1736 "flags" => 0 });
1737 return $self->error("unknown local host: $localhost: $err")
1738 if $err or !@ai;
1739 $local_addr = $ai[0]{addr};
1740 }
1741  
1742 bind $self, $local_addr
1743 or return $self->error("problem binding ",
1744 "to \"$localhost\": $!");
1745 }
1746  
1747 ## Open connection to server.
1748 connect $self, $remote_addr
1749 or do {
1750 $errno = "$!";
1751 $self->close;
1752 return $self->error("problem connecting to \"$host\", ",
1753 "port $port: $errno");
1754 };
1755 }
1756  
1757 select((select($self), $|=1)[$[]); # don't buffer writes
1758 $s->{blksize} = &_optimal_blksize((stat $self)[11]);
1759 $s->{buf} = "";
1760 $s->{eofile} = '';
1761 $s->{errormsg} = "";
1762 vec($s->{fdmask}='', fileno($self), 1) = 1;
1763 $s->{last_line} = "";
1764 $s->{sock_family} = $af;
1765 $s->{num_wrote} = 0;
1766 $s->{opened} = 1;
1767 $s->{pending_errormsg} = "";
1768 $s->{pushback_buf} = "";
1769 $s->{select_supported} = 1;
1770 $s->{timedout} = '';
1771 $s->{unsent_opts} = "";
1772 &_reset_options($s->{opts});
1773  
1774 1;
1775 } # end sub open
1776  
1777  
1778 sub option_accept {
1779 my ($self, @args) = @_;
1780 my (
1781 $arg,
1782 $option,
1783 $s,
1784 @opt_args,
1785 );
1786 local $_;
1787  
1788 ## Init.
1789 $s = *$self->{net_telnet};
1790  
1791 ## Parse the named args.
1792 while (($_, $arg) = splice @args, 0, 2) {
1793 ## Verify and save arguments.
1794 if (/^-?do$/i) {
1795 ## Make sure a callback is defined.
1796 return $self->error("usage: an option callback must already ",
1797 "be defined when enabling with $_")
1798 unless $s->{opt_cback};
1799  
1800 $option = &_verify_telopt_arg($self, $arg, $_);
1801 return unless defined $option;
1802 push @opt_args, { option => $option,
1803 is_remote => '',
1804 is_enable => 1,
1805 };
1806 }
1807 elsif (/^-?dont$/i) {
1808 $option = &_verify_telopt_arg($self, $arg, $_);
1809 return unless defined $option;
1810 push @opt_args, { option => $option,
1811 is_remote => '',
1812 is_enable => '',
1813 };
1814 }
1815 elsif (/^-?will$/i) {
1816 ## Make sure a callback is defined.
1817 return $self->error("usage: an option callback must already ",
1818 "be defined when enabling with $_")
1819 unless $s->{opt_cback};
1820  
1821 $option = &_verify_telopt_arg($self, $arg, $_);
1822 return unless defined $option;
1823 push @opt_args, { option => $option,
1824 is_remote => 1,
1825 is_enable => 1,
1826 };
1827 }
1828 elsif (/^-?wont$/i) {
1829 $option = &_verify_telopt_arg($self, $arg, $_);
1830 return unless defined $option;
1831 push @opt_args, { option => $option,
1832 is_remote => 1,
1833 is_enable => '',
1834 };
1835 }
1836 else {
1837 return $self->error('usage: $obj->option_accept(' .
1838 '[Do => $telopt,] ',
1839 '[Dont => $telopt,] ',
1840 '[Will => $telopt,] ',
1841 '[Wont => $telopt,]');
1842 }
1843 }
1844  
1845 ## Set "receive ok" for options specified.
1846 &_opt_accept($self, @opt_args);
1847 } # end sub option_accept
1848  
1849  
1850 sub option_callback {
1851 my ($self, $callback) = @_;
1852 my (
1853 $prev,
1854 $s,
1855 );
1856  
1857 $s = *$self->{net_telnet};
1858 $prev = $s->{opt_cback};
1859  
1860 if (@_ >= 2) {
1861 unless (defined $callback and ref($callback) eq "CODE") {
1862 &_carp($self, "ignoring Option_callback argument because it's " .
1863 "not a code ref");
1864 $callback = $prev;
1865 }
1866  
1867 $s->{opt_cback} = $callback;
1868 }
1869  
1870 $prev;
1871 } # end sub option_callback
1872  
1873  
1874 sub option_log {
1875 my ($self, $name) = @_;
1876 my (
1877 $fh,
1878 $s,
1879 );
1880  
1881 $s = *$self->{net_telnet};
1882 $fh = $s->{opt_log};
1883  
1884 if (@_ >= 2) {
1885 if (!defined($name) or $name eq "") { # input arg is ""
1886 ## Turn off logging.
1887 $fh = "";
1888 }
1889 elsif (&_is_open_fh($name)) { # input arg is an open fh
1890 ## Use the open fh for logging.
1891 $fh = $name;
1892 select((select($fh), $|=1)[$[]); # don't buffer writes
1893 }
1894 elsif (!ref $name) { # input arg is filename
1895 ## Open the file for logging.
1896 $fh = &_fname_to_handle($self, $name)
1897 or return;
1898 select((select($fh), $|=1)[$[]); # don't buffer writes
1899 }
1900 else {
1901 return $self->error("bad Option_log argument ",
1902 "\"$name\": not filename or open fh");
1903 }
1904  
1905 $s->{opt_log} = $fh;
1906 }
1907  
1908 $fh;
1909 } # end sub option_log
1910  
1911  
1912 sub option_state {
1913 my ($self, $option) = @_;
1914 my (
1915 $opt_state,
1916 $s,
1917 %opt_state,
1918 );
1919  
1920 ## Ensure telnet option is non-negative integer.
1921 $option = &_verify_telopt_arg($self, $option);
1922 return unless defined $option;
1923  
1924 ## Init.
1925 $s = *$self->{net_telnet};
1926 unless (defined $s->{opts}{$option}) {
1927 &_set_default_option($s, $option);
1928 }
1929  
1930 ## Return hashref to a copy of the values.
1931 $opt_state = $s->{opts}{$option};
1932 %opt_state = %$opt_state;
1933 \%opt_state;
1934 } # end sub option_state
1935  
1936  
1937 ## Make ors() synonymous with output_record_separator().
1938 sub ors { &output_record_separator; }
1939  
1940  
1941 sub output_field_separator {
1942 my ($self, $ofs) = @_;
1943 my (
1944 $prev,
1945 $s,
1946 );
1947  
1948 $s = *$self->{net_telnet};
1949 $prev = $s->{"ofs"};
1950  
1951 if (@_ >= 2) {
1952 unless (defined $ofs) {
1953 $ofs = "";
1954 }
1955  
1956 $s->{"ofs"} = $ofs;
1957 }
1958  
1959 $prev;
1960 } # end sub output_field_separator
1961  
1962  
1963 sub output_log {
1964 my ($self, $name) = @_;
1965 my (
1966 $fh,
1967 $s,
1968 );
1969  
1970 $s = *$self->{net_telnet};
1971 $fh = $s->{outputlog};
1972  
1973 if (@_ >= 2) {
1974 if (!defined($name) or $name eq "") { # input arg is ""
1975 ## Turn off logging.
1976 $fh = "";
1977 }
1978 elsif (&_is_open_fh($name)) { # input arg is an open fh
1979 ## Use the open fh for logging.
1980 $fh = $name;
1981 select((select($fh), $|=1)[$[]); # don't buffer writes
1982 }
1983 elsif (!ref $name) { # input arg is filename
1984 ## Open the file for logging.
1985 $fh = &_fname_to_handle($self, $name)
1986 or return;
1987 select((select($fh), $|=1)[$[]); # don't buffer writes
1988 }
1989 else {
1990 return $self->error("bad Output_log argument ",
1991 "\"$name\": not filename or open fh");
1992 }
1993  
1994 $s->{outputlog} = $fh;
1995 }
1996  
1997 $fh;
1998 } # end sub output_log
1999  
2000  
2001 sub output_record_separator {
2002 my ($self, $ors) = @_;
2003 my (
2004 $prev,
2005 $s,
2006 );
2007  
2008 $s = *$self->{net_telnet};
2009 $prev = $s->{"ors"};
2010  
2011 if (@_ >= 2) {
2012 unless (defined $ors) {
2013 $ors = "";
2014 }
2015  
2016 $s->{"ors"} = $ors;
2017 }
2018  
2019 $prev;
2020 } # end sub output_record_separator
2021  
2022  
2023 sub peerhost {
2024 my ($self) = @_;
2025 my (
2026 $host,
2027 $sockaddr,
2028 );
2029 local $^W = ''; # avoid closed socket warning from getpeername()
2030  
2031 ## Get packed sockaddr struct of remote side and then unpack it.
2032 $sockaddr = getpeername $self
2033 or return "";
2034 (undef, $host) = $self->_unpack_sockaddr($sockaddr);
2035  
2036 $host;
2037 } # end sub peerhost
2038  
2039  
2040 sub peerport {
2041 my ($self) = @_;
2042 my (
2043 $port,
2044 $sockaddr,
2045 );
2046 local $^W = ''; # avoid closed socket warning from getpeername()
2047  
2048 ## Get packed sockaddr struct of remote side and then unpack it.
2049 $sockaddr = getpeername $self
2050 or return "";
2051 ($port) = $self->_unpack_sockaddr($sockaddr);
2052  
2053 $port;
2054 } # end sub peerport
2055  
2056  
2057 sub port {
2058 my ($self, $port) = @_;
2059 my (
2060 $prev,
2061 $s,
2062 $service,
2063 );
2064  
2065 $s = *$self->{net_telnet};
2066 $prev = $s->{port};
2067  
2068 if (@_ >= 2) {
2069 $port = &_parse_port($self, $port)
2070 or return;
2071  
2072 $s->{port} = $port;
2073 }
2074  
2075 $prev;
2076 } # end sub port
2077  
2078  
2079 sub print {
2080 my ($self) = shift;
2081 my (
2082 $buf,
2083 $fh,
2084 $s,
2085 );
2086  
2087 $s = *$self->{net_telnet};
2088 $s->{timedout} = '';
2089 return $self->error("write error: filehandle isn't open")
2090 unless $s->{opened};
2091  
2092 ## Add field and record separators.
2093 $buf = join($s->{"ofs"}, @_) . $s->{"ors"};
2094  
2095 ## Log the output if requested.
2096 if ($s->{outputlog}) {
2097 &_log_print($s->{outputlog}, $buf);
2098 }
2099  
2100 ## Convert native newlines to CR LF.
2101 if (!$s->{bin_mode}) {
2102 $buf =~ s(\n)(\015\012)g;
2103 }
2104  
2105 ## Escape TELNET IAC and also CR not followed by LF.
2106 if ($s->{telnet_mode}) {
2107 $buf =~ s(\377)(\377\377)g;
2108 &_escape_cr(\$buf);
2109 }
2110  
2111 &_put($self, \$buf, "print");
2112 } # end sub print
2113  
2114  
2115 sub print_length {
2116 my ($self) = @_;
2117  
2118 *$self->{net_telnet}{num_wrote};
2119 } # end sub print_length
2120  
2121  
2122 sub prompt {
2123 my ($self, $prompt) = @_;
2124 my (
2125 $prev,
2126 $s,
2127 );
2128  
2129 $s = *$self->{net_telnet};
2130 $prev = $s->{cmd_prompt};
2131  
2132 ## Parse args.
2133 if (@_ == 2) {
2134 $prompt = &_parse_prompt($self, $prompt)
2135 or return;
2136  
2137 $s->{cmd_prompt} = $prompt;
2138 }
2139  
2140 $prev;
2141 } # end sub prompt
2142  
2143  
2144 sub put {
2145 my ($self) = @_;
2146 my (
2147 $binmode,
2148 $buf,
2149 $errmode,
2150 $is_timeout_arg,
2151 $s,
2152 $telnetmode,
2153 $timeout,
2154 %args,
2155 );
2156 local $_;
2157  
2158 ## Init.
2159 $s = *$self->{net_telnet};
2160 $s->{timedout} = '';
2161  
2162 ## Parse args.
2163 if (@_ == 2) { # one positional arg given
2164 $buf = $_[1];
2165 }
2166 elsif (@_ > 2) { # named args given
2167 ## Get the named args.
2168 (undef, %args) = @_;
2169  
2170 ## Parse the named args.
2171 foreach (keys %args) {
2172 if (/^-?binmode$/i) {
2173 $binmode = $args{$_};
2174 unless (defined $binmode) {
2175 $binmode = 0;
2176 }
2177 }
2178 elsif (/^-?errmode$/i) {
2179 $errmode = &_parse_errmode($self, $args{$_});
2180 }
2181 elsif (/^-?string$/i) {
2182 $buf = $args{$_};
2183 }
2184 elsif (/^-?telnetmode$/i) {
2185 $telnetmode = $args{$_};
2186 unless (defined $telnetmode) {
2187 $telnetmode = 0;
2188 }
2189 }
2190 elsif (/^-?timeout$/i) {
2191 $timeout = &_parse_timeout($self, $args{$_});
2192 $is_timeout_arg = 1;
2193 }
2194 else {
2195 &_croak($self, "bad named parameter \"$_\" given ",
2196 "to " . ref($self) . "::put()");
2197 }
2198 }
2199 }
2200  
2201 ## If any args given, override corresponding instance data.
2202 local $s->{bin_mode} = $binmode
2203 if defined $binmode;
2204 local $s->{errormode} = $errmode
2205 if defined $errmode;
2206 local $s->{telnet_mode} = $telnetmode
2207 if defined $telnetmode;
2208 local $s->{time_out} = $timeout
2209 if defined $is_timeout_arg;
2210  
2211 ## Check for errors.
2212 return $self->error("write error: filehandle isn't open")
2213 unless $s->{opened};
2214  
2215 ## Log the output if requested.
2216 if ($s->{outputlog}) {
2217 &_log_print($s->{outputlog}, $buf);
2218 }
2219  
2220 ## Convert native newlines to CR LF.
2221 if (!$s->{bin_mode}) {
2222 $buf =~ s(\n)(\015\012)g;
2223 }
2224  
2225 ## Escape TELNET IAC and also CR not followed by LF.
2226 if ($s->{telnet_mode}) {
2227 $buf =~ s(\377)(\377\377)g;
2228 &_escape_cr(\$buf);
2229 }
2230  
2231 &_put($self, \$buf, "put");
2232 } # end sub put
2233  
2234  
2235 ## Make rs() synonymous input_record_separator().
2236 sub rs { &input_record_separator; }
2237  
2238  
2239 sub sockfamily {
2240 my ($self) = @_;
2241 my $s = *$self->{net_telnet};
2242 my $sockfamily = "";
2243  
2244 if ($s->{sock_family} == AF_INET) {
2245 $sockfamily = "ipv4";
2246 }
2247 elsif (defined($AF_INET6) and $s->{sock_family} == $AF_INET6) {
2248 $sockfamily = "ipv6";
2249 }
2250  
2251 $sockfamily;
2252 } # end sub sockfamily
2253  
2254  
2255 sub sockhost {
2256 my ($self) = @_;
2257 my (
2258 $host,
2259 $sockaddr,
2260 );
2261 local $^W = ''; # avoid closed socket warning from getsockname()
2262  
2263 ## Get packed sockaddr struct of local side and then unpack it.
2264 $sockaddr = getsockname $self
2265 or return "";
2266 (undef, $host) = $self->_unpack_sockaddr($sockaddr);
2267  
2268 $host;
2269 } # end sub sockhost
2270  
2271  
2272 sub sockport {
2273 my ($self) = @_;
2274 my (
2275 $port,
2276 $sockaddr,
2277 );
2278 local $^W = ''; # avoid closed socket warning from getsockname()
2279  
2280 ## Get packed sockaddr struct of local side and then unpack it.
2281 $sockaddr = getsockname $self
2282 or return "";
2283 ($port) = $self->_unpack_sockaddr($sockaddr);
2284  
2285 $port;
2286 } # end sub sockport
2287  
2288  
2289 sub suboption_callback {
2290 my ($self, $callback) = @_;
2291 my (
2292 $prev,
2293 $s,
2294 );
2295  
2296 $s = *$self->{net_telnet};
2297 $prev = $s->{subopt_cback};
2298  
2299 if (@_ >= 2) {
2300 unless (defined $callback and ref($callback) eq "CODE") {
2301 &_carp($self,"ignoring Suboption_callback argument because it's " .
2302 "not a code ref");
2303 $callback = $prev;
2304 }
2305  
2306 $s->{subopt_cback} = $callback;
2307 }
2308  
2309 $prev;
2310 } # end sub suboption_callback
2311  
2312  
2313 sub telnetmode {
2314 my ($self, $mode) = @_;
2315 my (
2316 $prev,
2317 $s,
2318 );
2319  
2320 $s = *$self->{net_telnet};
2321 $prev = $s->{telnet_mode};
2322  
2323 if (@_ >= 2) {
2324 unless (defined $mode) {
2325 $mode = 0;
2326 }
2327  
2328 $s->{telnet_mode} = $mode;
2329 }
2330  
2331 $prev;
2332 } # end sub telnetmode
2333  
2334  
2335 sub timed_out {
2336 my ($self, $value) = @_;
2337 my (
2338 $prev,
2339 $s,
2340 );
2341  
2342 $s = *$self->{net_telnet};
2343 $prev = $s->{timedout};
2344  
2345 if (@_ >= 2) {
2346 unless (defined $value) {
2347 $value = "";
2348 }
2349  
2350 $s->{timedout} = $value;
2351 }
2352  
2353 $prev;
2354 } # end sub timed_out
2355  
2356  
2357 sub timeout {
2358 my ($self, $timeout) = @_;
2359 my (
2360 $prev,
2361 $s,
2362 );
2363  
2364 $s = *$self->{net_telnet};
2365 $prev = $s->{time_out};
2366  
2367 if (@_ >= 2) {
2368 $s->{time_out} = &_parse_timeout($self, $timeout);
2369 }
2370  
2371 $prev;
2372 } # end sub timeout
2373  
2374  
2375 sub waitfor {
2376 my ($self, @args) = @_;
2377 my (
2378 $arg,
2379 $binmode,
2380 $endtime,
2381 $errmode,
2382 $len,
2383 $match,
2384 $match_op,
2385 $pos,
2386 $prematch,
2387 $s,
2388 $search,
2389 $search_cond,
2390 $telnetmode,
2391 $timeout,
2392 @match_cond,
2393 @match_ops,
2394 @search_cond,
2395 @string_cond,
2396 @warns,
2397 );
2398 local $@;
2399 local $_;
2400  
2401 ## Init.
2402 $s = *$self->{net_telnet};
2403 $s->{timedout} = '';
2404 return if $s->{eofile};
2405 return unless @args;
2406 $timeout = $s->{time_out};
2407  
2408 ## Code template used to build string match conditional.
2409 ## Values between array elements must be supplied later.
2410 @string_cond =
2411 ('if (($pos = index $s->{buf}, ', ') > -1) {
2412 $len = ', ';
2413 $prematch = substr $s->{buf}, 0, $pos;
2414 $match = substr $s->{buf}, $pos, $len;
2415 substr($s->{buf}, 0, $pos + $len) = "";
2416 last;
2417 }');
2418  
2419 ## Code template used to build pattern match conditional.
2420 ## Values between array elements must be supplied later.
2421 @match_cond =
2422 ('if ($s->{buf} =~ ', ') {
2423 $prematch = $`;
2424 $match = $&;
2425 substr($s->{buf}, 0, length($`) + length($&)) = "";
2426 last;
2427 }');
2428  
2429 ## Parse args.
2430 if (@_ == 2) { # one positional arg given
2431 $arg = $_[1];
2432  
2433 ## Fill in the blanks in the code template.
2434 push @match_ops, $arg;
2435 push @search_cond, join("", $match_cond[0], $arg, $match_cond[1]);
2436 }
2437 elsif (@_ > 2) { # named args given
2438 ## Parse the named args.
2439 while (($_, $arg) = splice @args, 0, 2) {
2440 if (/^-?binmode$/i) {
2441 $binmode = $arg;
2442 unless (defined $binmode) {
2443 $binmode = 0;
2444 }
2445 }
2446 elsif (/^-?errmode$/i) {
2447 $errmode = &_parse_errmode($self, $arg);
2448 }
2449 elsif (/^-?match$/i) {
2450 ## Fill in the blanks in the code template.
2451 push @match_ops, $arg;
2452 push @search_cond, join("",
2453 $match_cond[0], $arg, $match_cond[1]);
2454 }
2455 elsif (/^-?string$/i) {
2456 ## Fill in the blanks in the code template.
2457 $arg =~ s/'/\\'/g; # quote ticks
2458 push @search_cond, join("",
2459 $string_cond[0], "'$arg'",
2460 $string_cond[1], length($arg),
2461 $string_cond[2]);
2462 }
2463 elsif (/^-?telnetmode$/i) {
2464 $telnetmode = $arg;
2465 unless (defined $telnetmode) {
2466 $telnetmode = 0;
2467 }
2468 }
2469 elsif (/^-?timeout$/i) {
2470 $timeout = &_parse_timeout($self, $arg);
2471 }
2472 else {
2473 &_croak($self, "bad named parameter \"$_\" given " .
2474 "to " . ref($self) . "::waitfor()");
2475 }
2476 }
2477 }
2478  
2479 ## If any args given, override corresponding instance data.
2480 local $s->{errormode} = $errmode
2481 if defined $errmode;
2482 local $s->{bin_mode} = $binmode
2483 if defined $binmode;
2484 local $s->{telnet_mode} = $telnetmode
2485 if defined $telnetmode;
2486  
2487 ## Check for bad match operator argument.
2488 foreach $match_op (@match_ops) {
2489 return $self->error("missing opening delimiter of match operator ",
2490 "in argument \"$match_op\" given to ",
2491 ref($self) . "::waitfor()")
2492 unless $match_op =~ m(^\s*/) or $match_op =~ m(^\s*m\s*\W);
2493 }
2494  
2495 ## Construct conditional to check for requested string and pattern matches.
2496 ## Turn subsequent "if"s into "elsif".
2497 $search_cond = join "\n\tels", @search_cond;
2498  
2499 ## Construct loop to fill buffer until string/pattern, timeout, or eof.
2500 $search = join "", "
2501 while (1) {\n\t",
2502 $search_cond, '
2503 &_fillbuf($self, $s, $endtime)
2504 or do {
2505 last if $s->{timedout};
2506 $self->close;
2507 last;
2508 };
2509 }';
2510  
2511 ## Set wall time when we timeout.
2512 $endtime = &_endtime($timeout);
2513  
2514 ## Run the loop.
2515 {
2516 local $^W = 1;
2517 local $SIG{"__WARN__"} = sub { push @warns, @_ };
2518 local $s->{errormode} = "return";
2519 $s->{errormsg} = "";
2520 eval $search;
2521 }
2522  
2523 ## Check for failure.
2524 return $self->error("pattern match timed-out") if $s->{timedout};
2525 return $self->error($s->{errormsg}) if $s->{errormsg} ne "";
2526 return $self->error("pattern match read eof") if $s->{eofile};
2527  
2528 ## Check for Perl syntax errors or warnings.
2529 if ($@ or @warns) {
2530 foreach $match_op (@match_ops) {
2531 &_match_check($self, $match_op)
2532 or return;
2533 }
2534 return $self->error($@) if $@;
2535 return $self->error(@warns) if @warns;
2536 }
2537  
2538 wantarray ? ($prematch, $match) : 1;
2539 } # end sub waitfor
2540  
2541  
2542 ######################## Private Subroutines #########################
2543  
2544  
2545 sub _append_lineno {
2546 my ($obj, @msgs) = @_;
2547 my (
2548 $file,
2549 $line,
2550 $pkg,
2551 );
2552  
2553 ## Find the caller that's not in object's class or one of its base classes.
2554 ($pkg, $file , $line) = &_user_caller($obj);
2555 join("", @msgs, " at ", $file, " line ", $line, "\n");
2556 } # end sub _append_lineno
2557  
2558  
2559 sub _carp {
2560 my ($self) = @_;
2561 my $s = *$self->{net_telnet};
2562  
2563 $s->{errormsg} = &_append_lineno(@_);
2564 warn $s->{errormsg}, "\n";
2565 } # end sub _carp
2566  
2567  
2568 sub _croak {
2569 my ($self) = @_;
2570 my $s = *$self->{net_telnet};
2571  
2572 $s->{errormsg} = &_append_lineno(@_);
2573 die $s->{errormsg}, "\n";
2574 } # end sub _croak
2575  
2576  
2577 sub _endtime {
2578 my ($interval) = @_;
2579  
2580 ## Compute wall time when timeout occurs.
2581 if (defined $interval) {
2582 if ($interval >= $^T) { # it's already an absolute time
2583 return $interval;
2584 }
2585 elsif ($interval > 0) { # it's relative to the current time
2586 return int($interval + time + 0.5);
2587 }
2588 else { # it's a one time poll
2589 return 0;
2590 }
2591 }
2592 else { # there's no timeout
2593 return undef;
2594 }
2595 } # end sub _endtime
2596  
2597  
2598 sub _errno_include {
2599 local $@;
2600 local $SIG{"__DIE__"} = "DEFAULT";
2601  
2602 eval "require Errno";
2603 } # end sub errno_include
2604  
2605  
2606 sub _escape_cr {
2607 my ($string) = @_;
2608 my (
2609 $nextchar,
2610 );
2611 my $pos = 0;
2612  
2613 ## Convert all CR (not followed by LF) to CR NULL.
2614 while (($pos = index($$string, "\015", $pos)) > -1) {
2615 $nextchar = substr $$string, $pos + 1, 1;
2616  
2617 substr($$string, $pos, 1) = "\015\000"
2618 unless $nextchar eq "\012";
2619  
2620 $pos++;
2621 }
2622  
2623 1;
2624 } # end sub _escape_cr
2625  
2626  
2627 sub _extract_arg_errmode {
2628 my ($self, $args) = @_;
2629 my (
2630 %args,
2631 );
2632 local $_;
2633 my $errmode = '';
2634  
2635 ## Check for named parameters.
2636 return '' unless @$args >= 2;
2637  
2638 ## Rebuild args without errmode parameter.
2639 %args = @$args;
2640 @$args = ();
2641  
2642 ## Extract errmode arg.
2643 foreach (keys %args) {
2644 if (/^-?errmode$/i) {
2645 $errmode = &_parse_errmode($self, $args{$_});
2646 }
2647 else {
2648 push @$args, $_, $args{$_};
2649 }
2650 }
2651  
2652 $errmode;
2653 } # end sub _extract_arg_errmode
2654  
2655  
2656 sub _fillbuf {
2657 my ($self, $s, $endtime) = @_;
2658 my (
2659 $msg,
2660 $nfound,
2661 $nread,
2662 $pushback_len,
2663 $read_pos,
2664 $ready,
2665 $timed_out,
2666 $timeout,
2667 $unparsed_pos,
2668 );
2669  
2670 ## If error from last read not yet reported then do it now.
2671 if ($s->{pending_errormsg}) {
2672 $msg = $s->{pending_errormsg};
2673 $s->{pending_errormsg} = "";
2674 return $self->error($msg);
2675 }
2676  
2677 return unless $s->{opened};
2678  
2679 while (1) {
2680 ## Maximum buffer size exceeded?
2681 return $self->error("maximum input buffer length exceeded: ",
2682 $s->{maxbufsize}, " bytes")
2683 unless length($s->{buf}) <= $s->{maxbufsize};
2684  
2685 ## Determine how long to wait for input ready.
2686 ($timed_out, $timeout) = &_timeout_interval($endtime);
2687 if ($timed_out) {
2688 $s->{timedout} = 1;
2689 return $self->error("read timed-out");
2690 }
2691  
2692 ## Wait for input ready.
2693 $nfound = select $ready=$s->{fdmask}, "", "", $timeout;
2694  
2695 ## Handle any errors while waiting.
2696 if ((!defined $nfound or $nfound <= 0) and $s->{select_supported}) {
2697 if (defined $nfound and $nfound == 0) { # timed-out
2698 $s->{timedout} = 1;
2699 return $self->error("read timed-out");
2700 }
2701 else { # error waiting for input ready
2702 if (defined $EINTR) {
2703 next if $! == $EINTR; # restart select()
2704 }
2705 else {
2706 next if $! =~ /^interrupted/i; # restart select()
2707 }
2708  
2709 $s->{opened} = '';
2710 return $self->error("read error: $!");
2711 }
2712 }
2713  
2714 ## Append to buffer any partially processed telnet or CR sequence.
2715 $pushback_len = length $s->{pushback_buf};
2716 if ($pushback_len) {
2717 $s->{buf} .= $s->{pushback_buf};
2718 $s->{pushback_buf} = "";
2719 }
2720  
2721 ## Read the waiting data.
2722 $read_pos = length $s->{buf};
2723 $unparsed_pos = $read_pos - $pushback_len;
2724 $nread = sysread $self, $s->{buf}, $s->{blksize}, $read_pos;
2725  
2726 # Modified section to handle MCCP2 and MCCP1 ##############################################
2727 if ($nread && ($s->{opts}{86}{remote_enabled} || $s->{opts}{85}{remote_enabled})) {
2728  
2729 my ($buff, $zlibObj, $status, $posn, $previousBuff, $output, $spare, $sparePosn);
2730  
2731 $buff = $s->{buf};
2732  
2733 if (! $s->{axmud_mccp_mode}) {
2734  
2735 ($zlibObj, $status) = Compress::Zlib::inflateInit();
2736 if (! defined $zlibObj) {
2737  
2738 $self->error("failed to initiate zlib compression stream");
2739 &_disable_mccp($self, 1);
2740 $s->{axmud_session}->set_mccpMode('compress_error');
2741  
2742 } else {
2743  
2744 $s->{axmud_zlib_obj} = $zlibObj;
2745 $s->{axmud_mccp_mode} = 1;
2746 $s->{axmud_session}->set_mccpMode('client_agree');
2747 }
2748 }
2749  
2750 if ($s->{axmud_mccp_mode} == 1) {
2751  
2752 # Wait for IAC SB MCCP IAC SE (MCCP2), or IAC SB 85 WILL SE (MCCP1)
2753 $posn = index($buff, chr(255) . chr(250) . chr(85) . chr(251) . chr(240));
2754 if ($posn == -1) {
2755  
2756 $posn = index($buff, chr(255) . chr(250) . chr(86) . chr(255) . chr(240));
2757 }
2758  
2759 if ($posn > -1) {
2760  
2761 # IAC SB MCCP IAC SE (or IAC SB 85 WILL SE) received
2762 $s->{axmud_mccp_mode} = 2;
2763 # For MCCP1, the IAC SB 85 WILL SE is broken, and won't cause
2764 # Games::Axmud::Session->subOptCallback to be called in the normal way, so
2765 # here we have to call it artificially, pretending that a IAC SB 85 IAC SE
2766 # sequence was received
2767 if ($s->{opts}{85}{remote_enabled}) {
2768  
2769 $s->{axmud_session}->subOptCallback($self, 85, '');
2770 }
2771 }
2772 }
2773  
2774 if ($s->{axmud_mccp_mode} >= 2 && $pushback_len) {
2775  
2776 # If any partially processed telnet or CR sequence was appended to the buffer,
2777 # don't inflate that portion
2778 $previousBuff = substr($buff, 0, $pushback_len);
2779 $buff = substr($buff, $pushback_len);
2780 }
2781  
2782 if ($buff && $s->{axmud_mccp_mode} >= 2) {
2783  
2784 if ($s->{axmud_mccp_mode} == 2) {
2785  
2786 # First inflation attempt. In case the packet contains IAC SB MCCP IAC SE (or
2787 # IAC SB 85 WILL SE) followed immediately by the zlib stream, we must only
2788 # inflate the zlib stream itself
2789 $sparePosn = index($buff, chr(255) . chr(250) . chr(85) . chr(251) . chr(240));
2790 if ($sparePosn == -1) {
2791  
2792 $sparePosn
2793 = index($buff, chr(255) . chr(250) . chr(86) . chr(255) . chr(240));
2794 }
2795  
2796 if ($sparePosn > -1) {
2797  
2798 $spare = substr($buff, 0, ($sparePosn + 5));
2799 $buff = substr($buff, ($sparePosn + 5));
2800 ($output, $status) = $s->{axmud_zlib_obj}->inflate($buff);
2801 $output = $spare . $output;
2802  
2803 } else {
2804  
2805 ($output, $status) = $s->{axmud_zlib_obj}->inflate($buff);
2806 }
2807  
2808 } else {
2809  
2810 # Subsequent inflation attempts
2811 ($output, $status) = $s->{axmud_zlib_obj}->inflate($buff);
2812 }
2813  
2814 if ($status == Z_STREAM_END) {
2815  
2816 # End of zlib compression stream. Don't inflate anything after this point
2817 &_disable_mccp($self, 0);
2818 $s->{axmud_session}->set_mccpMode('compress_stop');
2819  
2820 # Re-attach anything that appeared after the end of the data stream
2821 if (defined $previousBuff) {
2822 $s->{buf} = $previousBuff . $output . $buff;
2823 } else {
2824 $s->{buf} = $output . $buff;
2825 }
2826  
2827 $nread = length ($output . $buff);
2828  
2829 } elsif ($status != Z_OK) {
2830  
2831 $self->error("zlib compression failed, disabling MCCP");
2832 &_disable_mccp($self, 1);
2833 $s->{axmud_session}->set_mccpMode('compress_error');
2834  
2835 } else {
2836  
2837 if ($s->{axmud_mccp_mode} == 2) {
2838  
2839 # First successful inflation
2840 $s->{axmud_mccp_mode} = 3;
2841 }
2842  
2843 # Inflation successful
2844 if (defined $previousBuff) {
2845 $s->{buf} = $previousBuff . $output;
2846 } else {
2847 $s->{buf} = $output;
2848 }
2849  
2850 $nread = length ($output);
2851 }
2852 }
2853 }
2854  
2855 # #########################################################################################
2856  
2857 ## Handle any read errors.
2858 if (!defined $nread) { # read failed
2859 if (defined $EINTR) {
2860 next if $! == $EINTR; # restart sysread()
2861 }
2862 else {
2863 next if $! =~ /^interrupted/i; # restart sysread()
2864 }
2865  
2866 $s->{opened} = '';
2867 return $self->error("read error: $!");
2868 }
2869  
2870 ## Handle eof.
2871 if ($nread == 0) { # eof read
2872 $s->{opened} = '';
2873 return;
2874 }
2875  
2876 ## Display network traffic if requested.
2877 if ($s->{dumplog}) {
2878 &_log_dump('<', $s->{dumplog}, \$s->{buf}, $read_pos);
2879 }
2880  
2881 ## Process any telnet commands in the data stream.
2882 if ($s->{telnet_mode} and index($s->{buf},"\377",$unparsed_pos) > -1) {
2883 &_interpret_tcmd($self, $s, $unparsed_pos);
2884 }
2885  
2886 ## Process any carriage-return sequences in the data stream.
2887 &_interpret_cr($s, $unparsed_pos);
2888  
2889 ## Read again if all chars read were consumed as telnet cmds.
2890 next if $unparsed_pos >= length $s->{buf};
2891  
2892 ## Log the input if requested.
2893 if ($s->{inputlog}) {
2894 &_log_print($s->{inputlog}, substr($s->{buf}, $unparsed_pos));
2895 }
2896  
2897 ## Save the last line read.
2898 &_save_lastline($s);
2899  
2900 ## We've successfully read some data into the buffer.
2901 last;
2902 } # end while(1)
2903  
2904 1;
2905 } # end sub _fillbuf
2906  
2907  
2908 sub _disable_mccp {
2909 my ($self, $flag) = @_;
2910 my $s = *$self->{net_telnet};
2911  
2912 if ($flag) {
2913  
2914 # Must send IAC DONT MCCP
2915 my $telCmd;
2916  
2917 if ($s->{opts}{86}{remote_enabled}) {
2918 $telCmd = pack("C*", &TELNET_IAC, &TELNET_DONT, 86);
2919 } else {
2920 $telCmd = pack("C*", &TELNET_IAC, &TELNET_DONT, 85);
2921 }
2922  
2923 $self->put(
2924 String => $telCmd,
2925 Telnetmode => 0,
2926 );
2927 }
2928  
2929 $s->{axmud_mccp_mode} = 0;
2930 $s->{axmud_zlib_obj} = '';
2931 $s->{opts}{85}{remote_enabled} = '';
2932 $s->{opts}{85}{remote_state} = 'no';
2933 $s->{opts}{85}{local_enabled} = '';
2934 $s->{opts}{85}{local_state} = 'no';
2935 $s->{opts}{86}{remote_enabled} = '';
2936 $s->{opts}{86}{remote_state} = 'no';
2937 $s->{opts}{86}{local_enabled} = '';
2938 $s->{opts}{86}{local_state} = 'no';
2939  
2940 1;
2941 } # end sub _disable_mccp
2942  
2943  
2944 sub _flush_opts {
2945 my ($self) = @_;
2946 my (
2947 $option_chars,
2948 );
2949 my $s = *$self->{net_telnet};
2950  
2951 ## Get option and clear the output buf.
2952 $option_chars = $s->{unsent_opts};
2953 $s->{unsent_opts} = "";
2954  
2955 ## Try to send options without waiting.
2956 {
2957 local $s->{errormode} = "return";
2958 local $s->{time_out} = 0;
2959 &_put($self, \$option_chars, "telnet option negotiation")
2960 or do {
2961 ## Save chars not printed for later.
2962 substr($option_chars, 0, $self->print_length) = "";
2963 $s->{unsent_opts} .= $option_chars;
2964 };
2965 }
2966  
2967 1;
2968 } # end sub _flush_opts
2969  
2970  
2971 sub _fname_to_handle {
2972 my ($self, $filename) = @_;
2973 my (
2974 $fh,
2975 );
2976 no strict "refs";
2977  
2978 $fh = &_new_handle();
2979 CORE::open $fh, "> $filename"
2980 or return $self->error("problem creating $filename: $!");
2981  
2982 $fh;
2983 } # end sub _fname_to_handle
2984  
2985  
2986 sub _have_alarm {
2987 local $@;
2988  
2989 eval {
2990 local $SIG{"__DIE__"} = "DEFAULT";
2991 local $SIG{ALRM} = sub { die };
2992 alarm 0;
2993 };
2994  
2995 ! $@;
2996 } # end sub _have_alarm
2997  
2998  
2999 sub _import_af_inet6 {
3000 local $@;
3001  
3002 eval {
3003 local $SIG{"__DIE__"} = "DEFAULT";
3004  
3005 Socket::AF_INET6();
3006 };
3007 } # end sub _import_af_inet6
3008  
3009  
3010 sub _import_af_unspec {
3011 local $@;
3012  
3013 eval {
3014 local $SIG{"__DIE__"} = "DEFAULT";
3015  
3016 Socket::AF_UNSPEC();
3017 };
3018 } # end sub _import_af_unspec
3019  
3020  
3021 sub _import_ai_addrconfig {
3022 local $@;
3023  
3024 eval {
3025 local $SIG{"__DIE__"} = "DEFAULT";
3026  
3027 Socket::AI_ADDRCONFIG();
3028 };
3029 } # end sub _import_ai_addrconfig
3030  
3031  
3032 sub _import_eai_badflags {
3033 local $@;
3034  
3035 eval {
3036 local $SIG{"__DIE__"} = "DEFAULT";
3037  
3038 Socket::EAI_BADFLAGS();
3039 };
3040 } # end sub _import_eai_badflags
3041  
3042  
3043 sub _import_eintr {
3044 local $@;
3045 local $SIG{"__DIE__"} = "DEFAULT";
3046  
3047 eval "require Errno; Errno::EINTR();";
3048 } # end sub _import_eintr
3049  
3050  
3051 sub _interpret_cr {
3052 my ($s, $pos) = @_;
3053 my (
3054 $nextchar,
3055 );
3056  
3057 while (($pos = index($s->{buf}, "\015", $pos)) > -1) {
3058 $nextchar = substr($s->{buf}, $pos + 1, 1);
3059 if ($nextchar eq "\0") {
3060 ## Convert CR NULL to CR when in telnet mode.
3061 if ($s->{telnet_mode}) {
3062 substr($s->{buf}, $pos + 1, 1) = "";
3063 }
3064 }
3065 elsif ($nextchar eq "\012") {
3066 ## Convert CR LF to newline when not in binary mode.
3067 if (!$s->{bin_mode}) {
3068 substr($s->{buf}, $pos, 2) = "\n";
3069 }
3070 }
3071 elsif (!length($nextchar) and ($s->{telnet_mode} or !$s->{bin_mode})) {
3072 ## Save CR in alt buffer for possible CR LF or CR NULL conversion.
3073 $s->{pushback_buf} .= "\015";
3074 chop $s->{buf};
3075 }
3076  
3077 $pos++;
3078 }
3079  
3080 1;
3081 } # end sub _interpret_cr
3082  
3083  
3084 sub _interpret_tcmd {
3085 my ($self, $s, $offset) = @_;
3086 my (
3087 $callback,
3088 $endpos,
3089 $nextchar,
3090 $option,
3091 $parameters,
3092 $pos,
3093 $subcmd,
3094 );
3095 local $_;
3096  
3097 ## Parse telnet commands in the data stream.
3098 $pos = $offset;
3099 while (($pos = index $s->{buf}, "\377", $pos) > -1) { # unprocessed IAC
3100 $nextchar = substr $s->{buf}, $pos + 1, 1;
3101  
3102 ## Save command if it's only partially read.
3103 if (!length $nextchar) {
3104 $s->{pushback_buf} .= "\377";
3105 chop $s->{buf};
3106 last;
3107 }
3108  
3109 if ($nextchar eq "\377") { # IAC is escaping "\377" char
3110 ## Remove escape char from data stream.
3111 substr($s->{buf}, $pos, 1) = "";
3112 $pos++;
3113 }
3114 elsif ($nextchar eq "\375" or $nextchar eq "\373" or
3115 $nextchar eq "\374" or $nextchar eq "\376") { # opt negotiation
3116 $option = substr $s->{buf}, $pos + 2, 1;
3117  
3118 ## Save command if it's only partially read.
3119 if (!length $option) {
3120 $s->{pushback_buf} .= "\377" . $nextchar;
3121 chop $s->{buf};
3122 chop $s->{buf};
3123 last;
3124 }
3125  
3126 ## Remove command from data stream.
3127 substr($s->{buf}, $pos, 3) = "";
3128  
3129 ## Handle option negotiation.
3130 &_negotiate_recv($self, $s, $nextchar, ord($option), $pos);
3131 }
3132 elsif ($nextchar eq "\372") { # start of subnegotiation parameters
3133 ## Save command if it's only partially read.
3134 $endpos = index $s->{buf}, "\360", $pos;
3135 if ($endpos == -1) {
3136 $s->{pushback_buf} .= substr $s->{buf}, $pos;
3137 substr($s->{buf}, $pos) = "";
3138 last;
3139 }
3140  
3141 ## Remove subnegotiation cmd from buffer.
3142 $subcmd = substr($s->{buf}, $pos, $endpos - $pos + 1);
3143 substr($s->{buf}, $pos, $endpos - $pos + 1) = "";
3144  
3145 ## Invoke subnegotiation callback.
3146 if ($s->{subopt_cback} and length($subcmd) >= 5) {
3147 $option = unpack "C", substr($subcmd, 2, 1);
3148 if (length($subcmd) >= 6) {
3149 $parameters = substr $subcmd, 3, length($subcmd) - 5;
3150 }
3151 else {
3152 $parameters = "";
3153 }
3154  
3155 $callback = $s->{subopt_cback};
3156 &$callback($self, $option, $parameters);
3157 }
3158 }
3159 elsif ($nextchar eq "\371") {
3160 ## Don't remove IAC GA from the data stream; let GA::Session deal with it
3161 $pos += 2;
3162 }
3163 else { # various two char telnet commands
3164 ## Ignore and remove command from data stream.
3165 substr($s->{buf}, $pos, 2) = "";
3166 }
3167 }
3168  
3169 ## Try to send any waiting option negotiation.
3170 if (length $s->{unsent_opts}) {
3171 &_flush_opts($self);
3172 }
3173  
3174 1;
3175 } # end sub _interpret_tcmd
3176  
3177  
3178 sub _io_socket_include {
3179 local $@;
3180 local $SIG{"__DIE__"} = "DEFAULT";
3181  
3182 eval "require IO::Socket";
3183 } # end sub io_socket_include
3184  
3185  
3186 sub _is_open_fh {
3187 my ($fh) = @_;
3188 my $is_open = '';
3189 local $@;
3190  
3191 eval {
3192 local $SIG{"__DIE__"} = "DEFAULT";
3193 $is_open = defined(fileno $fh);
3194 };
3195  
3196 $is_open;
3197 } # end sub _is_open_fh
3198  
3199  
3200 sub _log_dump {
3201 my ($direction, $fh, $data, $offset, $len) = @_;
3202 my (
3203 $addr,
3204 $hexvals,
3205 $line,
3206 );
3207  
3208 $addr = 0;
3209 $len = length($$data) - $offset
3210 if !defined $len;
3211 return 1 if $len <= 0;
3212  
3213 ## Print data in dump format.
3214 while ($len > 0) {
3215 ## Convert up to the next 16 chars to hex, padding w/ spaces.
3216 if ($len >= 16) {
3217 $line = substr $$data, $offset, 16;
3218 }
3219 else {
3220 $line = substr $$data, $offset, $len;
3221 }
3222 $hexvals = unpack("H*", $line);
3223 $hexvals .= ' ' x (32 - length $hexvals);
3224  
3225 ## Place in 16 columns, each containing two hex digits.
3226 $hexvals = sprintf("%s %s %s %s " x 4,
3227 unpack("a2" x 16, $hexvals));
3228  
3229 ## For the ASCII column, change unprintable chars to a period.
3230 $line =~ s/[\000-\037,\177-\237]/./g;
3231  
3232 ## Print the line in dump format.
3233 &_log_print($fh, sprintf("%s 0x%5.5lx: %s%s\n",
3234 $direction, $addr, $hexvals, $line));
3235  
3236 $addr += 16;
3237 $offset += 16;
3238 $len -= 16;
3239 }
3240  
3241 &_log_print($fh, "\n");
3242  
3243 1;
3244 } # end sub _log_dump
3245  
3246  
3247 sub _log_option {
3248 my ($fh, $direction, $request, $option) = @_;
3249 my (
3250 $name,
3251 );
3252  
3253 if ($option >= 0 and $option <= $#Telopts) {
3254 $name = $Telopts[$option];
3255 } elsif (exists $Axmud_Telopts{$option}) {
3256 $name = $Axmud_Telopts{$option};
3257 } else {
3258 $name = $option;
3259 }
3260  
3261 &_log_print($fh, "$direction $request $name\n");
3262 } # end sub _log_option
3263  
3264  
3265 sub _log_print {
3266 my ($fh, $buf) = @_;
3267 local $\ = '';
3268  
3269 if (ref($fh) eq "GLOB") { # fh is GLOB ref
3270 print $fh $buf;
3271 }
3272 else { # fh isn't GLOB ref
3273 $fh->print($buf);
3274 }
3275 } # end sub _log_print
3276  
3277  
3278 sub _match_check {
3279 my ($self, $code) = @_;
3280 my $error;
3281 my @warns = ();
3282 local $@;
3283  
3284 ## Use eval to check for syntax errors or warnings.
3285 {
3286 local $SIG{"__DIE__"} = "DEFAULT";
3287 local $SIG{"__WARN__"} = sub { push @warns, @_ };
3288 local $^W = 1;
3289 local $_ = '';
3290 eval "\$_ =~ $code;";
3291 }
3292 if ($@) {
3293 ## Remove useless lines numbers from message.
3294 ($error = $@) =~ s/ at \(eval \d+\) line \d+.?//;
3295 chomp $error;
3296 return $self->error("bad match operator: $error");
3297 }
3298 elsif (@warns) {
3299 ## Remove useless lines numbers from message.
3300 ($error = shift @warns) =~ s/ at \(eval \d+\) line \d+.?//;
3301 $error =~ s/ while "strict subs" in use//;
3302 chomp $error;
3303 return $self->error("bad match operator: $error");
3304 }
3305  
3306 1;
3307 } # end sub _match_check
3308  
3309  
3310 sub _negotiate_callback {
3311 my ($self, $opt, $is_remote, $is_enabled, $was_enabled, $opt_bufpos) = @_;
3312 my (
3313 $callback,
3314 $s,
3315 );
3316 local $_;
3317  
3318 ## Keep track of remote echo.
3319 if ($is_remote and $opt == &TELOPT_ECHO) { # received WILL or WONT ECHO
3320 $s = *$self->{net_telnet};
3321  
3322 if ($is_enabled and !$was_enabled) { # received WILL ECHO
3323 $s->{remote_echo} = 1;
3324 }
3325 elsif (!$is_enabled and $was_enabled) { # received WONT ECHO
3326 $s->{remote_echo} = '';
3327 }
3328 }
3329  
3330 ## Invoke callback, if there is one.
3331 $callback = $self->option_callback;
3332 if ($callback) {
3333 &$callback($self, $opt, $is_remote,
3334 $is_enabled, $was_enabled, $opt_bufpos);
3335 }
3336  
3337 1;
3338 } # end sub _negotiate_callback
3339  
3340  
3341 sub _negotiate_recv {
3342 my ($self, $s, $opt_request, $opt, $opt_bufpos) = @_;
3343  
3344 ## Ensure data structure exists for this option.
3345 unless (defined $s->{opts}{$opt}) {
3346 &_set_default_option($s, $opt);
3347 }
3348  
3349 ## Process the option.
3350 if ($opt_request eq "\376") { # DONT
3351 &_negotiate_recv_disable($self, $s, $opt, "dont", $opt_bufpos,
3352 $s->{opts}{$opt}{local_enable_ok},
3353 \$s->{opts}{$opt}{local_enabled},
3354 \$s->{opts}{$opt}{local_state});
3355 }
3356 elsif ($opt_request eq "\375") { # DO
3357 &_negotiate_recv_enable($self, $s, $opt, "do", $opt_bufpos,
3358 $s->{opts}{$opt}{local_enable_ok},
3359 \$s->{opts}{$opt}{local_enabled},
3360 \$s->{opts}{$opt}{local_state});
3361 }
3362 elsif ($opt_request eq "\374") { # WONT
3363 &_negotiate_recv_disable($self, $s, $opt, "wont", $opt_bufpos,
3364 $s->{opts}{$opt}{remote_enable_ok},
3365 \$s->{opts}{$opt}{remote_enabled},
3366 \$s->{opts}{$opt}{remote_state});
3367 }
3368 elsif ($opt_request eq "\373") { # WILL
3369 &_negotiate_recv_enable($self, $s, $opt, "will", $opt_bufpos,
3370 $s->{opts}{$opt}{remote_enable_ok},
3371 \$s->{opts}{$opt}{remote_enabled},
3372 \$s->{opts}{$opt}{remote_state});
3373 }
3374 else { # internal error
3375 die;
3376 }
3377  
3378 1;
3379 } # end sub _negotiate_recv
3380  
3381  
3382 sub _negotiate_recv_disable {
3383 my ($self, $s, $opt, $opt_request,
3384 $opt_bufpos, $enable_ok, $is_enabled, $state) = @_;
3385 my (
3386 $ack,
3387 $disable_cmd,
3388 $enable_cmd,
3389 $is_remote,
3390 $nak,
3391 $was_enabled,
3392 );
3393  
3394 # Axmud v1.0.696 - $$state is sometimes 'undef', for some reason, and this causes an error
3395 if (! defined $$state) {
3396  
3397 $$state = '';
3398 }
3399  
3400 ## What do we use to request enable/disable or respond with ack/nak.
3401 if ($opt_request eq "wont") {
3402 $enable_cmd = "\377\375" . pack("C", $opt); # do command
3403 $disable_cmd = "\377\376" . pack("C", $opt); # dont command
3404 $is_remote = 1;
3405 $ack = "DO";
3406 $nak = "DONT";
3407  
3408 &_log_option($s->{opt_log}, "RCVD", "WONT", $opt)
3409 if $s->{opt_log};
3410 }
3411 elsif ($opt_request eq "dont") {
3412 $enable_cmd = "\377\373" . pack("C", $opt); # will command
3413 $disable_cmd = "\377\374" . pack("C", $opt); # wont command
3414 $is_remote = '';
3415 $ack = "WILL";
3416 $nak = "WONT";
3417  
3418 &_log_option($s->{opt_log}, "RCVD", "DONT", $opt)
3419 if $s->{opt_log};
3420 }
3421 else { # internal error
3422 die;
3423 }
3424  
3425 ## Respond to WONT or DONT based on the current negotiation state.
3426 if ($$state eq "no") { # state is already disabled
3427 }
3428 elsif ($$state eq "yes") { # they're initiating disable
3429 $$is_enabled = '';
3430 $$state = "no";
3431  
3432 ## Send positive acknowledgment.
3433 $s->{unsent_opts} .= $disable_cmd;
3434 &_log_option($s->{opt_log}, "SENT", $nak, $opt)
3435 if $s->{opt_log};
3436  
3437 ## Invoke callbacks.
3438 &_negotiate_callback($self, $opt, $is_remote,
3439 $$is_enabled, $was_enabled, $opt_bufpos);
3440 }
3441 elsif ($$state eq "wantno") { # they sent positive ack
3442 $$is_enabled = '';
3443 $$state = "no";
3444  
3445 ## Invoke callback.
3446 &_negotiate_callback($self, $opt, $is_remote,
3447 $$is_enabled, $was_enabled, $opt_bufpos);
3448 }
3449 elsif ($$state eq "wantno opposite") { # pos ack but we changed our mind
3450 ## Indicate disabled but now we want to enable.
3451 $$is_enabled = '';
3452 $$state = "wantyes";
3453  
3454 ## Send queued request.
3455 $s->{unsent_opts} .= $enable_cmd;
3456 &_log_option($s->{opt_log}, "SENT", $ack, $opt)
3457 if $s->{opt_log};
3458  
3459 ## Invoke callback.
3460 &_negotiate_callback($self, $opt, $is_remote,
3461 $$is_enabled, $was_enabled, $opt_bufpos);
3462 }
3463 elsif ($$state eq "wantyes") { # they sent negative ack
3464 $$is_enabled = '';
3465 $$state = "no";
3466  
3467 ## Invoke callback.
3468 &_negotiate_callback($self, $opt, $is_remote,
3469 $$is_enabled, $was_enabled, $opt_bufpos);
3470 }
3471 elsif ($$state eq "wantyes opposite") { # nak but we changed our mind
3472 $$is_enabled = '';
3473 $$state = "no";
3474  
3475 ## Invoke callback.
3476 &_negotiate_callback($self, $opt, $is_remote,
3477 $$is_enabled, $was_enabled, $opt_bufpos);
3478 }
3479 } # end sub _negotiate_recv_disable
3480  
3481  
3482 sub _negotiate_recv_enable {
3483 my ($self, $s, $opt, $opt_request,
3484 $opt_bufpos, $enable_ok, $is_enabled, $state) = @_;
3485 my (
3486 $ack,
3487 $disable_cmd,
3488 $enable_cmd,
3489 $is_remote,
3490 $nak,
3491 $was_enabled,
3492 );
3493  
3494 # Axmud v1.0.696 - $$state is sometimes 'undef', for some reason, and this causes an error
3495 if (! defined $$state) {
3496  
3497 $$state = '';
3498 }
3499  
3500 ## What we use to send enable/disable request or send ack/nak response.
3501 if ($opt_request eq "will") {
3502 $enable_cmd = "\377\375" . pack("C", $opt); # do command
3503 $disable_cmd = "\377\376" . pack("C", $opt); # dont command
3504 $is_remote = 1;
3505 $ack = "DO";
3506 $nak = "DONT";
3507  
3508 &_log_option($s->{opt_log}, "RCVD", "WILL", $opt)
3509 if $s->{opt_log};
3510 }
3511 elsif ($opt_request eq "do") {
3512 $enable_cmd = "\377\373" . pack("C", $opt); # will command
3513 $disable_cmd = "\377\374" . pack("C", $opt); # wont command
3514 $is_remote = '';
3515 $ack = "WILL";
3516 $nak = "WONT";
3517  
3518 &_log_option($s->{opt_log}, "RCVD", "DO", $opt)
3519 if $s->{opt_log};
3520 }
3521 else { # internal error
3522 die;
3523 }
3524  
3525 ## Save current enabled state.
3526 $was_enabled = $$is_enabled;
3527  
3528 ## Respond to WILL or DO based on the current negotiation state.
3529 if ($$state eq "no") { # they're initiating enable
3530 if ($enable_ok) { # we agree they/us should enable
3531 $$is_enabled = 1;
3532 $$state = "yes";
3533  
3534 ## Send positive acknowledgment.
3535 $s->{unsent_opts} .= $enable_cmd;
3536 &_log_option($s->{opt_log}, "SENT", $ack, $opt)
3537 if $s->{opt_log};
3538  
3539 ## Invoke callbacks.
3540 &_negotiate_callback($self, $opt, $is_remote,
3541 $$is_enabled, $was_enabled, $opt_bufpos);
3542 }
3543 else { # we disagree they/us should enable
3544 ## Send negative acknowledgment.
3545 $s->{unsent_opts} .= $disable_cmd;
3546 &_log_option($s->{opt_log}, "SENT", $nak, $opt)
3547 if $s->{opt_log};
3548 }
3549 }
3550 elsif ($$state eq "yes") { # state is already enabled
3551 }
3552 elsif ($$state eq "wantno") { # error: our disable req answered by enable
3553 $$is_enabled = '';
3554 $$state = "no";
3555  
3556 ## Invoke callbacks.
3557 &_negotiate_callback($self, $opt, $is_remote,
3558 $$is_enabled, $was_enabled, $opt_bufpos);
3559 }
3560 elsif ($$state eq "wantno opposite") { # err: disable req answerd by enable
3561 $$is_enabled = 1;
3562 $$state = "yes";
3563  
3564 ## Invoke callbacks.
3565 &_negotiate_callback($self, $opt, $is_remote,
3566 $$is_enabled, $was_enabled, $opt_bufpos);
3567 }
3568 elsif ($$state eq "wantyes") { # they sent pos ack
3569 $$is_enabled = 1;
3570 $$state = "yes";
3571  
3572 ## Invoke callback.
3573 &_negotiate_callback($self, $opt, $is_remote,
3574 $$is_enabled, $was_enabled, $opt_bufpos);
3575 }
3576 elsif ($$state eq "wantyes opposite") { # pos ack but we changed our mind
3577 ## Indicate enabled but now we want to disable.
3578 $$is_enabled = 1;
3579 $$state = "wantno";
3580  
3581 ## Inform other side we changed our mind.
3582 $s->{unsent_opts} .= $disable_cmd;
3583 &_log_option($s->{opt_log}, "SENT", $nak, $opt)
3584 if $s->{opt_log};
3585  
3586 ## Invoke callback.
3587 &_negotiate_callback($self, $opt, $is_remote,
3588 $$is_enabled, $was_enabled, $opt_bufpos);
3589 }
3590  
3591 1;
3592 } # end sub _negotiate_recv_enable
3593  
3594  
3595 sub _new_handle {
3596 if ($INC{"IO/Handle.pm"}) {
3597 return IO::Handle->new;
3598 }
3599 else {
3600 require FileHandle;
3601 return FileHandle->new;
3602 }
3603 } # end sub _new_handle
3604  
3605  
3606 sub _next_getlines {
3607 my ($self, $s) = @_;
3608 my (
3609 $len,
3610 $line,
3611 $pos,
3612 @lines,
3613 );
3614  
3615 ## Fill buffer and get first line.
3616 $line = $self->getline
3617 or return;
3618 push @lines, $line;
3619  
3620 ## Extract subsequent lines from buffer.
3621 while (($pos = index($s->{buf}, $s->{"rs"})) != -1) {
3622 $len = $pos + length $s->{"rs"};
3623 push @lines, substr($s->{buf}, 0, $len);
3624 substr($s->{buf}, 0, $len) = "";
3625 }
3626  
3627 @lines;
3628 } # end sub _next_getlines
3629  
3630  
3631 sub _opt_accept {
3632 my ($self, @args) = @_;
3633 my (
3634 $arg,
3635 $option,
3636 $s,
3637 );
3638  
3639 ## Init.
3640 $s = *$self->{net_telnet};
3641  
3642 foreach $arg (@args) {
3643 ## Ensure data structure defined for this option.
3644 $option = $arg->{option};
3645 if (!defined $s->{opts}{$option}) {
3646 &_set_default_option($s, $option);
3647 }
3648  
3649 ## Save whether we'll accept or reject this option.
3650 if ($arg->{is_remote}) {
3651 $s->{opts}{$option}{remote_enable_ok} = $arg->{is_enable};
3652 }
3653 else {
3654 $s->{opts}{$option}{local_enable_ok} = $arg->{is_enable};
3655 }
3656 }
3657  
3658 1;
3659 } # end sub _opt_accept
3660  
3661  
3662 sub _optimal_blksize {
3663 my ($blksize) = @_;
3664  
3665 ## Use default when block size is invalid.
3666 if (!defined $blksize or $blksize eq "" or $blksize < 512 or $blksize > 1_048_576) {
3667 $blksize = 4096;
3668 }
3669  
3670 $blksize;
3671 } # end sub _optimal_blksize
3672  
3673  
3674 sub _parse_cmd_remove_mode {
3675 my ($self, $mode) = @_;
3676  
3677 if (!defined $mode) {
3678 $mode = 0;
3679 }
3680 elsif ($mode =~ /^\s*auto\s*$/i) {
3681 $mode = "auto";
3682 }
3683 elsif ($mode !~ /^\d+$/) {
3684 &_carp($self, "ignoring bad Cmd_remove_mode " .
3685 "argument \"$mode\": it's not \"auto\" or a " .
3686 "non-negative integer");
3687 $mode = *$self->{net_telnet}{cmd_rm_mode};
3688 }
3689  
3690 $mode;
3691 } # end sub _parse_cmd_remove_mode
3692  
3693  
3694 sub _parse_errmode {
3695 my ($self, $errmode) = @_;
3696  
3697 ## Set the error mode.
3698 if (!defined $errmode) {
3699 &_carp($self, "ignoring undefined Errmode argument");
3700 $errmode = *$self->{net_telnet}{errormode};
3701 }
3702 elsif ($errmode =~ /^\s*return\s*$/i) {
3703 $errmode = "return";
3704 }
3705 elsif ($errmode =~ /^\s*die\s*$/i) {
3706 $errmode = "die";
3707 }
3708 elsif (ref($errmode) eq "CODE") {
3709 }
3710 elsif (ref($errmode) eq "ARRAY") {
3711 unless (ref($errmode->[0]) eq "CODE") {
3712 &_carp($self, "ignoring bad Errmode argument: " .
3713 "first list item isn't a code ref");
3714 $errmode = *$self->{net_telnet}{errormode};
3715 }
3716 }
3717 else {
3718 &_carp($self, "ignoring bad Errmode argument \"$errmode\"");
3719 $errmode = *$self->{net_telnet}{errormode};
3720 }
3721  
3722 $errmode;
3723 } # end sub _parse_errmode
3724  
3725  
3726 sub _parse_family {
3727 my ($self, $family) = @_;
3728 my (
3729 $parsed_family,
3730 $socket_version,
3731 );
3732  
3733 $socket_version = $Socket::VERSION; # replace '2.020_03' with '2.020'
3734 $socket_version =~ s/\_.*$//;
3735  
3736 unless (defined $family) {
3737 $family = "";
3738 }
3739  
3740 if ($family =~ /^\s*ipv4\s*$/i) { # family arg is "ipv4"
3741 $parsed_family = "ipv4";
3742 }
3743 elsif ($family =~ /^\s*any\s*$/i) { # family arg is "any"
3744 if ($socket_version >= 1.94 and defined $AF_INET6) { # has IPv6
3745 $parsed_family = "any";
3746 }
3747 else { # IPv6 not supported on this machine
3748 $parsed_family = "ipv4";
3749 }
3750 }
3751 elsif ($family =~ /^\s*ipv6\s*$/i) { # family arg is "ipv6"
3752 return $self->error("Family arg ipv6 not supported when " .
3753 "Socket.pm version < 1.94")
3754 unless $socket_version >= 1.94;
3755 return $self->error("Family arg ipv6 not supported by " .
3756 "this OS: AF_INET6 not in Socket.pm")
3757 unless defined $AF_INET6;
3758  
3759 $parsed_family = "ipv6";
3760 }
3761 else {
3762 return $self->error("bad Family argument \"$family\": " .
3763 "must be \"ipv4\", \"ipv6\", or \"any\"");
3764 }
3765  
3766 $parsed_family;
3767 } # end sub _parse_family
3768  
3769  
3770 sub _parse_input_record_separator {
3771 my ($self, $rs) = @_;
3772  
3773 unless (defined $rs and length $rs) {
3774 &_carp($self, "ignoring null Input_record_separator argument");
3775 $rs = *$self->{net_telnet}{"rs"};
3776 }
3777  
3778 $rs;
3779 } # end sub _parse_input_record_separator
3780  
3781  
3782 sub _parse_localfamily {
3783 my ($self, $family) = @_;
3784 my (
3785 $socket_version,
3786 );
3787  
3788 $socket_version = $Socket::VERSION; # replace '2.020_03' with '2.020'
3789 $socket_version =~ s/\_.*$//;
3790  
3791 unless (defined $family) {
3792 $family = "";
3793 }
3794  
3795 if ($family =~ /^\s*ipv4\s*$/i) { # family arg is "ipv4"
3796 $family = "ipv4";
3797 }
3798 elsif ($family =~ /^\s*any\s*$/i) { # family arg is "any"
3799 if ($socket_version >= 1.94 and defined $AF_INET6) { # has IPv6
3800 $family = "any";
3801 }
3802 else { # IPv6 not supported on this machine
3803 $family = "ipv4";
3804 }
3805 }
3806 elsif ($family =~ /^\s*ipv6\s*$/i) { # family arg is "ipv6"
3807 return $self->error("Localfamily arg ipv6 not supported when " .
3808 "Socket.pm version < 1.94")
3809 unless $socket_version >= 1.94;
3810 return $self->error("Localfamily arg ipv6 not supported by " .
3811 "this OS: AF_INET6 not in Socket.pm")
3812 unless defined $AF_INET6;
3813  
3814 $family = "ipv6";
3815 }
3816 else {
3817 return $self->error("bad Localfamily argument \"$family\": " .
3818 "must be \"ipv4\", \"ipv6\", or \"any\"");
3819 }
3820  
3821 $family;
3822 } # end sub _parse_localfamily
3823  
3824  
3825 sub _parse_port {
3826 my ($self, $port) = @_;
3827 my (
3828 $service,
3829 );
3830  
3831 unless (defined $port) {
3832 $port = "";
3833 }
3834  
3835 return $self->error("bad Port argument \"$port\"")
3836 unless $port;
3837  
3838 if ($port !~ /^\d+$/) { # port isn't all digits
3839 $service = $port;
3840 $port = getservbyname($service, "tcp");
3841  
3842 return $self->error("bad Port argument \"$service\": " .
3843 "it's an unknown TCP service")
3844 unless $port;
3845 }
3846  
3847 $port;
3848 } # end sub _parse_port
3849  
3850  
3851 sub _parse_prompt {
3852 my ($self, $prompt) = @_;
3853  
3854 unless (defined $prompt) {
3855 $prompt = "";
3856 }
3857  
3858 return $self->error("bad Prompt argument \"$prompt\": " .
3859 "missing opening delimiter of match operator")
3860 unless $prompt =~ m(^\s*/) or $prompt =~ m(^\s*m\s*\W);
3861  
3862 $prompt;
3863 } # end sub _parse_prompt
3864  
3865  
3866 sub _parse_timeout {
3867 my ($self, $timeout) = @_;
3868 local $@;
3869  
3870 ## Ensure valid timeout.
3871 if (defined $timeout) {
3872 ## Test for non-numeric or negative values.
3873 eval {
3874 local $SIG{"__DIE__"} = "DEFAULT";
3875 local $SIG{"__WARN__"} = sub { die "non-numeric\n" };
3876 local $^W = 1;
3877 $timeout *= 1;
3878 };
3879 if ($@) { # timeout arg is non-numeric
3880 &_carp($self,
3881 "ignoring non-numeric Timeout argument \"$timeout\"");
3882 $timeout = *$self->{net_telnet}{time_out};
3883 }
3884 elsif ($timeout < 0) { # timeout arg is negative
3885 &_carp($self, "ignoring negative Timeout argument \"$timeout\"");
3886 $timeout = *$self->{net_telnet}{time_out};
3887 }
3888 }
3889  
3890 $timeout;
3891 } # end sub _parse_timeout
3892  
3893  
3894 sub _put {
3895 my ($self, $buf, $subname) = @_;
3896 my (
3897 $endtime,
3898 $len,
3899 $nfound,
3900 $nwrote,
3901 $offset,
3902 $ready,
3903 $s,
3904 $timed_out,
3905 $timeout,
3906 $zero_wrote_count,
3907 );
3908  
3909 ## Init.
3910 $s = *$self->{net_telnet};
3911 $s->{num_wrote} = 0;
3912 $zero_wrote_count = 0;
3913 $offset = 0;
3914 $len = length $$buf;
3915 $endtime = &_endtime($s->{time_out});
3916  
3917 return $self->error("write error: filehandle isn't open")
3918 unless $s->{opened};
3919  
3920 ## Try to send any waiting option negotiation.
3921 if (length $s->{unsent_opts}) {
3922 &_flush_opts($self);
3923 }
3924  
3925 ## Write until all data blocks written.
3926 while ($len) {
3927 ## Determine how long to wait for output ready.
3928 ($timed_out, $timeout) = &_timeout_interval($endtime);
3929 if ($timed_out) {
3930 $s->{timedout} = 1;
3931 return $self->error("$subname timed-out");
3932 }
3933  
3934 ## Wait for output ready.
3935 $nfound = select "", $ready=$s->{fdmask}, "", $timeout;
3936  
3937 ## Handle any errors while waiting.
3938 if ((!defined $nfound or $nfound <= 0) and $s->{select_supported}) {
3939 if (defined $nfound and $nfound == 0) { # timed-out
3940 $s->{timedout} = 1;
3941 return $self->error("$subname timed-out");
3942 }
3943 else { # error waiting for output ready
3944 if (defined $EINTR) {
3945 next if $! == $EINTR; # restart select()
3946 }
3947 else {
3948 next if $! =~ /^interrupted/i; # restart select()
3949 }
3950  
3951 $s->{opened} = '';
3952 return $self->error("write error: $!");
3953 }
3954 }
3955  
3956 ## Write the data.
3957 $nwrote = syswrite $self, $$buf, $s->{blksize}, $offset;
3958  
3959 ## Handle any write errors.
3960 if (!defined $nwrote) { # write failed
3961 if (defined $EINTR) {
3962 next if $! == $EINTR; # restart syswrite()
3963 }
3964 else {
3965 next if $! =~ /^interrupted/i; # restart syswrite()
3966 }
3967  
3968 $s->{opened} = '';
3969 return $self->error("write error: $!");
3970 }
3971 elsif ($nwrote == 0) { # zero chars written
3972 ## Try ten more times to write the data.
3973 if ($zero_wrote_count++ <= 10) {
3974 &_sleep(0.01);
3975 next;
3976 }
3977  
3978 $s->{opened} = '';
3979 return $self->error("write error: zero length write: $!");
3980 }
3981  
3982 ## Display network traffic if requested.
3983 if ($s->{dumplog}) {
3984 &_log_dump('>', $s->{dumplog}, $buf, $offset, $nwrote);
3985 }
3986  
3987 ## Increment.
3988 $s->{num_wrote} += $nwrote;
3989 $offset += $nwrote;
3990 $len -= $nwrote;
3991 }
3992  
3993 1;
3994 } # end sub _put
3995  
3996  
3997 sub _qualify_fh {
3998 my ($obj, $name) = @_;
3999 my (
4000 $user_class,
4001 );
4002 local $@;
4003 local $_;
4004  
4005 ## Get user's package name.
4006 ($user_class) = &_user_caller($obj);
4007  
4008 ## Ensure name is qualified with a package name.
4009 $name = qualify($name, $user_class);
4010  
4011 ## If it's not already, make it a typeglob ref.
4012 if (!ref $name) {
4013 no strict;
4014 local $SIG{"__DIE__"} = "DEFAULT";
4015 local $^W = '';
4016  
4017 $name =~ s/^\*+//;
4018 $name = eval "\\*$name";
4019 return unless ref $name;
4020 }
4021  
4022 $name;
4023 } # end sub _qualify_fh
4024  
4025  
4026 sub _reset_options {
4027 my ($opts) = @_;
4028 my (
4029 $opt,
4030 );
4031  
4032 foreach $opt (keys %$opts) {
4033 $opts->{$opt}{remote_enabled} = '';
4034 $opts->{$opt}{remote_state} = "no";
4035 $opts->{$opt}{local_enabled} = '';
4036 $opts->{$opt}{local_state} = "no";
4037 }
4038  
4039 1;
4040 } # end sub _reset_options
4041  
4042  
4043 sub _save_lastline {
4044 my ($s) = @_;
4045 my (
4046 $firstpos,
4047 $lastpos,
4048 $len_w_sep,
4049 $len_wo_sep,
4050 $offset,
4051 );
4052 my $rs = "\n";
4053  
4054 if (($lastpos = rindex $s->{buf}, $rs) > -1) { # eol found
4055 while (1) {
4056 ## Find beginning of line.
4057 $firstpos = rindex $s->{buf}, $rs, $lastpos - 1;
4058 if ($firstpos == -1) {
4059 $offset = 0;
4060 }
4061 else {
4062 $offset = $firstpos + length $rs;
4063 }
4064  
4065 ## Determine length of line with and without separator.
4066 $len_wo_sep = $lastpos - $offset;
4067 $len_w_sep = $len_wo_sep + length $rs;
4068  
4069 ## Save line if it's not blank.
4070 if (substr($s->{buf}, $offset, $len_wo_sep)
4071 !~ /^\s*$/)
4072 {
4073 $s->{last_line} = substr($s->{buf},
4074 $offset,
4075 $len_w_sep);
4076 last;
4077 }
4078  
4079 last if $firstpos == -1;
4080  
4081 $lastpos = $firstpos;
4082 }
4083 }
4084  
4085 1;
4086 } # end sub _save_lastline
4087  
4088  
4089 sub _set_default_option {
4090 my ($s, $option) = @_;
4091  
4092 $s->{opts}{$option} = {
4093 remote_enabled => '',
4094 remote_state => "no",
4095 remote_enable_ok => '',
4096 local_enabled => '',
4097 local_state => "no",
4098 local_enable_ok => '',
4099 };
4100 } # end sub _set_default_option
4101  
4102  
4103 sub _sleep {
4104 my ($secs) = @_;
4105 my $bitmask = "";
4106 local *SOCK;
4107  
4108 socket SOCK, AF_INET, SOCK_STREAM, 0;
4109 vec($bitmask, fileno(SOCK), 1) = 1;
4110 select $bitmask, "", "", $secs;
4111 CORE::close SOCK;
4112  
4113 1;
4114 } # end sub _sleep
4115  
4116  
4117 sub _timeout_interval {
4118 my ($endtime) = @_;
4119 my (
4120 $timeout,
4121 );
4122  
4123 ## Return timed-out boolean and timeout interval.
4124 if (defined $endtime) {
4125 ## Is it a one-time poll.
4126 return ('', 0) if $endtime == 0;
4127  
4128 ## Calculate the timeout interval.
4129 $timeout = $endtime - time;
4130  
4131 ## Did we already timeout.
4132 return (1, 0) unless $timeout > 0;
4133  
4134 return ('', $timeout);
4135 }
4136 else { # there is no timeout
4137 return ('', undef);
4138 }
4139 } # end sub _timeout_interval
4140  
4141  
4142 sub _unpack_sockaddr {
4143 my ($self, $sockaddr) = @_;
4144 my (
4145 $packed_addr,
4146 $sockfamily,
4147 );
4148 my $addr = "";
4149 my $port = "";
4150  
4151 $sockfamily = $self->sockfamily;
4152  
4153 ## Parse sockaddr struct.
4154 if ($sockfamily eq "ipv4") {
4155 ($port, $packed_addr) = sockaddr_in($sockaddr);
4156 $addr = Socket::inet_ntoa($packed_addr);
4157 }
4158 elsif ($sockfamily eq "ipv6") {
4159 ($port, $packed_addr) = Socket::sockaddr_in6($sockaddr);
4160 $addr = Socket::inet_ntop($AF_INET6, $packed_addr);
4161 }
4162  
4163 ($port, $addr);
4164 } # end sub _unpack_sockaddr
4165  
4166  
4167 sub _user_caller {
4168 my ($obj) = @_;
4169 my (
4170 $class,
4171 $curr_pkg,
4172 $file,
4173 $i,
4174 $line,
4175 $pkg,
4176 %isa,
4177 @isa,
4178 );
4179 local $@;
4180 local $_;
4181  
4182 ## Create a boolean hash to test for isa. Make sure current
4183 ## package and the object's class are members.
4184 $class = ref $obj;
4185 @isa = eval "\@${class}::ISA";
4186 push @isa, $class;
4187 ($curr_pkg) = caller 1;
4188 push @isa, $curr_pkg;
4189 %isa = map { $_ => 1 } @isa;
4190  
4191 ## Search back in call frames for a package that's not in isa.
4192 $i = 1;
4193 while (($pkg, $file, $line) = caller ++$i) {
4194 next if $isa{$pkg};
4195  
4196 return ($pkg, $file, $line);
4197 }
4198  
4199 ## If not found, choose outer most call frame.
4200 ($pkg, $file, $line) = caller --$i;
4201 return ($pkg, $file, $line);
4202 } # end sub _user_caller
4203  
4204  
4205 sub _verify_telopt_arg {
4206 my ($self, $option, $argname) = @_;
4207 local $@;
4208  
4209 ## If provided, use argument name in error message.
4210 if (defined $argname) {
4211 $argname = "for arg $argname";
4212 }
4213 else {
4214 $argname = "";
4215 }
4216  
4217 ## Ensure telnet option is a non-negative integer.
4218 eval {
4219 local $SIG{"__DIE__"} = "DEFAULT";
4220 local $SIG{"__WARN__"} = sub { die "non-numeric\n" };
4221 local $^W = 1;
4222 $option = abs(int $option);
4223 };
4224 return $self->error("bad telnet option $argname: non-numeric")
4225 if $@;
4226  
4227 return $self->error("bad telnet option $argname: option > 255")
4228 unless $option <= 255;
4229  
4230 $option;
4231 } # end sub _verify_telopt_arg
4232  
4233  
4234 ######################## Exported Constants ##########################
4235  
4236  
4237 sub TELNET_IAC () {255}; # interpret as command:
4238 sub TELNET_DONT () {254}; # you are not to use option
4239 sub TELNET_DO () {253}; # please, you use option
4240 sub TELNET_WONT () {252}; # I won't use option
4241 sub TELNET_WILL () {251}; # I will use option
4242 sub TELNET_SB () {250}; # interpret as subnegotiation
4243 sub TELNET_GA () {249}; # you may reverse the line
4244 sub TELNET_EL () {248}; # erase the current line
4245 sub TELNET_EC () {247}; # erase the current character
4246 sub TELNET_AYT () {246}; # are you there
4247 sub TELNET_AO () {245}; # abort output--but let prog finish
4248 sub TELNET_IP () {244}; # interrupt process--permanently
4249 sub TELNET_BREAK () {243}; # break
4250 sub TELNET_DM () {242}; # data mark--for connect. cleaning
4251 sub TELNET_NOP () {241}; # nop
4252 sub TELNET_SE () {240}; # end sub negotiation
4253 sub TELNET_EOR () {239}; # end of record (transparent mode)
4254 sub TELNET_ABORT () {238}; # Abort process
4255 sub TELNET_SUSP () {237}; # Suspend process
4256 sub TELNET_EOF () {236}; # End of file
4257 sub TELNET_SYNCH () {242}; # for telfunc calls
4258  
4259 sub TELOPT_BINARY () {0}; # Binary Transmission
4260 sub TELOPT_ECHO () {1}; # Echo
4261 sub TELOPT_RCP () {2}; # Reconnection
4262 sub TELOPT_SGA () {3}; # Suppress Go Ahead
4263 sub TELOPT_NAMS () {4}; # Approx Message Size Negotiation
4264 sub TELOPT_STATUS () {5}; # Status
4265 sub TELOPT_TM () {6}; # Timing Mark
4266 sub TELOPT_RCTE () {7}; # Remote Controlled Trans and Echo
4267 sub TELOPT_NAOL () {8}; # Output Line Width
4268 sub TELOPT_NAOP () {9}; # Output Page Size
4269 sub TELOPT_NAOCRD () {10}; # Output Carriage-Return Disposition
4270 sub TELOPT_NAOHTS () {11}; # Output Horizontal Tab Stops
4271 sub TELOPT_NAOHTD () {12}; # Output Horizontal Tab Disposition
4272 sub TELOPT_NAOFFD () {13}; # Output Formfeed Disposition
4273 sub TELOPT_NAOVTS () {14}; # Output Vertical Tabstops
4274 sub TELOPT_NAOVTD () {15}; # Output Vertical Tab Disposition
4275 sub TELOPT_NAOLFD () {16}; # Output Linefeed Disposition
4276 sub TELOPT_XASCII () {17}; # Extended ASCII
4277 sub TELOPT_LOGOUT () {18}; # Logout
4278 sub TELOPT_BM () {19}; # Byte Macro
4279 sub TELOPT_DET () {20}; # Data Entry Terminal
4280 sub TELOPT_SUPDUP () {21}; # SUPDUP
4281 sub TELOPT_SUPDUPOUTPUT () {22}; # SUPDUP Output
4282 sub TELOPT_SNDLOC () {23}; # Send Location
4283 sub TELOPT_TTYPE () {24}; # Terminal Type
4284 sub TELOPT_EOR () {25}; # End of Record
4285 sub TELOPT_TUID () {26}; # TACACS User Identification
4286 sub TELOPT_OUTMRK () {27}; # Output Marking
4287 sub TELOPT_TTYLOC () {28}; # Terminal Location Number
4288 sub TELOPT_3270REGIME () {29}; # Telnet 3270 Regime
4289 sub TELOPT_X3PAD () {30}; # X.3 PAD
4290 sub TELOPT_NAWS () {31}; # Negotiate About Window Size
4291 sub TELOPT_TSPEED () {32}; # Terminal Speed
4292 sub TELOPT_LFLOW () {33}; # Remote Flow Control
4293 sub TELOPT_LINEMODE () {34}; # Linemode
4294 sub TELOPT_XDISPLOC () {35}; # X Display Location
4295 sub TELOPT_OLD_ENVIRON () {36}; # Environment Option
4296 sub TELOPT_AUTHENTICATION () {37}; # Authentication Option
4297 sub TELOPT_ENCRYPT () {38}; # Encryption Option
4298 sub TELOPT_NEW_ENVIRON () {39}; # New Environment Option
4299 sub TELOPT_TN3270E () {40}; # TN3270 Enhancements
4300 sub TELOPT_CHARSET () {42}; # CHARSET Option
4301 sub TELOPT_COMPORT () {44}; # Com Port Control Option
4302 sub TELOPT_KERMIT () {47}; # Kermit Option
4303 sub TELOPT_EXOPL () {255}; # Extended-Options-List
4304  
4305 # Added by Axmud
4306 sub TELOPT_MSDP () {69}; # Mud Server Data Protocol
4307 sub TELOPT_MSSP () {70}; # Mud Server Status Protocol
4308 sub TELOPT_MCCP1 () {85}; # Mud Client Compression Protocol (MCCP1)
4309 sub TELOPT_MCCP2 () {86}; # Mud Client Compression Protocol (MCCP2)
4310 sub TELOPT_MSP () {90}; # Mud Sound Protocol
4311 sub TELOPT_MXP () {91}; # Mud Xtension Protocol
4312 sub TELOPT_ZMP () {93}; # Zenith Mud Protocol
4313 sub TELOPT_AARD102 () {102}; # Aardwolf 102 channel
4314 sub TELOPT_ATCP () {200}; # Achaea Telnet Client Protocol
4315 sub TELOPT_GMCP () {201}; # Generic MUD Communication Protocol
4316 }
4317  
4318 # Package must return a true value
4319 1