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