home *** CD-ROM | disk | FTP | other *** search
/ CLIX - Fazer Clix Custa Nix / CLIX-CD.cdr / mac / lib / chat2.pl < prev    next >
Text File  |  1997-05-18  |  9KB  |  361 lines

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