-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamyrpm
executable file
·6621 lines (5086 loc) · 187 KB
/
amyrpm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# This chunk of stuff was generated by App::FatPacker. To find the original
# file's code, look for the end of this BEGIN block or the string 'FATPACK'
BEGIN {
my %fatpacked;
$fatpacked{"Expect.pm"} = '#line '.(1+__LINE__).' "'.__FILE__."\"\n".<<'EXPECT';
# -*-cperl-*-
# Please see the .pod files for documentation. This module is copyrighted
# as per the usual perl legalese:
# Copyright (c) 1997 Austin Schutz.
# expect() interface & functionality enhancements (c) 1999 Roland Giersig.
#
# All rights reserved. This program is free software; you can
# redistribute it and/or modify it under the same terms as Perl
# itself.
#
# Don't blame/flame me if you bust your stuff.
# Austin Schutz <[email protected]>
#
# This module now is maintained by
# Roland Giersig <[email protected]>
#
use 5.006; # 4 won't cut it.
package Expect;
use IO::Pty 1.03; # We need make_slave_controlling_terminal()
use IO::Tty;
use strict 'refs';
use strict 'vars';
use strict 'subs';
use POSIX qw(:sys_wait_h :unistd_h); # For WNOHANG and isatty
use Fcntl qw(:DEFAULT); # For checking file handle settings.
use Carp qw(cluck croak carp confess);
use IO::Handle ();
use Exporter ();
use Errno;
# This is necessary to make routines within Expect work.
@Expect::ISA = qw(IO::Pty Exporter);
@Expect::EXPORT = qw(expect exp_continue exp_continue_timeout);
BEGIN {
$Expect::VERSION = '1.21';
# These are defaults which may be changed per object, or set as
# the user wishes.
# This will be unset, since the default behavior differs between
# spawned processes and initialized filehandles.
# $Expect::Log_Stdout = 1;
$Expect::Log_Group = 1;
$Expect::Debug = 0;
$Expect::Exp_Max_Accum = 0; # unlimited
$Expect::Exp_Internal = 0;
$Expect::IgnoreEintr = 0;
$Expect::Manual_Stty = 0;
$Expect::Multiline_Matching = 1;
$Expect::Do_Soft_Close = 0;
@Expect::Before_List = ();
@Expect::After_List = ();
%Expect::Spawned_PIDs = ();
}
sub version {
my($version) = shift;
warn "Version $version is later than $Expect::VERSION. It may not be supported" if (defined ($version) && ($version > $Expect::VERSION));
die "Versions before 1.03 are not supported in this release" if ((defined ($version)) && ($version < 1.03));
return $Expect::VERSION;
}
sub new {
my ($class) = shift;
$class = ref($class) if ref($class); # so we can be called as $exp->new()
# Create the pty which we will use to pass process info.
my($self) = new IO::Pty;
die "$class: Could not assign a pty" unless $self;
bless $self => $class;
$self->autoflush(1);
# This is defined here since the default is different for
# initialized handles as opposed to spawned processes.
${*$self}{exp_Log_Stdout} = 1;
$self->_init_vars();
if (@_) {
# we got add'l parms, so pass them to spawn
return $self->spawn(@_);
}
return $self;
}
sub spawn {
my ($class) = shift;
my $self;
if (ref($class)) {
$self = $class;
} else {
$self = $class->new();
}
croak "Cannot reuse an object with an already spawned command"
if exists ${*$self}{"exp_Command"};
my(@cmd) = @_; # spawn is passed command line args.
${*$self}{"exp_Command"} = \@cmd;
# set up pipe to detect childs exec error
pipe(FROM_CHILD, TO_PARENT) or die "Cannot open pipe: $!";
pipe(FROM_PARENT, TO_CHILD) or die "Cannot open pipe: $!";
TO_PARENT->autoflush(1);
TO_CHILD->autoflush(1);
eval {
fcntl(TO_PARENT, Fcntl::F_SETFD, Fcntl::FD_CLOEXEC);
};
my $pid = fork;
unless (defined ($pid)) {
warn "Cannot fork: $!" if $^W;
return undef;
}
if($pid) {
# parent
my $errno;
${*$self}{exp_Pid} = $pid;
close TO_PARENT;
close FROM_PARENT;
$self->close_slave();
$self->set_raw() if $self->raw_pty and isatty($self);
close TO_CHILD; # so child gets EOF and can go ahead
# now wait for child exec (eof due to close-on-exit) or exec error
my $errstatus = sysread(FROM_CHILD, $errno, 256);
die "Cannot sync with child: $!" if not defined $errstatus;
close FROM_CHILD;
if ($errstatus) {
$! = $errno+0;
warn "Cannot exec(@cmd): $!\n" if $^W;
return undef;
}
}
else {
# child
close FROM_CHILD;
close TO_CHILD;
$self->make_slave_controlling_terminal();
my $slv = $self->slave()
or die "Cannot get slave: $!";
$slv->set_raw() if $self->raw_pty;
close($self);
# wait for parent before we detach
my $buffer;
my $errstatus = sysread(FROM_PARENT, $buffer, 256);
die "Cannot sync with parent: $!" if not defined $errstatus;
close FROM_PARENT;
close(STDIN);
open(STDIN,"<&". $slv->fileno())
or die "Couldn't reopen STDIN for reading, $!\n";
close(STDOUT);
open(STDOUT,">&". $slv->fileno())
or die "Couldn't reopen STDOUT for writing, $!\n";
close(STDERR);
open(STDERR,">&". $slv->fileno())
or die "Couldn't reopen STDERR for writing, $!\n";
{ exec(@cmd) };
print TO_PARENT $!+0;
die "Cannot exec(@cmd): $!\n";
}
# This is sort of for code compatibility, and to make debugging a little
# easier. By code compatibility I mean that previously the process's
# handle was referenced by $process{Pty_Handle} instead of just $process.
# This is almost like 'naming' the handle to the process.
# I think this also reflects Tcl Expect-like behavior.
${*$self}{exp_Pty_Handle} = "spawn id(".$self->fileno().")";
if ((${*$self}{"exp_Debug"}) or (${*$self}{"exp_Exp_Internal"})) {
cluck("Spawned '@cmd'\r\n",
"\t${*$self}{exp_Pty_Handle}\r\n",
"\tPid: ${*$self}{exp_Pid}\r\n",
"\tTty: ".$self->SUPER::ttyname()."\r\n",
);
}
$Expect::Spawned_PIDs{${*$self}{exp_Pid}} = undef;
return $self;
}
sub exp_init {
# take a filehandle, for use later with expect() or interconnect() .
# All the functions are written for reading from a tty, so if the naming
# scheme looks odd, that's why.
my ($class) = shift;
my($self) = shift;
bless $self, $class;
croak "exp_init not passed a file object, stopped"
unless defined($self->fileno());
$self->autoflush(1);
# Define standard variables.. debug states, etc.
$self->_init_vars();
# Turn of logging. By default we don't want crap from a file to get spewed
# on screen as we read it.
${*$self}{exp_Log_Stdout} = 0;
${*$self}{exp_Pty_Handle} = "handle id(".$self->fileno().")";
${*$self}{exp_Pty_Handle} = "STDIN" if $self->fileno() == fileno (STDIN);
print STDERR "Initialized ${*$self}{exp_Pty_Handle}.'\r\n"
if ${*$self}{"exp_Debug"};
return $self;
}
# make an alias
*init = \&exp_init;
######################################################################
# We're happy OOP people. No direct access to stuff.
# For standard read-writeable parameters, we define some autoload magic...
my %Writeable_Vars = ( debug => 'exp_Debug',
exp_internal => 'exp_Exp_Internal',
do_soft_close => 'exp_Do_Soft_Close',
max_accum => 'exp_Max_Accum',
match_max => 'exp_Max_Accum',
notransfer => 'exp_NoTransfer',
log_stdout => 'exp_Log_Stdout',
log_user => 'exp_Log_Stdout',
log_group => 'exp_Log_Group',
manual_stty => 'exp_Manual_Stty',
restart_timeout_upon_receive => 'exp_Continue',
raw_pty => 'exp_Raw_Pty',
);
my %Readable_Vars = ( pid => 'exp_Pid',
exp_pid => 'exp_Pid',
exp_match_number => 'exp_Match_Number',
match_number => 'exp_Match_Number',
exp_error => 'exp_Error',
error => 'exp_Error',
exp_command => 'exp_Command',
command => 'exp_Command',
exp_match => 'exp_Match',
match => 'exp_Match',
exp_matchlist => 'exp_Matchlist',
matchlist => 'exp_Matchlist',
exp_before => 'exp_Before',
before => 'exp_Before',
exp_after => 'exp_After',
after => 'exp_After',
exp_exitstatus => 'exp_Exit',
exitstatus => 'exp_Exit',
exp_pty_handle => 'exp_Pty_Handle',
pty_handle => 'exp_Pty_Handle',
exp_logfile => 'exp_Log_File',
logfile => 'exp_Log_File',
%Writeable_Vars,
);
sub AUTOLOAD {
my $self = shift;
my $type = ref($self)
or croak "$self is not an object";
use vars qw($AUTOLOAD);
my $name = $AUTOLOAD;
$name =~ s/.*:://; # strip fully-qualified portion
unless (exists $Readable_Vars{$name}) {
croak "ERROR: cannot find method `$name' in class $type";
}
my $varname = $Readable_Vars{$name};
my $tmp;
$tmp = ${*$self}{$varname} if exists ${*$self}{$varname};
if (@_) {
if (exists $Writeable_Vars{$name}) {
my $ref = ref($tmp);
if ($ref eq 'ARRAY') {
${*$self}{$varname} = [ @_ ];
} elsif ($ref eq 'HASH') {
${*$self}{$varname} = { @_ };
} else {
${*$self}{$varname} = shift;
}
} else {
carp "Trying to set read-only variable `$name'"
if $^W;
}
}
my $ref = ref($tmp);
return (wantarray? @{$tmp} : $tmp) if ($ref eq 'ARRAY');
return (wantarray? %{$tmp} : $tmp) if ($ref eq 'HASH');
return $tmp;
}
######################################################################
sub set_seq {
# Set an escape sequence/function combo for a read handle for interconnect.
# Ex: $read_handle->set_seq('',\&function,\@parameters);
my($self) = shift;
my($escape_sequence,$function) = (shift,shift);
${${*$self}{exp_Function}}{$escape_sequence} = $function;
if ((!defined($function)) ||($function eq 'undef')) {
${${*$self}{exp_Function}}{$escape_sequence} = \&_undef;
}
${${*$self}{exp_Parameters}}{$escape_sequence} = shift;
# This'll be a joy to execute. :)
if ( ${*$self}{"exp_Debug"} ) {
print STDERR "Escape seq. '" . $escape_sequence;
print STDERR "' function for ${*$self}{exp_Pty_Handle} set to '";
print STDERR ${${*$self}{exp_Function}}{$escape_sequence};
print STDERR "(" . join(',', @_) . ")'\r\n";
}
}
sub set_group {
my($self) = shift;
my($write_handle);
# Make sure we can read from the read handle
if (! defined($_[0])) {
if (defined (${*$self}{exp_Listen_Group})) {
return @{${*$self}{exp_Listen_Group}};
} else {
# Refrain from referencing an undef
return undef;
}
}
@{${*$self}{exp_Listen_Group}} = ();
if ($self->_get_mode() !~ 'r') {
warn("Attempting to set a handle group on ${*$self}{exp_Pty_Handle}, ",
"a non-readable handle!\r\n");
}
while ($write_handle = shift) {
if ($write_handle->_get_mode() !~ 'w') {
warn("Attempting to set a non-writeable listen handle ",
"${*$write_handle}{exp_Pty_handle} for ",
"${*$self}{exp_Pty_Handle}!\r\n");
}
push (@{${*$self}{exp_Listen_Group}},$write_handle);
}
}
sub log_file {
my $self = shift;
return(${*$self}{exp_Log_File})
if not @_; # we got no param, return filehandle
my $file = shift;
my $mode = shift || "a";
if (${*$self}{exp_Log_File} and ref(${*$self}{exp_Log_File}) ne 'CODE') {
close(${*$self}{exp_Log_File});
}
${*$self}{exp_Log_File} = undef;
return if (not $file);
my $fh = $file;
if (not ref($file)) {
# it's a filename
$fh = new IO::File $file, $mode
or croak "Cannot open logfile $file: $!";
}
if (ref($file) ne 'CODE') {
croak "Given logfile doesn't have a 'print' method"
if not $fh->can("print");
$fh->autoflush(1); # so logfile is up to date
}
${*$self}{exp_Log_File} = $fh;
}
# I'm going to leave this here in case I might need to change something.
# Previously this was calling `stty`, in a most bastardized manner.
sub exp_stty {
my($self) = shift;
my($mode) = "@_";
return undef unless defined($mode);
if (not defined $INC{"IO/Stty.pm"}) {
carp "IO::Stty not installed, cannot change mode";
return undef;
}
if (${*$self}{"exp_Debug"}) {
print STDERR "Setting ${*$self}{exp_Pty_Handle} to tty mode '$mode'\r\n";
}
unless (POSIX::isatty($self)) {
if (${*$self}{"exp_Debug"} or $^W) {
warn "${*$self}{exp_Pty_Handle} is not a tty. Not changing mode";
}
return ''; # No undef to avoid warnings elsewhere.
}
IO::Stty::stty($self, split(/\s/,$mode));
}
*stty = \&exp_stty;
# If we want to clear the buffer. Otherwise Accum will grow during send_slow
# etc. and contain the remainder after matches.
sub clear_accum {
my ($self) = shift;
my ($temp) = (${*$self}{exp_Accum});
${*$self}{exp_Accum} = '';
# return the contents of the accumulator.
return $temp;
}
sub set_accum {
my ($self) = shift;
my ($temp) = (${*$self}{exp_Accum});
${*$self}{exp_Accum} = shift;
# return the contents of the accumulator.
return $temp;
}
######################################################################
# define constants for pattern subs
sub exp_continue() { "exp_continue" }
sub exp_continue_timeout() { "exp_continue_timeout" }
######################################################################
# Expect on multiple objects at once.
#
# Call as Expect::expect($timeout, -i => \@exp_list, @patternlist,
# -i => $exp, @pattern_list, ...);
# or $exp->expect($timeout, @patternlist, -i => \@exp_list, @patternlist,
# -i => $exp, @pattern_list, ...);
#
# Patterns are arrays that consist of
# [ $pattern_type, $pattern, $sub, @subparms ]
#
# Optional $pattern_type is '-re' (RegExp, default) or '-ex' (exact);
#
# $sub is optional CODE ref, which is called as &{$sub}($exp, @subparms)
# if pattern matched; may return exp_continue or exp_continue_timeout.
#
# Old-style syntax (pure pattern strings with optional type) also supported.
#
sub expect {
my $self;
print STDERR ("expect(@_) called...\n") if $Expect::Debug;
if (defined($_[0])) {
if (ref($_[0]) and $_[0]->isa('Expect')) {
$self = shift;
} elsif ($_[0] eq 'Expect') {
shift; # or as Expect->expect
}
}
croak "expect(): not enough arguments, should be expect(timeout, [patterns...])" if @_ < 1;
my $timeout = shift;
my $timeout_hook = undef;
my @object_list;
my %patterns;
my @pattern_list;
my @timeout_list;
my $curr_list;
if ($self) {
$curr_list = [$self];
} else {
# called directly, so first parameter must be '-i' to establish
# object list.
$curr_list = [];
croak "expect(): ERROR: if called directly (not as \$obj->expect(...), but as Expect::expect(...), first parameter MUST be '-i' to set an object (list) for the patterns to work on."
if ($_[0] ne '-i');
}
# Let's make a list of patterns wanting to be evaled as regexps.
my $parm;
my $parm_nr = 1;
while (defined($parm = shift)) {
print STDERR ("expect(): handling param '$parm'...\n") if $Expect::Debug;
if (ref($parm)) {
if (ref($parm) eq 'ARRAY') {
my $err = _add_patterns_to_list(\@pattern_list, \@timeout_list,
$parm_nr, $parm);
carp ("expect(): Warning: multiple `timeout' patterns (",
scalar(@timeout_list), ").\r\n")
if @timeout_list > 1;
$timeout_hook = $timeout_list[-1] if $timeout_list[-1];
croak $err if $err;
$parm_nr++;
} else {
croak ("expect(): Unknown pattern ref $parm");
}
} else {
# not a ref, is an option or raw pattern
if (substr($parm, 0, 1) eq '-') {
# it's an option
print STDERR ("expect(): handling option '$parm'...\n")
if $Expect::Debug;
if ($parm eq '-i') {
# first add collected patterns to object list
if (scalar(@$curr_list)) {
push @object_list, $curr_list if not exists $patterns{"$curr_list"};
push @{$patterns{"$curr_list"}}, @pattern_list;
@pattern_list = ();
}
# now put parm(s) into current object list
if (ref($_[0]) eq 'ARRAY') {
$curr_list = shift;
} else {
$curr_list = [ shift ];
}
} elsif ($parm eq '-re'
or $parm eq '-ex') {
if (ref($_[1]) eq 'CODE') {
push @pattern_list, [ $parm_nr, $parm, shift, shift ];
} else {
push @pattern_list, [ $parm_nr, $parm, shift, undef ];
}
$parm_nr++;
} else {
croak ("Unknown option $parm");
}
} else {
# a plain pattern, check if it is followed by a CODE ref
if (ref($_[0]) eq 'CODE') {
if ($parm eq 'timeout') {
push @timeout_list, shift;
carp ("expect(): Warning: multiple `timeout' patterns (",
scalar(@timeout_list), ").\r\n")
if @timeout_list > 1;
$timeout_hook = $timeout_list[-1] if $timeout_list[-1];
} elsif ($parm eq 'eof') {
push @pattern_list, [ $parm_nr, "-$parm", undef, shift ];
} else {
push @pattern_list, [ $parm_nr, '-ex', $parm, shift ];
}
} else {
print STDERR ("expect(): exact match '$parm'...\n")
if $Expect::Debug;
push @pattern_list, [ $parm_nr, '-ex', $parm, undef ];
}
$parm_nr++;
}
}
}
# add rest of collected patterns to object list
carp "expect(): Empty object list" unless $curr_list;
push @object_list, $curr_list if not exists $patterns{"$curr_list"};
push @{$patterns{"$curr_list"}}, @pattern_list;
my $debug = $self ? ${*$self}{exp_Debug} : $Expect::Debug;
my $internal = $self ? ${*$self}{exp_Exp_Internal} : $Expect::Exp_Internal;
# now start matching...
if (@Expect::Before_List) {
print STDERR ("Starting BEFORE pattern matching...\r\n")
if ($debug or $internal);
_multi_expect(0, undef, @Expect::Before_List);
}
cluck ("Starting EXPECT pattern matching...\r\n")
if ($debug or $internal);
my @ret;
@ret = _multi_expect($timeout, $timeout_hook,
map { [$_, @{$patterns{"$_"}}] } @object_list);
if (@Expect::After_List) {
print STDERR ("Starting AFTER pattern matching...\r\n")
if ($debug or $internal);
_multi_expect(0, undef, @Expect::After_List);
}
wantarray ? @ret : $ret[0];
}
######################################################################
# the real workhorse
#
sub _multi_expect($$@) {
my $timeout = shift;
my $timeout_hook = shift;
if ($timeout_hook) {
croak "Unknown timeout_hook type $timeout_hook"
unless (ref($timeout_hook) eq 'CODE'
or ref($timeout_hook) eq 'ARRAY');
}
foreach my $pat (@_) {
my @patterns = @{$pat}[1..$#{$pat}];
foreach my $exp (@{$pat->[0]}) {
${*$exp}{exp_New_Data} = 1; # first round we always try to match
if (exists ${*$exp}{"exp_Max_Accum"} and ${*$exp}{"exp_Max_Accum"}) {
${*$exp}{exp_Accum} =
$exp->_trim_length(${*$exp}{exp_Accum},
${*$exp}{exp_Max_Accum});
}
print STDERR ("${*$exp}{exp_Pty_Handle}: beginning expect.\r\n",
"\tTimeout: ",
(defined($timeout) ? $timeout : "unlimited" ),
" seconds.\r\n",
"\tCurrent time: ". localtime(). "\r\n",
) if $Expect::Debug;
# What are we expecting? What do you expect? :-)
if (${*$exp}{exp_Exp_Internal}) {
print STDERR "${*$exp}{exp_Pty_Handle}: list of patterns:\r\n";
foreach my $pattern (@patterns) {
print STDERR (' ',
defined($pattern->[0])?
'#'. $pattern->[0].': ' :
'',
$pattern->[1],
" `", _make_readable($pattern->[2]),
"'\r\n");
}
print STDERR "\r\n";
}
}
}
my $successful_pattern;
my $exp_matched;
my $err;
my $before;
my $after;
my $match;
my @matchlist;
# Set the last loop time to now for time comparisons at end of loop.
my $start_loop_time = time();
my $exp_cont = 1;
READLOOP:
while ($exp_cont) {
$exp_cont = 1;
$err = "";
my $rmask = '';
my $time_left = undef;
if (defined $timeout) {
$time_left = $timeout - (time() - $start_loop_time);
$time_left = 0 if $time_left < 0;
}
$exp_matched = undef;
# Test for a match first so we can test the current Accum w/out
# worrying about an EOF.
foreach my $pat (@_) {
my @patterns = @{$pat}[1..$#{$pat}];
foreach my $exp (@{$pat->[0]}) {
# build mask for select in next section...
my $fn = $exp->fileno();
vec($rmask, $fn, 1) = 1 if defined $fn;
next unless ${*$exp}{exp_New_Data};
# clear error status
${*$exp}{exp_Error} = undef;
# This could be huge. We should attempt to do something
# about this. Because the output is used for debugging
# I'm of the opinion that showing smaller amounts if the
# total is huge should be ok.
# Thus the 'trim_length'
print STDERR ("\r\n${*$exp}{exp_Pty_Handle}: Does `",
$exp->_trim_length(_make_readable(${*$exp}{exp_Accum})),
"'\r\nmatch:\r\n")
if ${*$exp}{exp_Exp_Internal};
# we don't keep the parameter number anymore
# (clashes with before & after), instead the parameter number is
# stored inside the pattern; we keep the pattern ref
# and look up the number later.
foreach my $pattern (@patterns) {
print STDERR (" pattern",
defined($pattern->[0])? ' #' . $pattern->[0] : '',
": ", $pattern->[1],
" `", _make_readable($pattern->[2]),
"'? ")
if (${*$exp}{exp_Exp_Internal});
# Matching exactly
if ($pattern->[1] eq '-ex') {
my $match_index = index(${*$exp}{exp_Accum},
$pattern->[2]);
# We matched if $match_index > -1
if ($match_index > -1) {
$before = substr(${*$exp}{exp_Accum}, 0, $match_index);
$match = substr(${*$exp}{exp_Accum}, $match_index,
length($pattern->[2]));
$after = substr(${*$exp}{exp_Accum},
$match_index + length($pattern->[2])) ;
${*$exp}{exp_Before} = $before;
${*$exp}{exp_Match} = $match;
${*$exp}{exp_After} = $after;
${*$exp}{exp_Match_Number} = $pattern->[0];
$exp_matched = $exp;
}
} elsif ($pattern->[1] eq '-re') {
# m// in array context promises to return an empty list
# but doesn't if the pattern doesn't contain brackets (),
# so we kludge around by adding an empty bracket
# at the end.
if ($Expect::Multiline_Matching) {
@matchlist = (${*$exp}{exp_Accum}
=~ m/$pattern->[2]()/m);
($match, $before, $after) = ($&, $`, $');
} else {
@matchlist = (${*$exp}{exp_Accum}
=~ m/$pattern->[2]()/);
($match, $before, $after) = ($&, $`, $');
}
if (@matchlist) {
# Matching regexp
${*$exp}{exp_Before} = $before;
${*$exp}{exp_Match} = $match;
${*$exp}{exp_After} = $after;
pop @matchlist; # remove kludged empty bracket from end
@{${*$exp}{exp_Matchlist}} = @matchlist;
${*$exp}{exp_Match_Number} = $pattern->[0];
$exp_matched = $exp;
}
} else {
# 'timeout' or 'eof'
}
if ($exp_matched) {
${*$exp}{exp_Accum} = $after
unless ${*$exp}{exp_NoTransfer};
print STDERR "YES!!\r\n"
if ${*$exp}{exp_Exp_Internal};
print STDERR (" Before match string: `",
$exp->_trim_length(_make_readable(($before))),
"'\r\n",
" Match string: `", _make_readable($match),
"'\r\n",
" After match string: `",
$exp->_trim_length(_make_readable(($after))),
"'\r\n",
" Matchlist: (",
join(", ",
map { "`".$exp->_trim_length(_make_readable(($_)))."'"
} @matchlist,
),
")\r\n",
) if (${*$exp}{exp_Exp_Internal});
# call hook function if defined
if ($pattern->[3]) {
print STDERR ("Calling hook $pattern->[3]...\r\n",
) if (${*$exp}{exp_Exp_Internal} or $Expect::Debug);
if ($#{$pattern} > 3) {
# call with parameters if given
$exp_cont = &{$pattern->[3]}($exp,
@{$pattern}[4..$#{$pattern}]);
} else {
$exp_cont = &{$pattern->[3]}($exp);
}
}
if ($exp_cont and $exp_cont eq exp_continue) {
print STDERR ("Continuing expect, restarting timeout...\r\n")
if (${*$exp}{exp_Exp_Internal} or $Expect::Debug);
$start_loop_time = time(); # restart timeout count
next READLOOP;
} elsif ($exp_cont and $exp_cont eq exp_continue_timeout) {
print STDERR ("Continuing expect...\r\n")
if (${*$exp}{exp_Exp_Internal} or $Expect::Debug);
next READLOOP;
}
last READLOOP;
}
print STDERR "No.\r\n" if ${*$exp}{exp_Exp_Internal};
}
print STDERR "\r\n" if ${*$exp}{exp_Exp_Internal};
# don't have to match again until we get new data
${*$exp}{exp_New_Data} = 0;
}
} # End of matching section
# No match, let's see what is pending on the filehandles...
print STDERR ("Waiting for new data (",
defined($time_left)? $time_left : 'unlimited',
" seconds)...\r\n",
) if ($Expect::Exp_Internal or $Expect::Debug);
my $nfound;
SELECT: {
$nfound = select($rmask, undef, undef, $time_left);
if ($nfound < 0) {
if ($!{EINTR} and $Expect::IgnoreEintr) {
print STDERR ("ignoring EINTR, restarting select()...\r\n")
if ($Expect::Exp_Internal or $Expect::Debug);
next SELECT;
}
print STDERR ("select() returned error code '$!'\r\n")
if ($Expect::Exp_Internal or $Expect::Debug);
# returned error
$err = "4:$!";
last READLOOP;
}
}
# go until we don't find something (== timeout).
if ($nfound == 0) {
# No pattern, no EOF. Did we time out?
$err = "1:TIMEOUT";
foreach my $pat (@_) {
foreach my $exp (@{$pat->[0]}) {
$before = ${*$exp}{exp_Before} = ${*$exp}{exp_Accum};
next if not defined $exp->fileno(); # skip already closed
${*$exp}{exp_Error} = $err unless ${*$exp}{exp_Error};
}
}
print STDERR ("TIMEOUT\r\n")
if ($Expect::Debug or $Expect::Exp_Internal);
if ($timeout_hook) {
my $ret;
print STDERR ("Calling timeout function $timeout_hook...\r\n")
if ($Expect::Debug or $Expect::Exp_Internal);
if (ref($timeout_hook) eq 'CODE') {
$ret = &{$timeout_hook}($_[0]->[0]);
} else {
if ($#{$timeout_hook} > 3) {
$ret = &{$timeout_hook->[3]}($_[0]->[0],
@{$timeout_hook}[4..$#{$timeout_hook}]);
} else {
$ret = &{$timeout_hook->[3]}($_[0]->[0]);
}
}
if ($ret and $ret eq exp_continue) {
$start_loop_time = time(); # restart timeout count
next READLOOP;
}
}
last READLOOP;
}
my @bits = split(//,unpack('b*',$rmask));
foreach my $pat (@_) {
foreach my $exp (@{$pat->[0]}) {
next if not defined $exp->fileno(); # skip already closed
if ($bits[$exp->fileno()]) {
print STDERR ("${*$exp}{exp_Pty_Handle}: new data.\r\n")
if $Expect::Debug;
# read in what we found.
my $buffer;
my $nread = sysread($exp, $buffer, 2048);
# Make errors (nread undef) show up as EOF.
$nread = 0 unless defined ($nread);
if ($nread == 0) {
print STDERR ("${*$exp}{exp_Pty_Handle}: EOF\r\n")
if ($Expect::Debug);
$before = ${*$exp}{exp_Before} = $exp->clear_accum();
$err = "2:EOF";
${*$exp}{exp_Error} = $err;
${*$exp}{exp_Has_EOF} = 1;
$exp_cont = undef;
foreach my $eof_pat (grep {$_->[1] eq '-eof'} @{$pat}[1..$#{$pat}]) {
my $ret;
print STDERR ("Calling EOF hook $eof_pat->[3]...\r\n",
) if ($Expect::Debug);
if ($#{$eof_pat} > 3) {
# call with parameters if given
$ret = &{$eof_pat->[3]}($exp,
@{$eof_pat}[4..$#{$eof_pat}]);
} else {
$ret = &{$eof_pat->[3]}($exp);
}
if ($ret and
($ret eq exp_continue
or $ret eq exp_continue_timeout)) {
$exp_cont = $ret;
}
}
# is it dead?
if (defined(${*$exp}{exp_Pid})) {
my $ret = waitpid(${*$exp}{exp_Pid}, POSIX::WNOHANG);
if ($ret == ${*$exp}{exp_Pid}) {
printf STDERR ("%s: exit(0x%02X)\r\n",
${*$exp}{exp_Pty_Handle}, $?)
if ($Expect::Debug);
$err = "3:Child PID ${*$exp}{exp_Pid} exited with status $?";
${*$exp}{exp_Error} = $err;
${*$exp}{exp_Exit} = $?;
delete $Expect::Spawned_PIDs{${*$exp}{exp_Pid}};
${*$exp}{exp_Pid} = undef;
}
}
print STDERR ("${*$exp}{exp_Pty_Handle}: closing...\r\n")
if ($Expect::Debug);
$exp->hard_close();
next;
}
print STDERR ("${*$exp}{exp_Pty_Handle}: read $nread byte(s).\r\n")
if ($Expect::Debug);
# ugly hack for broken solaris ttys that spew <blank><backspace>
# into our pretty output
$buffer =~ s/ \cH//g if not ${*$exp}{exp_Raw_Pty};
# Append it to the accumulator.
${*$exp}{exp_Accum} .= $buffer;
if (exists ${*$exp}{exp_Max_Accum}
and ${*$exp}{exp_Max_Accum}) {
${*$exp}{exp_Accum} =
$exp->_trim_length(${*$exp}{exp_Accum},
${*$exp}{exp_Max_Accum});
}
${*$exp}{exp_New_Data} = 1; # next round we try to match again
$exp_cont = exp_continue
if (exists ${*$exp}{exp_Continue} and ${*$exp}{exp_Continue});
# Now propagate what we have read to other listeners...
$exp->_print_handles($buffer);
# End handle reading section.
}
}
} # end read loop
$start_loop_time = time() # restart timeout count
if ($exp_cont and $exp_cont eq exp_continue);
}
# End READLOOP
# Post loop. Do we have anything?
# Tell us status
if ($Expect::Debug or $Expect::Exp_Internal) {
if ($exp_matched) {
print STDERR ("Returning from expect ",
${*$exp_matched}{exp_Error} ? 'un' : '',
"successfully.",
${*$exp_matched}{exp_Error} ?
"\r\n Error: ${*$exp_matched}{exp_Error}." : '',
"\r\n");
} else {
print STDERR ("Returning from expect with TIMEOUT or EOF\r\n");
}
if ($Expect::Debug and $exp_matched) {
print STDERR " ${*$exp_matched}{exp_Pty_Handle}: accumulator: `";
if (${*$exp_matched}{exp_Error}) {
print STDERR ($exp_matched->_trim_length
(_make_readable(${*$exp_matched}{exp_Before})),
"'\r\n");
} else {
print STDERR ($exp_matched->_trim_length
(_make_readable(${*$exp_matched}{exp_Accum})),
"'\r\n");
}
}
}
if ($exp_matched) {
return wantarray?
(${*$exp_matched}{exp_Match_Number},
${*$exp_matched}{exp_Error},
${*$exp_matched}{exp_Match},
${*$exp_matched}{exp_Before},
${*$exp_matched}{exp_After},
$exp_matched,
) :
${*$exp_matched}{exp_Match_Number};
}
return wantarray? (undef, $err, undef, $before, undef, undef) : undef;
}
# Patterns are arrays that consist of
# [ $pattern_type, $pattern, $sub, @subparms ]
# optional $pattern_type is '-re' (RegExp, default) or '-ex' (exact);
# $sub is optional CODE ref, which is called as &{$sub}($exp, @subparms)
# if pattern matched;
# the $parm_nr gets unshifted onto the array for reporting purposes.
sub _add_patterns_to_list($$$@) {
my $listref = shift;
my $timeoutlistref = shift; # gets timeout patterns
my $store_parm_nr = shift;
my $parm_nr = $store_parm_nr || 1;
foreach my $parm (@_) {
if (not ref($parm) eq 'ARRAY') {
return "Parameter #$parm_nr is not an ARRAY ref.";
}
$parm = [@$parm]; # make copy
if ($parm->[0] =~ m/\A-/) {
# it's an option
if ($parm->[0] ne '-re'
and $parm->[0] ne '-ex') {
return "Unknown option $parm->[0] in pattern #$parm_nr";
}