1 # chat.pl: chat with a server
2 # Based on: V2.01.alpha.7 91/06/16
3 # Randal L. Schwartz (was <merlyn@iwarp.intel.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 if( defined( &main'PF_INET ) ){
10 $pf_inet = &main'PF_INET;
11 $sock_stream = &main'SOCK_STREAM;
12 local($name, $aliases, $proto) = getprotobyname( 'tcp' );
16 # XXX hardwired $PF_INET, $SOCK_STREAM, 'tcp'
17 # but who the heck would change these anyway? (:-)
24 $sockaddr = 'S n a4 x8';
25 chop($thishost = `hostname`);
27 # *S = symbol for current I/O, gets assigned *chatsymbol....
28 $next = "chatsymbol000000"; # next one
29 $nextpat = "^chatsymbol"; # patterns that match next++, ++, ++, ++
32 ## $handle = &chat'open_port("server.address",$port_number);
33 ## opens a named or numbered TCP server
35 sub open_port { ## public
36 local($server, $port) = @_;
38 local($serveraddr,$serverproc);
40 # We may be multi-homed, start with 0, fixup once connexion is made
41 $thisaddr = "\0\0\0\0" ;
42 $thisproc = pack($sockaddr, 2, 0, $thisaddr);
45 if ($server =~ /^(\d+)+\.(\d+)\.(\d+)\.(\d+)$/) {
46 $serveraddr = pack('C4', $1, $2, $3, $4);
48 local(@x) = gethostbyname($server);
49 return undef unless @x;
52 $serverproc = pack($sockaddr, 2, $port, $serveraddr);
53 unless (socket(S, $pf_inet, $sock_stream, $tcp_proto)) {
54 ($!) = ($!, close(S)); # close S while saving $!
57 unless (bind(S, $thisproc)) {
58 ($!) = ($!, close(S)); # close S while saving $!
61 unless (connect(S, $serverproc)) {
62 ($!) = ($!, close(S)); # close S while saving $!
65 # We opened with the local address set to ANY, at this stage we know
66 # which interface we are using. This is critical if our machine is
67 # multi-homed, with IP forwarding off, so fix-up.
69 ($fam,$lport,$thisaddr) = unpack($sockaddr, getsockname(S));
70 $thisproc = pack($sockaddr, 2, 0, $thisaddr);
71 # end of post-connect fixup
72 select((select(S), $| = 1)[0]);
73 $next; # return symbol for switcharound
76 ## ($host, $port, $handle) = &chat'open_listen([$port_number]);
77 ## opens a TCP port on the current machine, ready to be listened to
78 ## if $port_number is absent or zero, pick a default port number
79 ## process must be uid 0 to listen to a low port number
81 sub open_listen { ## public
84 local($thisport) = shift || 0;
85 local($thisproc_local) = pack($sockaddr, 2, $thisport, $thisaddr);
86 local(*NS) = "__" . time;
87 unless (socket(NS, $pf_inet, $sock_stream, $tcp_proto)) {
88 ($!) = ($!, close(NS));
91 unless (bind(NS, $thisproc_local)) {
92 ($!) = ($!, close(NS));
95 unless (listen(NS, 1)) {
96 ($!) = ($!, close(NS));
99 select((select(NS), $| = 1)[0]);
100 local($family, $port, @myaddr) =
101 unpack("S n C C C C x8", getsockname(NS));
102 $S{"needs_accept"} = *NS; # so expect will open it
103 (@myaddr, $port, $next); # returning this
106 ## $handle = &chat'open_proc("command","arg1","arg2",...);
107 ## opens a /bin/sh on a pseudo-tty
109 sub open_proc { ## public
113 local(*TTY) = "__TTY" . time;
114 local($pty,$tty) = &_getpty(S,TTY);
115 die "Cannot find a new pty" unless defined $pty;
117 die "Cannot fork: $!" unless defined $pid;
119 close STDIN; close STDOUT; close STDERR;
121 if (open(DEVTTY, "/dev/tty")) {
122 ioctl(DEVTTY,0x20007471,0); # XXX s/b &TIOCNOTTY
126 open(STDOUT,">&TTY");
127 open(STDERR,">&STDOUT");
128 die "Oops" unless fileno(STDERR) == 2; # sanity
131 die "Cannot exec @cmd: $!";
134 $next; # return symbol for switcharound
137 # $S is the read-ahead buffer
139 ## $return = &chat'expect([$handle,] $timeout_time,
140 ## $pat1, $body1, $pat2, $body2, ... )
141 ## $handle is from previous &chat'open_*().
142 ## $timeout_time is the time (either relative to the current time, or
143 ## absolute, ala time(2)) at which a timeout event occurs.
144 ## $pat1, $pat2, and so on are regexs which are matched against the input
145 ## stream. If a match is found, the entire matched string is consumed,
146 ## and the corresponding body eval string is evaled.
148 ## Each pat is a regular-expression (probably enclosed in single-quotes
149 ## in the invocation). ^ and $ will work, respecting the current value of $*.
150 ## If pat is 'TIMEOUT', the body is executed if the timeout is exceeded.
151 ## If pat is 'EOF', the body is executed if the process exits before
152 ## the other patterns are seen.
154 ## Pats are scanned in the order given, so later pats can contain
155 ## general defaults that won't be examined unless the earlier pats
158 ## The result of eval'ing body is returned as the result of
159 ## the invocation. Recursive invocations are not thought
160 ## through, and may work only accidentally. :-)
162 ## undef is returned if either a timeout or an eof occurs and no
163 ## corresponding body has been defined.
164 ## I/O errors of any sort are treated as eof.
166 $nextsubname = "expectloop000000"; # used for subroutines
168 sub expect { ## public
169 if ($_[0] =~ /$nextpat/) {
172 local($endtime) = shift;
174 local($timeout,$eof) = (1,1);
175 local($caller) = caller;
176 local($rmask, $nfound, $timeleft, $thisbuf);
177 local($cases, $pattern, $action, $subname);
178 $endtime += time if $endtime < 600_000_000;
180 if (defined $S{"needs_accept"}) { # is it a listen socket?
181 local(*NS) = $S{"needs_accept"};
182 delete $S{"needs_accept"};
183 $S{"needs_close"} = *NS;
184 unless(accept(S,NS)) {
185 ($!) = ($!, close(S), close(NS));
188 select((select(S), $| = 1)[0]);
191 # now see whether we need to create a new sub:
193 unless ($subname = $expect_subname{$caller,@_}) {
194 # nope. make a new one:
195 $expect_subname{$caller,@_} = $subname = $nextsubname++;
197 $cases .= <<"EDQ"; # header is funny to make everything elsif's
203 ($pattern,$action) = splice(@_,0,2);
204 if ($pattern =~ /^eof$/i) {
212 } elsif ($pattern =~ /^timeout$/i) {
221 $pattern =~ s#/#\\/#g;
223 elsif (\$S =~ /$pattern/) {
231 $cases .= <<"EDQ" if $eof;
236 $cases .= <<"EDQ" if $timeout;
244 vec($rmask,fileno(S),1) = 1;
246 select($rmask, undef, undef, $endtime - time);
248 $nread = sysread(S, $thisbuf, 1024);
252 $eof++, redo LOOP; # any error is also eof
255 $timeout++, redo LOOP; # timeout
262 eval $cases; die "$cases:\n$@" if $@;
268 ## &chat'print([$handle,] @data)
269 ## $handle is from previous &chat'open().
270 ## like print $handle @data
272 sub print { ## public
273 if ($_[0] =~ /$nextpat/) {
278 print STDERR "printed:";
283 ## &chat'close([$handle,])
284 ## $handle is from previous &chat'open().
285 ## like close $handle
287 sub close { ## public
288 if ($_[0] =~ /$nextpat/) {
292 if (defined $S{"needs_close"}) { # is it a listen socket?
293 local(*NS) = $S{"needs_close"};
294 delete $S{"needs_close"};
299 ## @ready_handles = &chat'select($timeout, @handles)
300 ## select()'s the handles with a timeout value of $timeout seconds.
301 ## Returns an array of handles that are ready for I/O.
302 ## Both user handles and chat handles are supported (but beware of
303 ## stdio's buffering for user handles).
305 sub select { ## public
306 local($timeout) = shift;
307 local(@handles) = @_;
308 local(%handlename) = ();
310 local($caller) = caller;
313 if (/$nextpat/o) { # one of ours... see if ready
316 $timeout = 0; # we have a winner
319 $handlename{fileno($_)} = $_;
321 $handlename{fileno(/'/ ? $_ : "$caller\'$_")} = $_;
324 for (sort keys %handlename) {
325 vec($rmask, $_, 1) = 1;
327 select($rmask, undef, undef, $timeout);
328 for (sort keys %handlename) {
329 $ready{$handlename{$_}}++ if vec($rmask,$_,1);
334 # ($pty,$tty) = $chat'_getpty(PTY,TTY):
335 # internal procedure to get the next available pty.
336 # opens pty on handle PTY, and matching tty on handle TTY.
337 # returns undef if can't find a pty.
338 # Modify "/dev/pty" to "/dev/pts" for Dell Unix v2.2 (aka SVR4.04). Joe Doupnik.
340 sub _getpty { ## private
341 local($_PTY,$_TTY) = @_;
342 $_PTY =~ s/^([^']+)$/(caller)[$[]."'".$1/e;
343 $_TTY =~ s/^([^']+)$/(caller)[$[]."'".$1/e;
344 local($pty, $tty, $kind);
345 if( -e "/dev/pts000" ){ ## mods by Joe Doupnik Dec 1992
346 $kind = "pts"; ## SVR4 Streams
348 $kind = "pty"; ## BSD Clist stuff
350 for $bank (112..127) {
351 next unless -e sprintf("/dev/$kind%c0", $bank);
353 $pty = sprintf("/dev/$kind%c%c", $bank, $unit);
354 open($_PTY,"+>$pty") || next;
355 select((select($_PTY), $| = 1)[0]);
356 ($tty = $pty) =~ s/pty/tty/;
357 open($_TTY,"+>$tty") || next;
358 select((select($_TTY), $| = 1)[0]);
359 system "stty nl>$tty";