perl 4.0 patch 14: patch #11, continued
[p5sagit/p5-mst-13.2.git] / lib / chat2.pl
1 ## chat.pl: chat with a server
2 ## V2.01.alpha.7 91/06/16
3 ## Randal L. Schwartz
4
5 package chat;
6
7 $sockaddr = 'S n a4 x8';
8 chop($thishost = `hostname`); $thisaddr = (gethostbyname($thishost))[4];
9 $thisproc = pack($sockaddr, 2, 0, $thisaddr);
10
11 # *S = symbol for current I/O, gets assigned *chatsymbol....
12 $next = "chatsymbol000000"; # next one
13 $nextpat = "^chatsymbol"; # patterns that match next++, ++, ++, ++
14
15
16 ## $handle = &chat'open_port("server.address",$port_number);
17 ## opens a named or numbered TCP server
18
19 sub open_port { ## public
20         local($server, $port) = @_;
21
22         local($serveraddr,$serverproc);
23
24         *S = ++$next;
25         if ($server =~ /^(\d+)+\.(\d+)\.(\d+)\.(\d+)$/) {
26                 $serveraddr = pack('C4', $1, $2, $3, $4);
27         } else {
28                 local(@x) = gethostbyname($server);
29                 return undef unless @x;
30                 $serveraddr = $x[4];
31         }
32         $serverproc = pack($sockaddr, 2, $port, $serveraddr);
33         unless (socket(S, 2, 1, 6)) {
34                 # XXX hardwired $AF_SOCKET, $SOCK_STREAM, 'tcp'
35                 # but who the heck would change these anyway? (:-)
36                 ($!) = ($!, close(S)); # close S while saving $!
37                 return undef;
38         }
39         unless (bind(S, $thisproc)) {
40                 ($!) = ($!, close(S)); # close S while saving $!
41                 return undef;
42         }
43         unless (connect(S, $serverproc)) {
44                 ($!) = ($!, close(S)); # close S while saving $!
45                 return undef;
46         }
47         select((select(S), $| = 1)[0]);
48         $next; # return symbol for switcharound
49 }
50
51 ## ($host, $port, $handle) = &chat'open_listen([$port_number]);
52 ## opens a TCP port on the current machine, ready to be listened to
53 ## if $port_number is absent or zero, pick a default port number
54 ## process must be uid 0 to listen to a low port number
55
56 sub open_listen { ## public
57
58         *S = ++$next;
59         local($thisport) = shift || 0;
60         local($thisproc_local) = pack($sockaddr, 2, $thisport, $thisaddr);
61         local(*NS) = "__" . time;
62         unless (socket(NS, 2, 1, 6)) {
63                 # XXX hardwired $AF_SOCKET, $SOCK_STREAM, 'tcp'
64                 # but who the heck would change these anyway? (:-)
65                 ($!) = ($!, close(NS));
66                 return undef;
67         }
68         unless (bind(NS, $thisproc_local)) {
69                 ($!) = ($!, close(NS));
70                 return undef;
71         }
72         unless (listen(NS, 1)) {
73                 ($!) = ($!, close(NS));
74                 return undef;
75         }
76         select((select(NS), $| = 1)[0]);
77         local($family, $port, @myaddr) =
78                 unpack("S n C C C C x8", getsockname(NS));
79         $S{"needs_accept"} = *NS; # so expect will open it
80         (@myaddr, $port, $next); # returning this
81 }
82
83 ## $handle = &chat'open_proc("command","arg1","arg2",...);
84 ## opens a /bin/sh on a pseudo-tty
85
86 sub open_proc { ## public
87         local(@cmd) = @_;
88
89         *S = ++$next;
90         local(*TTY) = "__TTY" . time;
91         local($pty,$tty) = &_getpty(S,TTY);
92         die "Cannot find a new pty" unless defined $pty;
93         local($pid) = fork;
94         die "Cannot fork: $!" unless defined $pid;
95         unless ($pid) {
96                 close STDIN; close STDOUT; close STDERR;
97                 setpgrp(0,$$);
98                 if (open(DEVTTY, "/dev/tty")) {
99                     ioctl(DEVTTY,0x20007471,0);         # XXX s/b &TIOCNOTTY
100                     close DEVTTY;
101                 }
102                 open(STDIN,"<&TTY");
103                 open(STDOUT,">&TTY");
104                 open(STDERR,">&STDOUT");
105                 die "Oops" unless fileno(STDERR) == 2;  # sanity
106                 close(S);
107                 exec @cmd;
108                 die "Cannot exec @cmd: $!";
109         }
110         close(TTY);
111         $next; # return symbol for switcharound
112 }
113
114 # $S is the read-ahead buffer
115
116 ## $return = &chat'expect([$handle,] $timeout_time,
117 ##      $pat1, $body1, $pat2, $body2, ... )
118 ## $handle is from previous &chat'open_*().
119 ## $timeout_time is the time (either relative to the current time, or
120 ## absolute, ala time(2)) at which a timeout event occurs.
121 ## $pat1, $pat2, and so on are regexs which are matched against the input
122 ## stream.  If a match is found, the entire matched string is consumed,
123 ## and the corresponding body eval string is evaled.
124 ##
125 ## Each pat is a regular-expression (probably enclosed in single-quotes
126 ## in the invocation).  ^ and $ will work, respecting the current value of $*.
127 ## If pat is 'TIMEOUT', the body is executed if the timeout is exceeded.
128 ## If pat is 'EOF', the body is executed if the process exits before
129 ## the other patterns are seen.
130 ##
131 ## Pats are scanned in the order given, so later pats can contain
132 ## general defaults that won't be examined unless the earlier pats
133 ## have failed.
134 ##
135 ## The result of eval'ing body is returned as the result of
136 ## the invocation.  Recursive invocations are not thought
137 ## through, and may work only accidentally. :-)
138 ##
139 ## undef is returned if either a timeout or an eof occurs and no
140 ## corresponding body has been defined.
141 ## I/O errors of any sort are treated as eof.
142
143 $nextsubname = "expectloop000000"; # used for subroutines
144
145 sub expect { ## public
146         if ($_[0] =~ /$nextpat/) {
147                 *S = shift;
148         }
149         local($endtime) = shift;
150
151         local($timeout,$eof) = (1,1);
152         local($caller) = caller;
153         local($rmask, $nfound, $timeleft, $thisbuf);
154         local($cases, $pattern, $action, $subname);
155         $endtime += time if $endtime < 600_000_000;
156
157         if (defined $S{"needs_accept"}) { # is it a listen socket?
158                 local(*NS) = $S{"needs_accept"};
159                 delete $S{"needs_accept"};
160                 $S{"needs_close"} = *NS;
161                 unless(accept(S,NS)) {
162                         ($!) = ($!, close(S), close(NS));
163                         return undef;
164                 }
165                 select((select(S), $| = 1)[0]);
166         }
167
168         # now see whether we need to create a new sub:
169
170         unless ($subname = $expect_subname{$caller,@_}) {
171                 # nope.  make a new one:
172                 $expect_subname{$caller,@_} = $subname = $nextsubname++;
173
174                 $cases .= <<"EDQ"; # header is funny to make everything elsif's
175 sub $subname {
176         LOOP: {
177                 if (0) { ; }
178 EDQ
179                 while (@_) {
180                         ($pattern,$action) = splice(@_,0,2);
181                         if ($pattern =~ /^eof$/i) {
182                                 $cases .= <<"EDQ";
183                 elsif (\$eof) {
184                         package $caller;
185                         $action;
186                 }
187 EDQ
188                                 $eof = 0;
189                         } elsif ($pattern =~ /^timeout$/i) {
190                         $cases .= <<"EDQ";
191                 elsif (\$timeout) {
192                         package $caller;
193                         $action;
194                 }
195 EDQ
196                                 $timeout = 0;
197                         } else {
198                                 $pattern =~ s#/#\\/#g;
199                         $cases .= <<"EDQ";
200                 elsif (\$S =~ /$pattern/) {
201                         \$S = \$';
202                         package $caller;
203                         $action;
204                 }
205 EDQ
206                         }
207                 }
208                 $cases .= <<"EDQ" if $eof;
209                 elsif (\$eof) {
210                         undef;
211                 }
212 EDQ
213                 $cases .= <<"EDQ" if $timeout;
214                 elsif (\$timeout) {
215                         undef;
216                 }
217 EDQ
218                 $cases .= <<'ESQ';
219                 else {
220                         $rmask = "";
221                         vec($rmask,fileno(S),1) = 1;
222                         ($nfound, $rmask) =
223                                 select($rmask, undef, undef, $endtime - time);
224                         if ($nfound) {
225                                 $nread = sysread(S, $thisbuf, 1024);
226                                 if ($nread > 0) {
227                                         $S .= $thisbuf;
228                                 } else {
229                                         $eof++, redo LOOP; # any error is also eof
230                                 }
231                         } else {
232                                 $timeout++, redo LOOP; # timeout
233                         }
234                         redo LOOP;
235                 }
236         }
237 }
238 ESQ
239                 eval $cases; die "$cases:\n$@" if $@;
240         }
241         $eof = $timeout = 0;
242         do $subname();
243 }
244
245 ## &chat'print([$handle,] @data)
246 ## $handle is from previous &chat'open().
247 ## like print $handle @data
248
249 sub print { ## public
250         if ($_[0] =~ /$nextpat/) {
251                 *S = shift;
252         }
253         print S @_;
254 }
255
256 ## &chat'close([$handle,])
257 ## $handle is from previous &chat'open().
258 ## like close $handle
259
260 sub close { ## public
261         if ($_[0] =~ /$nextpat/) {
262                 *S = shift;
263         }
264         close(S);
265         if (defined $S{"needs_close"}) { # is it a listen socket?
266                 local(*NS) = $S{"needs_close"};
267                 delete $S{"needs_close"};
268                 close(NS);
269         }
270 }
271
272 ## @ready_handles = &chat'select($timeout, @handles)
273 ## select()'s the handles with a timeout value of $timeout seconds.
274 ## Returns an array of handles that are ready for I/O.
275 ## Both user handles and chat handles are supported (but beware of
276 ## stdio's buffering for user handles).
277
278 sub select { ## public
279         local($timeout) = shift;
280         local(@handles) = @_;
281         local(%handlename) = ();
282         local(%ready) = ();
283         local($caller) = caller;
284         local($rmask) = "";
285         for (@handles) {
286                 if (/$nextpat/o) { # one of ours... see if ready
287                         local(*SYM) = $_;
288                         if (length($SYM)) {
289                                 $timeout = 0; # we have a winner
290                                 $ready{$_}++;
291                         }
292                         $handlename{fileno($_)} = $_;
293                 } else {
294                         $handlename{fileno(/'/ ? $_ : "$caller\'$_")} = $_;
295                 }
296         }
297         for (sort keys %handlename) {
298                 vec($rmask, $_, 1) = 1;
299         }
300         select($rmask, undef, undef, $timeout);
301         for (sort keys %handlename) {
302                 $ready{$handlename{$_}}++ if vec($rmask,$_,1);
303         }
304         sort keys %ready;
305 }
306
307 # ($pty,$tty) = $chat'_getpty(PTY,TTY):
308 # internal procedure to get the next available pty.
309 # opens pty on handle PTY, and matching tty on handle TTY.
310 # returns undef if can't find a pty.
311
312 sub _getpty { ## private
313         local($_PTY,$_TTY) = @_;
314         $_PTY =~ s/^([^']+)$/(caller)[$[]."'".$1/e;
315         $_TTY =~ s/^([^']+)$/(caller)[$[]."'".$1/e;
316         local($pty,$tty);
317         for $bank (112..127) {
318                 next unless -e sprintf("/dev/pty%c0", $bank);
319                 for $unit (48..57) {
320                         $pty = sprintf("/dev/pty%c%c", $bank, $unit);
321                         open($_PTY,"+>$pty") || next;
322                         select((select($_PTY), $| = 1)[0]);
323                         ($tty = $pty) =~ s/pty/tty/;
324                         open($_TTY,"+>$tty") || next;
325                         select((select($_TTY), $| = 1)[0]);
326                         system "stty nl>$tty";
327                         return ($pty,$tty);
328                 }
329         }
330         undef;
331 }
332
333 1;