Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

728 lines
17 KiB

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