home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / IO / Socket.pm < prev   
Encoding:
Perl POD Document  |  1999-12-28  |  16.3 KB  |  695 lines

  1.  
  2. package IO::Socket;
  3.  
  4. =head1 NAME
  5.  
  6. IO::Socket - Object interface to socket communications
  7.  
  8. =head1 SYNOPSIS
  9.  
  10.     use IO::Socket;
  11.  
  12. =head1 DESCRIPTION
  13.  
  14. C<IO::Socket> provides an object interface to creating and using sockets. It
  15. is built upon the L<IO::Handle> interface and inherits all the methods defined
  16. by L<IO::Handle>.
  17.  
  18. C<IO::Socket> only defines methods for those operations which are common to all
  19. types of socket. Operations which are specified to a socket in a particular 
  20. domain have methods defined in sub classes of C<IO::Socket>
  21.  
  22. C<IO::Socket> will export all functions (and constants) defined by L<Socket>.
  23.  
  24. =head1 CONSTRUCTOR
  25.  
  26. =over 4
  27.  
  28. =item new ( [ARGS] )
  29.  
  30. Creates an C<IO::Socket>, which is a reference to a
  31. newly created symbol (see the C<Symbol> package). C<new>
  32. optionally takes arguments, these arguments are in key-value pairs.
  33. C<new> only looks for one key C<Domain> which tells new which domain
  34. the socket will be in. All other arguments will be passed to the
  35. configuration method of the package for that domain, See below.
  36.  
  37. =back
  38.  
  39. =head1 METHODS
  40.  
  41. See L<perlfunc> for complete descriptions of each of the following
  42. supported C<IO::Socket> methods, which are just front ends for the
  43. corresponding built-in functions:
  44.  
  45.     socket
  46.     socketpair
  47.     bind
  48.     listen
  49.     accept
  50.     send
  51.     recv
  52.     peername (getpeername)
  53.     sockname (getsockname)
  54.  
  55. Some methods take slightly different arguments to those defined in L<perlfunc>
  56. in attempt to make the interface more flexible. These are
  57.  
  58. =over 4
  59.  
  60. =item accept([PKG])
  61.  
  62. perform the system call C<accept> on the socket and return a new object. The
  63. new object will be created in the same class as the listen socket, unless
  64. C<PKG> is specified. This object can be used to communicate with the client
  65. that was trying to connect. In a scalar context the new socket is returned,
  66. or undef upon failure. In an array context a two-element array is returned
  67. containing the new socket and the peer address, the list will
  68. be empty upon failure.
  69.  
  70. Additional methods that are provided are
  71.  
  72. =item timeout([VAL])
  73.  
  74. Set or get the timeout value associated with this socket. If called without
  75. any arguments then the current setting is returned. If called with an argument
  76. the current setting is changed and the previous value returned.
  77.  
  78. =item sockopt(OPT [, VAL])
  79.  
  80. Unified method to both set and get options in the SOL_SOCKET level. If called
  81. with one argument then getsockopt is called, otherwise setsockopt is called.
  82.  
  83. =item sockdomain
  84.  
  85. Returns the numerical number for the socket domain type. For example, for
  86. a AF_INET socket the value of &AF_INET will be returned.
  87.  
  88. =item socktype
  89.  
  90. Returns the numerical number for the socket type. For example, for
  91. a SOCK_STREAM socket the value of &SOCK_STREAM will be returned.
  92.  
  93. =item protocol
  94.  
  95. Returns the numerical number for the protocol being used on the socket, if
  96. known. If the protocol is unknown, as with an AF_UNIX socket, zero
  97. is returned.
  98.  
  99. =back
  100.  
  101. =cut
  102.  
  103.  
  104. require 5.000;
  105.  
  106. use Config;
  107. use IO::Handle;
  108. use Socket 1.3;
  109. use Carp;
  110. use strict;
  111. use vars qw(@ISA $VERSION);
  112. use Exporter;
  113.  
  114. @ISA = qw(IO::Handle);
  115.  
  116. $VERSION = "1.1602";
  117.  
  118. sub import {
  119.     my $pkg = shift;
  120.     my $callpkg = caller;
  121.     Exporter::export 'Socket', $callpkg, @_;
  122. }
  123.  
  124. sub new {
  125.     my($class,%arg) = @_;
  126.     my $fh = $class->SUPER::new();
  127.  
  128.     ${*$fh}{'io_socket_timeout'} = delete $arg{Timeout};
  129.  
  130.     return scalar(%arg) ? $fh->configure(\%arg)
  131.             : $fh;
  132. }
  133.  
  134. my @domain2pkg = ();
  135.  
  136. sub register_domain {
  137.     my($p,$d) = @_;
  138.     $domain2pkg[$d] = $p;
  139. }
  140.  
  141. sub configure {
  142.     my($fh,$arg) = @_;
  143.     my $domain = delete $arg->{Domain};
  144.  
  145.     croak 'IO::Socket: Cannot configure a generic socket'
  146.     unless defined $domain;
  147.  
  148.     croak "IO::Socket: Unsupported socket domain"
  149.     unless defined $domain2pkg[$domain];
  150.  
  151.     croak "IO::Socket: Cannot configure socket in domain '$domain'"
  152.     unless ref($fh) eq "IO::Socket";
  153.  
  154.     bless($fh, $domain2pkg[$domain]);
  155.     $fh->configure($arg);
  156. }
  157.  
  158. sub socket {
  159.     @_ == 4 or croak 'usage: $fh->socket(DOMAIN, TYPE, PROTOCOL)';
  160.     my($fh,$domain,$type,$protocol) = @_;
  161.  
  162.     socket($fh,$domain,$type,$protocol) or
  163.         return undef;
  164.  
  165.     ${*$fh}{'io_socket_domain'} = $domain;
  166.     ${*$fh}{'io_socket_type'}   = $type;
  167.     ${*$fh}{'io_socket_proto'}  = $protocol;
  168.  
  169.     $fh;
  170. }
  171.  
  172. sub socketpair {
  173.     @_ == 4 || croak 'usage: IO::Socket->pair(DOMAIN, TYPE, PROTOCOL)';
  174.     my($class,$domain,$type,$protocol) = @_;
  175.     my $fh1 = $class->new();
  176.     my $fh2 = $class->new();
  177.  
  178.     socketpair($fh1,$fh1,$domain,$type,$protocol) or
  179.         return ();
  180.  
  181.     ${*$fh1}{'io_socket_type'}  = ${*$fh2}{'io_socket_type'}  = $type;
  182.     ${*$fh1}{'io_socket_proto'} = ${*$fh2}{'io_socket_proto'} = $protocol;
  183.  
  184.     ($fh1,$fh2);
  185. }
  186.  
  187. sub connect {
  188.     @_ == 2 || @_ == 3 or croak 'usage: $fh->connect(NAME) or $fh->connect(PORT, ADDR)';
  189.     my $fh = shift;
  190.     my $addr = @_ == 1 ? shift : sockaddr_in(@_);
  191.     my $timeout = ${*$fh}{'io_socket_timeout'};
  192.     local($SIG{ALRM}) = $timeout ? sub { undef $fh; }
  193.                  : $SIG{ALRM} || 'DEFAULT';
  194.  
  195.      eval {
  196.         croak 'connect: Bad address'
  197.             if(@_ == 2 && !defined $_[1]);
  198.  
  199.         if($timeout) {
  200.             defined $Config{d_alarm} && defined alarm($timeout) or
  201.                 $timeout = 0;
  202.         }
  203.  
  204.     my $ok = connect($fh, $addr);
  205.  
  206.         alarm(0)
  207.             if($timeout);
  208.  
  209.     croak "connect: timeout"
  210.         unless defined $fh;
  211.  
  212.     undef $fh unless $ok;
  213.     };
  214.  
  215.     $fh;
  216. }
  217.  
  218. sub bind {
  219.     @_ == 2 || @_ == 3 or croak 'usage: $fh->bind(NAME) or $fh->bind(PORT, ADDR)';
  220.     my $fh = shift;
  221.     my $addr = @_ == 1 ? shift : sockaddr_in(@_);
  222.  
  223.     return bind($fh, $addr) ? $fh
  224.                 : undef;
  225. }
  226.  
  227. sub listen {
  228.     @_ >= 1 && @_ <= 2 or croak 'usage: $fh->listen([QUEUE])';
  229.     my($fh,$queue) = @_;
  230.     $queue = 5
  231.     unless $queue && $queue > 0;
  232.  
  233.     return listen($fh, $queue) ? $fh
  234.                    : undef;
  235. }
  236.  
  237. sub accept {
  238.     @_ == 1 || @_ == 2 or croak 'usage $fh->accept([PKG])';
  239.     my $fh = shift;
  240.     my $pkg = shift || $fh;
  241.     my $timeout = ${*$fh}{'io_socket_timeout'};
  242.     my $new = $pkg->new(Timeout => $timeout);
  243.     my $peer = undef;
  244.  
  245.     eval {
  246.         if($timeout) {
  247.             my $fdset = "";
  248.             vec($fdset, $fh->fileno,1) = 1;
  249.             croak "accept: timeout"
  250.                 unless select($fdset,undef,undef,$timeout);
  251.         }
  252.         $peer = accept($new,$fh);
  253.     };
  254.  
  255.     return wantarray ? defined $peer ? ($new, $peer)
  256.                                      : () 
  257.                        : defined $peer ? $new
  258.                                      : undef;
  259. }
  260.  
  261. sub sockname {
  262.     @_ == 1 or croak 'usage: $fh->sockname()';
  263.     getsockname($_[0]);
  264. }
  265.  
  266. sub peername {
  267.     @_ == 1 or croak 'usage: $fh->peername()';
  268.     my($fh) = @_;
  269.     getpeername($fh)
  270.       || ${*$fh}{'io_socket_peername'}
  271.       || undef;
  272. }
  273.  
  274. sub send {
  275.     @_ >= 2 && @_ <= 4 or croak 'usage: $fh->send(BUF, [FLAGS, [TO]])';
  276.     my $fh    = $_[0];
  277.     my $flags = $_[2] || 0;
  278.     my $peer  = $_[3] || $fh->peername;
  279.  
  280.     croak 'send: Cannot determine peer address'
  281.      unless($peer);
  282.  
  283.     my $r = defined(getpeername($fh))
  284.     ? send($fh, $_[1], $flags)
  285.     : send($fh, $_[1], $flags, $peer);
  286.  
  287.     ${*$fh}{'io_socket_peername'} = $peer
  288.     if(@_ == 4 && defined $r);
  289.  
  290.     $r;
  291. }
  292.  
  293. sub recv {
  294.     @_ == 3 || @_ == 4 or croak 'usage: $fh->recv(BUF, LEN [, FLAGS])';
  295.     my $sock  = $_[0];
  296.     my $len   = $_[2];
  297.     my $flags = $_[3] || 0;
  298.  
  299.     ${*$sock}{'io_socket_peername'} = recv($sock, $_[1]='', $len, $flags);
  300. }
  301.  
  302.  
  303. sub setsockopt {
  304.     @_ == 4 or croak '$fh->setsockopt(LEVEL, OPTNAME)';
  305.     setsockopt($_[0],$_[1],$_[2],$_[3]);
  306. }
  307.  
  308. my $intsize = length(pack("i",0));
  309.  
  310. sub getsockopt {
  311.     @_ == 3 or croak '$fh->getsockopt(LEVEL, OPTNAME)';
  312.     my $r = getsockopt($_[0],$_[1],$_[2]);
  313.     $r = unpack("i", $r)
  314.     if(defined $r && length($r) == $intsize);
  315.     $r;
  316. }
  317.  
  318. sub sockopt {
  319.     my $fh = shift;
  320.     @_ == 1 ? $fh->getsockopt(SOL_SOCKET,@_)
  321.         : $fh->setsockopt(SOL_SOCKET,@_);
  322. }
  323.  
  324. sub timeout {
  325.     @_ == 1 || @_ == 2 or croak 'usage: $fh->timeout([VALUE])';
  326.     my($fh,$val) = @_;
  327.     my $r = ${*$fh}{'io_socket_timeout'} || undef;
  328.  
  329.     ${*$fh}{'io_socket_timeout'} = 0 + $val
  330.     if(@_ == 2);
  331.  
  332.     $r;
  333. }
  334.  
  335. sub sockdomain {
  336.     @_ == 1 or croak 'usage: $fh->sockdomain()';
  337.     my $fh = shift;
  338.     ${*$fh}{'io_socket_domain'};
  339. }
  340.  
  341. sub socktype {
  342.     @_ == 1 or croak 'usage: $fh->socktype()';
  343.     my $fh = shift;
  344.     ${*$fh}{'io_socket_type'}
  345. }
  346.  
  347. sub protocol {
  348.     @_ == 1 or croak 'usage: $fh->protocol()';
  349.     my($fh) = @_;
  350.     ${*$fh}{'io_socket_protocol'};
  351. }
  352.  
  353. =head1 SUB-CLASSES
  354.  
  355. =cut
  356.  
  357.  
  358. package IO::Socket::INET;
  359.  
  360. use strict;
  361. use vars qw(@ISA);
  362. use Socket;
  363. use Carp;
  364. use Exporter;
  365.  
  366. @ISA = qw(IO::Socket);
  367.  
  368. IO::Socket::INET->register_domain( AF_INET );
  369.  
  370. my %socket_type = ( tcp => SOCK_STREAM,
  371.             udp => SOCK_DGRAM,
  372.             icmp => SOCK_RAW,
  373.           );
  374.  
  375. =head2 IO::Socket::INET
  376.  
  377. C<IO::Socket::INET> provides a constructor to create an AF_INET domain socket
  378. and some related methods. The constructor can take the following options
  379.  
  380.     PeerAddr    Remote host address          <hostname>[:<port>]
  381.     PeerPort    Remote port or service       <service>[(<no>)] | <no>
  382.     LocalAddr    Local host bind    address      hostname[:port]
  383.     LocalPort    Local host bind    port         <service>[(<no>)] | <no>
  384.     Proto    Protocol name                "tcp" | "udp" | ...
  385.     Type    Socket type                  SOCK_STREAM | SOCK_DGRAM | ...
  386.     Listen    Queue size for listen
  387.     Reuse    Set SO_REUSEADDR before binding
  388.     Timeout    Timeout    value for various operations
  389.  
  390.  
  391. If C<Listen> is defined then a listen socket is created, else if the
  392. socket type, which is derived from the protocol, is SOCK_STREAM then
  393. connect() is called.
  394.  
  395. The C<PeerAddr> can be a hostname or the IP-address on the
  396. "xx.xx.xx.xx" form.  The C<PeerPort> can be a number or a symbolic
  397. service name.  The service name might be followed by a number in
  398. parenthesis which is used if the service is not known by the system.
  399. The C<PeerPort> specification can also be embedded in the C<PeerAddr>
  400. by preceding it with a ":".
  401.  
  402. Only one of C<Type> or C<Proto> needs to be specified, one will be
  403. assumed from the other.  If you specify a symbolic C<PeerPort> port,
  404. then the constructor will try to derive C<Type> and C<Proto> from
  405. the service name.
  406.  
  407. Examples:
  408.  
  409.    $sock = IO::Socket::INET->new(PeerAddr => 'www.perl.org',
  410.                                  PeerPort => 'http(80)',
  411.                                  Proto    => 'tcp');
  412.  
  413.    $sock = IO::Socket::INET->new(PeerAddr => 'localhost:smtp(25)');
  414.  
  415.    $sock = IO::Socket::INET->new(Listen    => 5,
  416.                                  LocalAddr => 'localhost',
  417.                                  LocalPort => 9000,
  418.                                  Proto     => 'tcp');
  419.  
  420. =head2 METHODS
  421.  
  422. =over 4
  423.  
  424. =item sockaddr ()
  425.  
  426. Return the address part of the sockaddr structure for the socket
  427.  
  428. =item sockport ()
  429.  
  430. Return the port number that the socket is using on the local host
  431.  
  432. =item sockhost ()
  433.  
  434. Return the address part of the sockaddr structure for the socket in a
  435. text form xx.xx.xx.xx
  436.  
  437. =item peeraddr ()
  438.  
  439. Return the address part of the sockaddr structure for the socket on
  440. the peer host
  441.  
  442. =item peerport ()
  443.  
  444. Return the port number for the socket on the peer host.
  445.  
  446. =item peerhost ()
  447.  
  448. Return the address part of the sockaddr structure for the socket on the
  449. peer host in a text form xx.xx.xx.xx
  450.  
  451. =back
  452.  
  453. =cut
  454.  
  455. sub _sock_info {
  456.   my($addr,$port,$proto) = @_;
  457.   my @proto = ();
  458.   my @serv = ();
  459.  
  460.   $port = $1
  461.     if(defined $addr && $addr =~ s,:([\w\(\)/]+)$,,);
  462.  
  463.   if(defined $proto) {
  464.     @proto = $proto =~ m,\D, ? getprotobyname($proto)
  465.                  : getprotobynumber($proto);
  466.  
  467.     $proto = $proto[2] || undef;
  468.   }
  469.  
  470.   if(defined $port) {
  471.     $port =~ s,\((\d+)\)$,,;
  472.  
  473.     my $defport = $1 || undef;
  474.     my $pnum = ($port =~ m,^(\d+)$,)[0];
  475.  
  476.     @serv= getservbyname($port, $proto[0] || "")
  477.     if($port =~ m,\D,);
  478.  
  479.     $port = $pnum || $serv[2] || $defport || undef;
  480.  
  481.     $proto = (getprotobyname($serv[3]))[2] || undef
  482.     if @serv && !$proto;
  483.   }
  484.  
  485.  return ($addr || undef,
  486.      $port || undef,
  487.      $proto || undef
  488.     );
  489. }
  490.  
  491. sub _error {
  492.     my $fh = shift;
  493.     $@ = join("",ref($fh),": ",@_);
  494.     carp $@ if $^W;
  495.     close($fh)
  496.     if(defined fileno($fh));
  497.     return undef;
  498. }
  499.  
  500. sub configure {
  501.     my($fh,$arg) = @_;
  502.     my($lport,$rport,$laddr,$raddr,$proto,$type);
  503.  
  504.  
  505.     ($laddr,$lport,$proto) = _sock_info($arg->{LocalAddr},
  506.                     $arg->{LocalPort},
  507.                     $arg->{Proto});
  508.  
  509.     $laddr = defined $laddr ? inet_aton($laddr)
  510.                 : INADDR_ANY;
  511.  
  512.     return _error($fh,"Bad hostname '",$arg->{LocalAddr},"'")
  513.     unless(defined $laddr);
  514.  
  515.     unless(exists $arg->{Listen}) {
  516.     ($raddr,$rport,$proto) = _sock_info($arg->{PeerAddr},
  517.                         $arg->{PeerPort},
  518.                         $proto);
  519.     }
  520.  
  521.     if(defined $raddr) {
  522.     $raddr = inet_aton($raddr);
  523.     return _error($fh,"Bad hostname '",$arg->{PeerAddr},"'")
  524.         unless(defined $raddr);
  525.     }
  526.  
  527.     return _error($fh,'Cannot determine protocol')
  528.     unless($proto);
  529.  
  530.     my $pname = (getprotobynumber($proto))[0];
  531.     $type = $arg->{Type} || $socket_type{$pname};
  532.  
  533.     $fh->socket(AF_INET, $type, $proto) or
  534.     return _error($fh,"$!");
  535.  
  536.     if ($arg->{Reuse}) {
  537.     $fh->sockopt(SO_REUSEADDR,1) or
  538.         return _error($fh);
  539.     }
  540.  
  541.     $fh->bind($lport || 0, $laddr) or
  542.     return _error($fh,"$!");
  543.  
  544.     if(exists $arg->{Listen}) {
  545.     $fh->listen($arg->{Listen} || 5) or
  546.         return _error($fh,"$!");
  547.     }
  548.     else {
  549.     return _error($fh,'Cannot determine remote port')
  550.         unless($rport || $type == SOCK_DGRAM || $type == SOCK_RAW);
  551.  
  552.     if($type == SOCK_STREAM || defined $raddr) {
  553.         return _error($fh,'Bad peer address')
  554.             unless(defined $raddr);
  555.  
  556.         $fh->connect($rport,$raddr) or
  557.         return _error($fh,"$!");
  558.     }
  559.     }
  560.  
  561.     $fh;
  562. }
  563.  
  564. sub sockaddr {
  565.     @_ == 1 or croak 'usage: $fh->sockaddr()';
  566.     my($fh) = @_;
  567.     (sockaddr_in($fh->sockname))[1];
  568. }
  569.  
  570. sub sockport {
  571.     @_ == 1 or croak 'usage: $fh->sockport()';
  572.     my($fh) = @_;
  573.     (sockaddr_in($fh->sockname))[0];
  574. }
  575.  
  576. sub sockhost {
  577.     @_ == 1 or croak 'usage: $fh->sockhost()';
  578.     my($fh) = @_;
  579.     inet_ntoa($fh->sockaddr);
  580. }
  581.  
  582. sub peeraddr {
  583.     @_ == 1 or croak 'usage: $fh->peeraddr()';
  584.     my($fh) = @_;
  585.     (sockaddr_in($fh->peername))[1];
  586. }
  587.  
  588. sub peerport {
  589.     @_ == 1 or croak 'usage: $fh->peerport()';
  590.     my($fh) = @_;
  591.     (sockaddr_in($fh->peername))[0];
  592. }
  593.  
  594. sub peerhost {
  595.     @_ == 1 or croak 'usage: $fh->peerhost()';
  596.     my($fh) = @_;
  597.     inet_ntoa($fh->peeraddr);
  598. }
  599.  
  600.  
  601. package IO::Socket::UNIX;
  602.  
  603. use strict;
  604. use vars qw(@ISA $VERSION);
  605. use Socket;
  606. use Carp;
  607. use Exporter;
  608.  
  609. @ISA = qw(IO::Socket);
  610.  
  611. IO::Socket::UNIX->register_domain( AF_UNIX );
  612.  
  613. =head2 IO::Socket::UNIX
  614.  
  615. C<IO::Socket::UNIX> provides a constructor to create an AF_UNIX domain socket
  616. and some related methods. The constructor can take the following options
  617.  
  618.     Type        Type of socket (eg SOCK_STREAM or SOCK_DGRAM)
  619.     Local       Path to local fifo
  620.     Peer        Path to peer fifo
  621.     Listen      Create a listen socket
  622.  
  623. =head2 METHODS
  624.  
  625. =over 4
  626.  
  627. =item hostpath()
  628.  
  629. Returns the pathname to the fifo at the local end
  630.  
  631. =item peerpath()
  632.  
  633. Returns the pathanme to the fifo at the peer end
  634.  
  635. =back
  636.  
  637. =cut
  638.  
  639. sub configure {
  640.     my($fh,$arg) = @_;
  641.     my($bport,$cport);
  642.  
  643.     my $type = $arg->{Type} || SOCK_STREAM;
  644.  
  645.     $fh->socket(AF_UNIX, $type, 0) or
  646.     return undef;
  647.  
  648.     if(exists $arg->{Local}) {
  649.     my $addr = sockaddr_un($arg->{Local});
  650.     $fh->bind($addr) or
  651.         return undef;
  652.     }
  653.     if(exists $arg->{Listen}) {
  654.     $fh->listen($arg->{Listen} || 5) or
  655.         return undef;
  656.     }
  657.     elsif(exists $arg->{Peer}) {
  658.     my $addr = sockaddr_un($arg->{Peer});
  659.     $fh->connect($addr) or
  660.         return undef;
  661.     }
  662.  
  663.     $fh;
  664. }
  665.  
  666. sub hostpath {
  667.     @_ == 1 or croak 'usage: $fh->hostpath()';
  668.     my $n = $_[0]->sockname || return undef;
  669.     (sockaddr_un($n))[0];
  670. }
  671.  
  672. sub peerpath {
  673.     @_ == 1 or croak 'usage: $fh->peerpath()';
  674.     my $n = $_[0]->peername || return undef;
  675.     (sockaddr_un($n))[0];
  676. }
  677.  
  678. =head1 SEE ALSO
  679.  
  680. L<Socket>, L<IO::Handle>
  681.  
  682. =head1 AUTHOR
  683.  
  684. Graham Barr E<lt>F<Graham.Barr@tiuk.ti.com>E<gt>
  685.  
  686. =head1 COPYRIGHT
  687.  
  688. Copyright (c) 1996 Graham Barr. All rights reserved. This program is free
  689. software; you can redistribute it and/or modify it under the same terms
  690. as Perl itself.
  691.  
  692. =cut
  693.  
  694. 1; # Keep require happy
  695.