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>
9 require 'sys/socket.ph';
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' );
18 # XXX hardwired $PF_INET, $SOCK_STREAM, 'tcp'
19 # but who the heck would change these anyway? (:-)
26 $sockaddr = 'S n a4 x8';
27 chop($thishost = `hostname`);
29 # *S = symbol for current I/O, gets assigned *chatsymbol....
30 $next = "chatsymbol000000"; # next one
31 $nextpat = "^chatsymbol"; # patterns that match next++, ++, ++, ++
34 ## $handle = &chat'open_port("server.address",$port_number);
35 ## opens a named or numbered TCP server
37 sub open_port { ## public
38 local($server, $port) = @_;
40 local($serveraddr,$serverproc);
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);
47 if ($server =~ /^(\d+)+\.(\d+)\.(\d+)\.(\d+)$/) {
48 $serveraddr = pack('C4', $1, $2, $3, $4);
50 local(@x) = gethostbyname($server);
51 return undef unless @x;
54 $serverproc = pack($sockaddr, 2, $port, $serveraddr);
55 unless (socket(S, $pf_inet, $sock_stream, $tcp_proto)) {
56 ($!) = ($!, close(S)); # close S while saving $!
59 unless (bind(S, $thisproc)) {
60 ($!) = ($!, close(S)); # close S while saving $!
63 unless (connect(S, $serverproc)) {
64 ($!) = ($!, close(S)); # close S while saving $!
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.
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
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
83 sub open_listen { ## public
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));
93 unless (bind(NS, $thisproc_local)) {
94 ($!) = ($!, close(NS));
97 unless (listen(NS, 1)) {
98 ($!) = ($!, close(NS));
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
108 ## $handle = &chat'open_proc("command","arg1","arg2",...);
109 ## opens a /bin/sh on a pseudo-tty
111 sub open_proc { ## public
115 local(*TTY) = "__TTY" . time;
116 local($pty,$tty) = &_getpty(S,TTY);
117 die "Cannot find a new pty" unless defined $pty;
119 die "Cannot fork: $!" unless defined $pid;
121 close STDIN; close STDOUT; close STDERR;
123 if (open(DEVTTY, "/dev/tty")) {
124 ioctl(DEVTTY,0x20007471,0); # XXX s/b &TIOCNOTTY
128 open(STDOUT,">&TTY");
129 open(STDERR,">&STDOUT");
130 die "Oops" unless fileno(STDERR) == 2; # sanity
133 die "Cannot exec @cmd: $!";
136 $next; # return symbol for switcharound
139 # $S is the read-ahead buffer
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.
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.
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
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. :-)
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.
168 $nextsubname = "expectloop000000"; # used for subroutines
170 sub expect { ## public
171 if ($_[0] =~ /$nextpat/) {
174 local($endtime) = shift;
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;
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));
190 select((select(S), $| = 1)[0]);
193 # now see whether we need to create a new sub:
195 unless ($subname = $expect_subname{$caller,@_}) {
196 # nope. make a new one:
197 $expect_subname{$caller,@_} = $subname = $nextsubname++;
199 $cases .= <<"EDQ"; # header is funny to make everything elsif's
205 ($pattern,$action) = splice(@_,0,2);
206 if ($pattern =~ /^eof$/i) {
214 } elsif ($pattern =~ /^timeout$/i) {
223 $pattern =~ s#/#\\/#g;
225 elsif (\$S =~ /$pattern/) {
233 $cases .= <<"EDQ" if $eof;
238 $cases .= <<"EDQ" if $timeout;
246 vec($rmask,fileno(S),1) = 1;
248 select($rmask, undef, undef, $endtime - time);
250 $nread = sysread(S, $thisbuf, 1024);
254 $eof++, redo LOOP; # any error is also eof
257 $timeout++, redo LOOP; # timeout
264 eval $cases; die "$cases:\n$@" if $@;
270 ## &chat'print([$handle,] @data)
271 ## $handle is from previous &chat'open().
272 ## like print $handle @data
274 sub print { ## public
275 if ($_[0] =~ /$nextpat/) {
279 local $out = join $, , @_;
280 syswrite(S, $out, length $out);
282 print STDERR "printed:";
287 ## &chat'close([$handle,])
288 ## $handle is from previous &chat'open().
289 ## like close $handle
291 sub close { ## public
292 if ($_[0] =~ /$nextpat/) {
296 if (defined $S{"needs_close"}) { # is it a listen socket?
297 local(*NS) = $S{"needs_close"};
298 delete $S{"needs_close"};
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).
309 sub select { ## public
310 local($timeout) = shift;
311 local(@handles) = @_;
312 local(%handlename) = ();
314 local($caller) = caller;
317 if (/$nextpat/o) { # one of ours... see if ready
320 $timeout = 0; # we have a winner
323 $handlename{fileno($_)} = $_;
325 $handlename{fileno(/'/ ? $_ : "$caller\'$_")} = $_;
328 for (sort keys %handlename) {
329 vec($rmask, $_, 1) = 1;
331 select($rmask, undef, undef, $timeout);
332 for (sort keys %handlename) {
333 $ready{$handlename{$_}}++ if vec($rmask,$_,1);
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.
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
352 $kind = "pty"; ## BSD Clist stuff
354 for $bank (112..127) {
355 next unless -e sprintf("/dev/$kind%c0", $bank);
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";