PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/dist/IO/lib/IO/Socket.pm

https://github.com/mauzo/perl
Perl | 540 lines | 404 code | 106 blank | 30 comment | 69 complexity | db4071e63c6632bd68cbaa814a6f8f5a MD5 | raw file
Possible License(s): AGPL-1.0
  1. # IO::Socket.pm
  2. #
  3. # Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights reserved.
  4. # 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. require 5.006;
  8. use IO::Handle;
  9. use Socket 1.3;
  10. use Carp;
  11. use strict;
  12. our(@ISA, $VERSION, @EXPORT_OK);
  13. use Exporter;
  14. use Errno;
  15. # legacy
  16. require IO::Socket::INET;
  17. require IO::Socket::UNIX if ($^O ne 'epoc' && $^O ne 'symbian');
  18. @ISA = qw(IO::Handle);
  19. $VERSION = "1.32";
  20. @EXPORT_OK = qw(sockatmark);
  21. sub import {
  22. my $pkg = shift;
  23. if (@_ && $_[0] eq 'sockatmark') { # not very extensible but for now, fast
  24. Exporter::export_to_level('IO::Socket', 1, $pkg, 'sockatmark');
  25. } else {
  26. my $callpkg = caller;
  27. Exporter::export 'Socket', $callpkg, @_;
  28. }
  29. }
  30. sub new {
  31. my($class,%arg) = @_;
  32. my $sock = $class->SUPER::new();
  33. $sock->autoflush(1);
  34. ${*$sock}{'io_socket_timeout'} = delete $arg{Timeout};
  35. return scalar(%arg) ? $sock->configure(\%arg)
  36. : $sock;
  37. }
  38. my @domain2pkg;
  39. sub register_domain {
  40. my($p,$d) = @_;
  41. $domain2pkg[$d] = $p;
  42. }
  43. sub configure {
  44. my($sock,$arg) = @_;
  45. my $domain = delete $arg->{Domain};
  46. croak 'IO::Socket: Cannot configure a generic socket'
  47. unless defined $domain;
  48. croak "IO::Socket: Unsupported socket domain"
  49. unless defined $domain2pkg[$domain];
  50. croak "IO::Socket: Cannot configure socket in domain '$domain'"
  51. unless ref($sock) eq "IO::Socket";
  52. bless($sock, $domain2pkg[$domain]);
  53. $sock->configure($arg);
  54. }
  55. sub socket {
  56. @_ == 4 or croak 'usage: $sock->socket(DOMAIN, TYPE, PROTOCOL)';
  57. my($sock,$domain,$type,$protocol) = @_;
  58. socket($sock,$domain,$type,$protocol) or
  59. return undef;
  60. ${*$sock}{'io_socket_domain'} = $domain;
  61. ${*$sock}{'io_socket_type'} = $type;
  62. ${*$sock}{'io_socket_proto'} = $protocol;
  63. $sock;
  64. }
  65. sub socketpair {
  66. @_ == 4 || croak 'usage: IO::Socket->socketpair(DOMAIN, TYPE, PROTOCOL)';
  67. my($class,$domain,$type,$protocol) = @_;
  68. my $sock1 = $class->new();
  69. my $sock2 = $class->new();
  70. socketpair($sock1,$sock2,$domain,$type,$protocol) or
  71. return ();
  72. ${*$sock1}{'io_socket_type'} = ${*$sock2}{'io_socket_type'} = $type;
  73. ${*$sock1}{'io_socket_proto'} = ${*$sock2}{'io_socket_proto'} = $protocol;
  74. ($sock1,$sock2);
  75. }
  76. sub connect {
  77. @_ == 2 or croak 'usage: $sock->connect(NAME)';
  78. my $sock = shift;
  79. my $addr = shift;
  80. my $timeout = ${*$sock}{'io_socket_timeout'};
  81. my $err;
  82. my $blocking;
  83. $blocking = $sock->blocking(0) if $timeout;
  84. if (!connect($sock, $addr)) {
  85. if (defined $timeout && ($!{EINPROGRESS} || $!{EWOULDBLOCK})) {
  86. require IO::Select;
  87. my $sel = new IO::Select $sock;
  88. undef $!;
  89. if (!$sel->can_write($timeout)) {
  90. $err = $! || (exists &Errno::ETIMEDOUT ? &Errno::ETIMEDOUT : 1);
  91. $@ = "connect: timeout";
  92. }
  93. elsif (!connect($sock,$addr) &&
  94. not ($!{EISCONN} || ($! == 10022 && $^O eq 'MSWin32'))
  95. ) {
  96. # Some systems refuse to re-connect() to
  97. # an already open socket and set errno to EISCONN.
  98. # Windows sets errno to WSAEINVAL (10022)
  99. $err = $!;
  100. $@ = "connect: $!";
  101. }
  102. }
  103. elsif ($blocking || !($!{EINPROGRESS} || $!{EWOULDBLOCK})) {
  104. $err = $!;
  105. $@ = "connect: $!";
  106. }
  107. }
  108. $sock->blocking(1) if $blocking;
  109. $! = $err if $err;
  110. $err ? undef : $sock;
  111. }
  112. # Enable/disable blocking IO on sockets.
  113. # Without args return the current status of blocking,
  114. # with args change the mode as appropriate, returning the
  115. # old setting, or in case of error during the mode change
  116. # undef.
  117. sub blocking {
  118. my $sock = shift;
  119. return $sock->SUPER::blocking(@_)
  120. if $^O ne 'MSWin32';
  121. # Windows handles blocking differently
  122. #
  123. # http://groups.google.co.uk/group/perl.perl5.porters/browse_thread/thread/b4e2b1d88280ddff/630b667a66e3509f?#630b667a66e3509f
  124. # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/ioctlsocket_2.asp
  125. #
  126. # 0x8004667e is FIONBIO
  127. #
  128. # which is used to set blocking behaviour.
  129. # NOTE:
  130. # This is a little confusing, the perl keyword for this is
  131. # 'blocking' but the OS level behaviour is 'non-blocking', probably
  132. # because sockets are blocking by default.
  133. # Therefore internally we have to reverse the semantics.
  134. my $orig= !${*$sock}{io_sock_nonblocking};
  135. return $orig unless @_;
  136. my $block = shift;
  137. if ( !$block != !$orig ) {
  138. ${*$sock}{io_sock_nonblocking} = $block ? 0 : 1;
  139. ioctl($sock, 0x8004667e, pack("L!",${*$sock}{io_sock_nonblocking}))
  140. or return undef;
  141. }
  142. return $orig;
  143. }
  144. sub close {
  145. @_ == 1 or croak 'usage: $sock->close()';
  146. my $sock = shift;
  147. ${*$sock}{'io_socket_peername'} = undef;
  148. $sock->SUPER::close();
  149. }
  150. sub bind {
  151. @_ == 2 or croak 'usage: $sock->bind(NAME)';
  152. my $sock = shift;
  153. my $addr = shift;
  154. return bind($sock, $addr) ? $sock
  155. : undef;
  156. }
  157. sub listen {
  158. @_ >= 1 && @_ <= 2 or croak 'usage: $sock->listen([QUEUE])';
  159. my($sock,$queue) = @_;
  160. $queue = 5
  161. unless $queue && $queue > 0;
  162. return listen($sock, $queue) ? $sock
  163. : undef;
  164. }
  165. sub accept {
  166. @_ == 1 || @_ == 2 or croak 'usage $sock->accept([PKG])';
  167. my $sock = shift;
  168. my $pkg = shift || $sock;
  169. my $timeout = ${*$sock}{'io_socket_timeout'};
  170. my $new = $pkg->new(Timeout => $timeout);
  171. my $peer = undef;
  172. if(defined $timeout) {
  173. require IO::Select;
  174. my $sel = new IO::Select $sock;
  175. unless ($sel->can_read($timeout)) {
  176. $@ = 'accept: timeout';
  177. $! = (exists &Errno::ETIMEDOUT ? &Errno::ETIMEDOUT : 1);
  178. return;
  179. }
  180. }
  181. $peer = accept($new,$sock)
  182. or return;
  183. return wantarray ? ($new, $peer)
  184. : $new;
  185. }
  186. sub sockname {
  187. @_ == 1 or croak 'usage: $sock->sockname()';
  188. getsockname($_[0]);
  189. }
  190. sub peername {
  191. @_ == 1 or croak 'usage: $sock->peername()';
  192. my($sock) = @_;
  193. ${*$sock}{'io_socket_peername'} ||= getpeername($sock);
  194. }
  195. sub connected {
  196. @_ == 1 or croak 'usage: $sock->connected()';
  197. my($sock) = @_;
  198. getpeername($sock);
  199. }
  200. sub send {
  201. @_ >= 2 && @_ <= 4 or croak 'usage: $sock->send(BUF, [FLAGS, [TO]])';
  202. my $sock = $_[0];
  203. my $flags = $_[2] || 0;
  204. my $peer = $_[3] || $sock->peername;
  205. croak 'send: Cannot determine peer address'
  206. unless(defined $peer);
  207. my $r = defined(getpeername($sock))
  208. ? send($sock, $_[1], $flags)
  209. : send($sock, $_[1], $flags, $peer);
  210. # remember who we send to, if it was successful
  211. ${*$sock}{'io_socket_peername'} = $peer
  212. if(@_ == 4 && defined $r);
  213. $r;
  214. }
  215. sub recv {
  216. @_ == 3 || @_ == 4 or croak 'usage: $sock->recv(BUF, LEN [, FLAGS])';
  217. my $sock = $_[0];
  218. my $len = $_[2];
  219. my $flags = $_[3] || 0;
  220. # remember who we recv'd from
  221. ${*$sock}{'io_socket_peername'} = recv($sock, $_[1]='', $len, $flags);
  222. }
  223. sub shutdown {
  224. @_ == 2 or croak 'usage: $sock->shutdown(HOW)';
  225. my($sock, $how) = @_;
  226. ${*$sock}{'io_socket_peername'} = undef;
  227. shutdown($sock, $how);
  228. }
  229. sub setsockopt {
  230. @_ == 4 or croak '$sock->setsockopt(LEVEL, OPTNAME, OPTVAL)';
  231. setsockopt($_[0],$_[1],$_[2],$_[3]);
  232. }
  233. my $intsize = length(pack("i",0));
  234. sub getsockopt {
  235. @_ == 3 or croak '$sock->getsockopt(LEVEL, OPTNAME)';
  236. my $r = getsockopt($_[0],$_[1],$_[2]);
  237. # Just a guess
  238. $r = unpack("i", $r)
  239. if(defined $r && length($r) == $intsize);
  240. $r;
  241. }
  242. sub sockopt {
  243. my $sock = shift;
  244. @_ == 1 ? $sock->getsockopt(SOL_SOCKET,@_)
  245. : $sock->setsockopt(SOL_SOCKET,@_);
  246. }
  247. sub atmark {
  248. @_ == 1 or croak 'usage: $sock->atmark()';
  249. my($sock) = @_;
  250. sockatmark($sock);
  251. }
  252. sub timeout {
  253. @_ == 1 || @_ == 2 or croak 'usage: $sock->timeout([VALUE])';
  254. my($sock,$val) = @_;
  255. my $r = ${*$sock}{'io_socket_timeout'};
  256. ${*$sock}{'io_socket_timeout'} = defined $val ? 0 + $val : $val
  257. if(@_ == 2);
  258. $r;
  259. }
  260. sub sockdomain {
  261. @_ == 1 or croak 'usage: $sock->sockdomain()';
  262. my $sock = shift;
  263. ${*$sock}{'io_socket_domain'};
  264. }
  265. sub socktype {
  266. @_ == 1 or croak 'usage: $sock->socktype()';
  267. my $sock = shift;
  268. ${*$sock}{'io_socket_type'}
  269. }
  270. sub protocol {
  271. @_ == 1 or croak 'usage: $sock->protocol()';
  272. my($sock) = @_;
  273. ${*$sock}{'io_socket_proto'};
  274. }
  275. 1;
  276. __END__
  277. =head1 NAME
  278. IO::Socket - Object interface to socket communications
  279. =head1 SYNOPSIS
  280. use IO::Socket;
  281. =head1 DESCRIPTION
  282. C<IO::Socket> provides an object interface to creating and using sockets. It
  283. is built upon the L<IO::Handle> interface and inherits all the methods defined
  284. by L<IO::Handle>.
  285. C<IO::Socket> only defines methods for those operations which are common to all
  286. types of socket. Operations which are specified to a socket in a particular
  287. domain have methods defined in sub classes of C<IO::Socket>
  288. C<IO::Socket> will export all functions (and constants) defined by L<Socket>.
  289. =head1 CONSTRUCTOR
  290. =over 4
  291. =item new ( [ARGS] )
  292. Creates an C<IO::Socket>, which is a reference to a
  293. newly created symbol (see the C<Symbol> package). C<new>
  294. optionally takes arguments, these arguments are in key-value pairs.
  295. C<new> only looks for one key C<Domain> which tells new which domain
  296. the socket will be in. All other arguments will be passed to the
  297. configuration method of the package for that domain, See below.
  298. NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
  299. As of VERSION 1.18 all IO::Socket objects have autoflush turned on
  300. by default. This was not the case with earlier releases.
  301. NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
  302. =back
  303. =head1 METHODS
  304. See L<perlfunc> for complete descriptions of each of the following
  305. supported C<IO::Socket> methods, which are just front ends for the
  306. corresponding built-in functions:
  307. socket
  308. socketpair
  309. bind
  310. listen
  311. accept
  312. send
  313. recv
  314. peername (getpeername)
  315. sockname (getsockname)
  316. shutdown
  317. Some methods take slightly different arguments to those defined in L<perlfunc>
  318. in attempt to make the interface more flexible. These are
  319. =over 4
  320. =item accept([PKG])
  321. perform the system call C<accept> on the socket and return a new
  322. object. The new object will be created in the same class as the listen
  323. socket, unless C<PKG> is specified. This object can be used to
  324. communicate with the client that was trying to connect.
  325. In a scalar context the new socket is returned, or undef upon
  326. failure. In a list context a two-element array is returned containing
  327. the new socket and the peer address; the list will be empty upon
  328. failure.
  329. The timeout in the [PKG] can be specified as zero to effect a "poll",
  330. but you shouldn't do that because a new IO::Select object will be
  331. created behind the scenes just to do the single poll. This is
  332. horrendously inefficient. Use rather true select() with a zero
  333. timeout on the handle, or non-blocking IO.
  334. =item socketpair(DOMAIN, TYPE, PROTOCOL)
  335. Call C<socketpair> and return a list of two sockets created, or an
  336. empty list on failure.
  337. =back
  338. Additional methods that are provided are:
  339. =over 4
  340. =item atmark
  341. True if the socket is currently positioned at the urgent data mark,
  342. false otherwise.
  343. use IO::Socket;
  344. my $sock = IO::Socket::INET->new('some_server');
  345. $sock->read($data, 1024) until $sock->atmark;
  346. Note: this is a reasonably new addition to the family of socket
  347. functions, so all systems may not support this yet. If it is
  348. unsupported by the system, an attempt to use this method will
  349. abort the program.
  350. The atmark() functionality is also exportable as sockatmark() function:
  351. use IO::Socket 'sockatmark';
  352. This allows for a more traditional use of sockatmark() as a procedural
  353. socket function. If your system does not support sockatmark(), the
  354. C<use> declaration will fail at compile time.
  355. =item connected
  356. If the socket is in a connected state the peer address is returned.
  357. If the socket is not in a connected state then undef will be returned.
  358. =item protocol
  359. Returns the numerical number for the protocol being used on the socket, if
  360. known. If the protocol is unknown, as with an AF_UNIX socket, zero
  361. is returned.
  362. =item sockdomain
  363. Returns the numerical number for the socket domain type. For example, for
  364. an AF_INET socket the value of &AF_INET will be returned.
  365. =item sockopt(OPT [, VAL])
  366. Unified method to both set and get options in the SOL_SOCKET level. If called
  367. with one argument then getsockopt is called, otherwise setsockopt is called.
  368. =item getsockopt(LEVEL, OPT)
  369. Get option associated with the socket. Other levels than SOL_SOCKET
  370. may be specified here.
  371. =item setsockopt(LEVEL, OPT, VAL)
  372. Set option associated with the socket. Other levels than SOL_SOCKET
  373. may be specified here.
  374. =item socktype
  375. Returns the numerical number for the socket type. For example, for
  376. a SOCK_STREAM socket the value of &SOCK_STREAM will be returned.
  377. =item timeout([VAL])
  378. Set or get the timeout value (in seconds) associated with this socket.
  379. If called without any arguments then the current setting is returned. If
  380. called with an argument the current setting is changed and the previous
  381. value returned.
  382. =back
  383. =head1 SEE ALSO
  384. L<Socket>, L<IO::Handle>, L<IO::Socket::INET>, L<IO::Socket::UNIX>
  385. =head1 AUTHOR
  386. Graham Barr. atmark() by Lincoln Stein. Currently maintained by the
  387. Perl Porters. Please report all bugs to <perl5-porters@perl.org>.
  388. =head1 COPYRIGHT
  389. Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights reserved.
  390. This program is free software; you can redistribute it and/or
  391. modify it under the same terms as Perl itself.
  392. The atmark() implementation: Copyright 2001, Lincoln Stein <lstein@cshl.org>.
  393. This module is distributed under the same terms as Perl itself.
  394. Feel free to use, modify and redistribute it as long as you retain
  395. the correct attribution.
  396. =cut