ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Socket.pm
(Generate patch)

Comparing AnyEvent/lib/AnyEvent/Socket.pm (file contents):
Revision 1.45 by root, Sat May 31 13:38:01 2008 UTC vs.
Revision 1.99 by root, Sun Jul 26 00:17:25 2009 UTC

33 33
34=cut 34=cut
35 35
36package AnyEvent::Socket; 36package AnyEvent::Socket;
37 37
38no warnings;
39use strict;
40
41use Carp (); 38use Carp ();
42use Errno (); 39use Errno ();
43use Socket qw(AF_INET AF_UNIX SOCK_STREAM SOCK_DGRAM SOL_SOCKET SO_REUSEADDR); 40use Socket qw(AF_INET AF_UNIX SOCK_STREAM SOCK_DGRAM SOL_SOCKET SO_REUSEADDR);
44 41
45use AnyEvent (); 42use AnyEvent (); BEGIN { AnyEvent::common_sense }
46use AnyEvent::Util qw(guard fh_nonblocking AF_INET6); 43use AnyEvent::Util qw(guard fh_nonblocking AF_INET6);
47use AnyEvent::DNS (); 44use AnyEvent::DNS ();
48 45
49use base 'Exporter'; 46use base 'Exporter';
50 47
51our @EXPORT = qw( 48our @EXPORT = qw(
49 getprotobyname
50 parse_hostport
52 parse_ipv4 parse_ipv6 51 parse_ipv4 parse_ipv6
53 parse_ip parse_address 52 parse_ip parse_address
53 format_ipv4 format_ipv6
54 format_ip format_address 54 format_ip format_address
55 address_family 55 address_family
56 inet_aton 56 inet_aton
57 tcp_server 57 tcp_server
58 tcp_connect 58 tcp_connect
59); 59);
60 60
61our $VERSION = 4.1; 61our $VERSION = 4.87;
62 62
63=item $ipn = parse_ipv4 $dotted_quad 63=item $ipn = parse_ipv4 $dotted_quad
64 64
65Tries to parse the given dotted quad IPv4 address and return it in 65Tries to parse the given dotted quad IPv4 address and return it in
66octet form (or undef when it isn't in a parsable format). Supports all 66octet form (or undef when it isn't in a parsable format). Supports all
78 78
79 # check leading parts against range 79 # check leading parts against range
80 return undef if grep $_ >= 256, @_[0 .. @_ - 2]; 80 return undef if grep $_ >= 256, @_[0 .. @_ - 2];
81 81
82 # check trailing part against range 82 # check trailing part against range
83 return undef if $_[-1] >= 1 << (8 * (4 - $#_)); 83 return undef if $_[-1] >= 2 ** (8 * (4 - $#_));
84 84
85 pack "N", (pop) 85 pack "N", (pop)
86 + ($_[0] << 24) 86 + ($_[0] << 24)
87 + ($_[1] << 16) 87 + ($_[1] << 16)
88 + ($_[2] << 8); 88 + ($_[2] << 8);
143 ? pack "S", AF_UNIX 143 ? pack "S", AF_UNIX
144 : undef 144 : undef
145 145
146} 146}
147 147
148=item $ipn = parse_address $text 148=item $ipn = parse_address $ip
149 149
150Combines C<parse_ipv4> and C<parse_ipv6> in one function. The address 150Combines C<parse_ipv4> and C<parse_ipv6> in one function. The address
151here refers to the host address (not socket address) in network form 151here refers to the host address (not socket address) in network form
152(binary). 152(binary).
153 153
154If the C<$text> is C<unix/>, then this function returns a special token 154If the C<$text> is C<unix/>, then this function returns a special token
155recognised by the other functions in this module to mean "UNIX domain 155recognised by the other functions in this module to mean "UNIX domain
156socket". 156socket".
157 157
158If the C<$text> to parse is a mapped IPv4 in IPv6 address (:ffff::<ipv4>),
159then it will be treated as an IPv4 address. If you don't want that, you
160have to call C<parse_ipv4> and/or C<parse_ipv6> manually.
161
162=item $ipn = AnyEvent::Socket::aton $ip
163
164Same as C<parse_address>, but not exported (think C<Socket::inet_aton> but
165I<without> name resolution).
166
158=cut 167=cut
159 168
160sub parse_address($) { 169sub parse_address($) {
161 &parse_ipv4 || &parse_ipv6 || &parse_unix 170 for (&parse_ipv6) {
171 if ($_) {
172 s/^\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff//;
173 return $_;
174 } else {
175 return &parse_ipv4 || &parse_unix
176 }
177 }
162} 178}
163 179
164*parse_ip =\&parse_address; #d# 180*aton = \&parse_address;
181
182=item ($name, $aliases, $proto) = getprotobyname $name
183
184Works like the builtin function of the same name, except it tries hard to
185work even on broken platforms (well, that's windows), where getprotobyname
186is traditionally very unreliable.
187
188=cut
189
190# microsoft can't even get getprotobyname working (the etc/protocols file
191# gets lost fairly often on windows), so we have to hardcode some common
192# protocol numbers ourselves.
193our %PROTO_BYNAME;
194
195$PROTO_BYNAME{tcp} = Socket::IPPROTO_TCP () if defined &Socket::IPPROTO_TCP;
196$PROTO_BYNAME{udp} = Socket::IPPROTO_UDP () if defined &Socket::IPPROTO_UDP;
197$PROTO_BYNAME{icmp} = Socket::IPPROTO_ICMP() if defined &Socket::IPPROTO_ICMP;
198
199sub getprotobyname($) {
200 my $name = lc shift;
201
202 defined (my $proton = $PROTO_BYNAME{$name} || (getprotobyname $name)[2])
203 or return;
204
205 ($name, uc $name, $proton)
206}
207
208=item ($host, $service) = parse_hostport $string[, $default_service]
209
210Splitting a string of the form C<hostname:port> is a common
211problem. Unfortunately, just splitting on the colon makes it hard to
212specify IPv6 addresses and doesn't support the less common but well
213standardised C<[ip literal]> syntax.
214
215This function tries to do this job in a better way, it supports the
216following formats, where C<port> can be a numerical port number of a
217service name, or a C<name=port> string, and the C< port> and C<:port>
218parts are optional. Also, everywhere where an IP address is supported
219a hostname or unix domain socket address is also supported (see
220C<parse_unix>).
221
222 hostname:port e.g. "www.linux.org", "www.x.de:443", "www.x.de:https=443"
223 ipv4:port e.g. "198.182.196.56", "127.1:22"
224 ipv6 e.g. "::1", "affe::1"
225 [ipv4or6]:port e.g. "[::1]", "[10.0.1]:80"
226 [ipv4or6] port e.g. "[127.0.0.1]", "[www.x.org] 17"
227 ipv4or6 port e.g. "::1 443", "10.0.0.1 smtp"
228
229It also supports defaulting the service name in a simple way by using
230C<$default_service> if no service was detected. If neither a service was
231detected nor a default was specified, then this function returns the
232empty list. The same happens when a parse error weas detected, such as a
233hostname with a colon in it (the function is rather conservative, though).
234
235Example:
236
237 print join ",", parse_hostport "localhost:443";
238 # => "localhost,443"
239
240 print join ",", parse_hostport "localhost", "https";
241 # => "localhost,https"
242
243 print join ",", parse_hostport "[::1]";
244 # => "," (empty list)
245
246=cut
247
248sub parse_hostport($;$) {
249 my ($host, $port);
250
251 for ("$_[0]") { # work on a copy, just in case, and also reset pos
252
253 # parse host, special cases: "ipv6" or "ipv6 port"
254 unless (
255 ($host) = /^\s* ([0-9a-fA-F:]*:[0-9a-fA-F:]*:[0-9a-fA-F\.:]*)/xgc
256 and parse_ipv6 $host
257 ) {
258 /^\s*/xgc;
259
260 if (/^ \[ ([^\[\]]+) \]/xgc) {
261 $host = $1;
262 } elsif (/^ ([^\[\]:\ ]+) /xgc) {
263 $host = $1;
264 } else {
265 return;
266 }
267 }
268
269 # parse port
270 if (/\G (?:\s+|:) ([^:[:space:]]+) \s*$/xgc) {
271 $port = $1;
272 } elsif (/\G\s*$/gc && length $_[1]) {
273 $port = $_[1];
274 } else {
275 return;
276 }
277 }
278
279 # hostnames must not contain :'s
280 return if $host =~ /:/ && !parse_ipv6 $host;
281
282 ($host, $port)
283}
165 284
166=item $sa_family = address_family $ipn 285=item $sa_family = address_family $ipn
167 286
168Returns the address family/protocol-family (AF_xxx/PF_xxx, in one value :) 287Returns the address family/protocol-family (AF_xxx/PF_xxx, in one value :)
169of the given host address in network format. 288of the given host address in network format.
176 : 16 == length $_[0] 295 : 16 == length $_[0]
177 ? AF_INET6 296 ? AF_INET6
178 : unpack "S", $_[0] 297 : unpack "S", $_[0]
179} 298}
180 299
300=item $text = format_ipv4 $ipn
301
302Expects a four octet string representing a binary IPv4 address and returns
303its textual format. Rarely used, see C<format_address> for a nicer
304interface.
305
306=item $text = format_ipv6 $ipn
307
308Expects a sixteen octet string representing a binary IPv6 address and
309returns its textual format. Rarely used, see C<format_address> for a
310nicer interface.
311
181=item $text = format_address $ipn 312=item $text = format_address $ipn
182 313
183Covnvert a host address in network format (e.g. 4 octets for IPv4 or 16 314Covnvert a host address in network format (e.g. 4 octets for IPv4 or 16
184octets for IPv6) and convert it into textual form. 315octets for IPv6) and convert it into textual form.
185 316
188This function works similarly to C<inet_ntop AF_INET || AF_INET6, ...>, 319This function works similarly to C<inet_ntop AF_INET || AF_INET6, ...>,
189except it automatically detects the address type. 320except it automatically detects the address type.
190 321
191Returns C<undef> if it cannot detect the type. 322Returns C<undef> if it cannot detect the type.
192 323
193=cut 324If the C<$ipn> is a mapped IPv4 in IPv6 address (:ffff::<ipv4>), then just
325the contained IPv4 address will be returned. If you do not want that, you
326have to call C<format_ipv6> manually.
194 327
195sub format_address; 328=item $text = AnyEvent::Socket::ntoa $ipn
329
330Same as format_address, but not exported (think C<inet_ntoa>).
331
332=cut
333
334sub format_ipv4($) {
335 join ".", unpack "C4", $_[0]
336}
337
338sub format_ipv6($) {
339 if (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0 eq $_[0]) {
340 return "::";
341 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 eq $_[0]) {
342 return "::1";
343 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0 eq substr $_[0], 0, 12) {
344 # v4compatible
345 return "::" . format_ipv4 substr $_[0], 12;
346 } elsif (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12) {
347 # v4mapped
348 return "::ffff:" . format_ipv4 substr $_[0], 12;
349 } elsif (v0.0.0.0.0.0.0.0.255.255.0.0 eq substr $_[0], 0, 12) {
350 # v4translated
351 return "::ffff:0:" . format_ipv4 substr $_[0], 12;
352 } else {
353 my $ip = sprintf "%x:%x:%x:%x:%x:%x:%x:%x", unpack "n8", $_[0];
354
355 # this is rather sucky, I admit
356 $ip =~ s/^0:(?:0:)*(0$)?/::/
357 or $ip =~ s/(:0){7}$/::/ or $ip =~ s/(:0){7}/:/
358 or $ip =~ s/(:0){6}$/::/ or $ip =~ s/(:0){6}/:/
359 or $ip =~ s/(:0){5}$/::/ or $ip =~ s/(:0){5}/:/
360 or $ip =~ s/(:0){4}$/::/ or $ip =~ s/(:0){4}/:/
361 or $ip =~ s/(:0){3}$/::/ or $ip =~ s/(:0){3}/:/
362 or $ip =~ s/(:0){2}$/::/ or $ip =~ s/(:0){2}/:/
363 or $ip =~ s/(:0){1}$/::/ or $ip =~ s/(:0){1}/:/;
364 return $ip
365 }
366}
367
196sub format_address($) { 368sub format_address($) {
197 my $af = address_family $_[0]; 369 my $af = address_family $_[0];
198 if ($af == AF_INET) { 370 if ($af == AF_INET) {
199 return join ".", unpack "C4", $_[0] 371 return &format_ipv4;
200 } elsif ($af == AF_INET6) { 372 } elsif ($af == AF_INET6) {
201 if (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0 eq $_[0]) {
202 return "::";
203 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 eq $_[0]) {
204 return "::1";
205 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0 eq substr $_[0], 0, 12) {
206 # v4compatible
207 return "::" . format_address substr $_[0], 12;
208 } elsif (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12) { 373 return (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12)
209 # v4mapped 374 ? format_ipv4 substr $_[0], 12
210 return "::ffff:" . format_address substr $_[0], 12; 375 : &format_ipv6;
211 } elsif (v0.0.0.0.0.0.0.0.255.255.0.0 eq substr $_[0], 0, 12) {
212 # v4translated
213 return "::ffff:0:" . format_address substr $_[0], 12;
214 } else {
215 my $ip = sprintf "%x:%x:%x:%x:%x:%x:%x:%x", unpack "n8", $_[0];
216
217 # this is rather sucky, I admit
218 $ip =~ s/^0:(?:0:)*(0$)?/::/
219 or $ip =~ s/(:0){7}$/::/ or $ip =~ s/(:0){7}/:/
220 or $ip =~ s/(:0){6}$/::/ or $ip =~ s/(:0){6}/:/
221 or $ip =~ s/(:0){5}$/::/ or $ip =~ s/(:0){5}/:/
222 or $ip =~ s/(:0){4}$/::/ or $ip =~ s/(:0){4}/:/
223 or $ip =~ s/(:0){3}$/::/ or $ip =~ s/(:0){3}/:/
224 or $ip =~ s/(:0){2}$/::/ or $ip =~ s/(:0){2}/:/
225 or $ip =~ s/(:0){1}$/::/ or $ip =~ s/(:0){1}/:/;
226 return $ip
227 }
228 } elsif ($af == AF_UNIX) { 376 } elsif ($af == AF_UNIX) {
229 return "unix/" 377 return "unix/"
230 } else { 378 } else {
231 return undef 379 return undef
232 } 380 }
233} 381}
234 382
235*format_ip = \&format_address; 383*ntoa = \&format_address;
236 384
237=item inet_aton $name_or_address, $cb->(@addresses) 385=item inet_aton $name_or_address, $cb->(@addresses)
238 386
239Works similarly to its Socket counterpart, except that it uses a 387Works similarly to its Socket counterpart, except that it uses a
240callback. Also, if a host has only an IPv6 address, this might be passed 388callback. Also, if a host has only an IPv6 address, this might be passed
268 } 416 }
269 }); 417 });
270 } 418 }
271} 419}
272 420
421BEGIN {
422 *sockaddr_family = $Socket::VERSION >= 1.75
423 ? \&Socket::sockaddr_family
424 : # for 5.6.x, we need to do something much more horrible
425 (Socket::pack_sockaddr_in 0x5555, "\x55\x55\x55\x55"
426 | eval { Socket::pack_sockaddr_un "U" }) =~ /^\x00/
427 ? sub { unpack "xC", $_[0] }
428 : sub { unpack "S" , $_[0] };
429}
430
273# check for broken platforms with extra field in sockaddr structure 431# check for broken platforms with extra field in sockaddr structure
274# kind of a rfc vs. bsd issue, as usual (ok, normally it's a 432# kind of a rfc vs. bsd issue, as usual (ok, normally it's a
275# unix vs. bsd issue, a iso C vs. bsd issue or simply a 433# unix vs. bsd issue, a iso C vs. bsd issue or simply a
276# correctness vs. bsd issue. 434# correctness vs. bsd issue.)
277my $pack_family = (0x55 == Socket::sockaddr_family "\x55\x55") 435my $pack_family = 0x55 == sockaddr_family ("\x55\x55")
278 ? "xC" : "S"; 436 ? "xC" : "S";
279 437
280=item $sa = AnyEvent::Socket::pack_sockaddr $service, $host 438=item $sa = AnyEvent::Socket::pack_sockaddr $service, $host
281 439
282Pack the given port/host combination into a binary sockaddr 440Pack the given port/host combination into a binary sockaddr
318module (C<format_address> converts it to C<unix/>). 476module (C<format_address> converts it to C<unix/>).
319 477
320=cut 478=cut
321 479
322sub unpack_sockaddr($) { 480sub unpack_sockaddr($) {
323 my $af = Socket::sockaddr_family $_[0]; 481 my $af = sockaddr_family $_[0];
324 482
325 if ($af == AF_INET) { 483 if ($af == AF_INET) {
326 Socket::unpack_sockaddr_in $_[0] 484 Socket::unpack_sockaddr_in $_[0]
327 } elsif ($af == AF_INET6) { 485 } elsif ($af == AF_INET6) {
328 unpack "x2 n x4 a16", $_[0] 486 unpack "x2 n x4 a16", $_[0]
356C<sctp>. The default is currently C<tcp>, but in the future, this function 514C<sctp>. The default is currently C<tcp>, but in the future, this function
357might try to use other protocols such as C<sctp>, depending on the socket 515might try to use other protocols such as C<sctp>, depending on the socket
358type and any SRV records it might find. 516type and any SRV records it might find.
359 517
360C<$family> must be either C<0> (meaning any protocol is OK), C<4> (use 518C<$family> must be either C<0> (meaning any protocol is OK), C<4> (use
361only IPv4) or C<6> (use only IPv6). This setting might be influenced by 519only IPv4) or C<6> (use only IPv6). The default is influenced by
362C<$ENV{PERL_ANYEVENT_PROTOCOLS}>. 520C<$ENV{PERL_ANYEVENT_PROTOCOLS}>.
363 521
364C<$type> must be C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_SEQPACKET> (or 522C<$type> must be C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_SEQPACKET> (or
365C<undef> in which case it gets automatically chosen). 523C<undef> in which case it gets automatically chosen to be C<SOCK_STREAM>
524unless C<$proto> is C<udp>).
366 525
367The callback will receive zero or more array references that contain 526The callback will receive zero or more array references that contain
368C<$family, $type, $proto> for use in C<socket> and a binary 527C<$family, $type, $proto> for use in C<socket> and a binary
369C<$sockaddr> for use in C<connect> (or C<bind>). 528C<$sockaddr> for use in C<connect> (or C<bind>).
370 529
378 537
379sub resolve_sockaddr($$$$$$) { 538sub resolve_sockaddr($$$$$$) {
380 my ($node, $service, $proto, $family, $type, $cb) = @_; 539 my ($node, $service, $proto, $family, $type, $cb) = @_;
381 540
382 if ($node eq "unix/") { 541 if ($node eq "unix/") {
383 return $cb->() if $family || !/^\//; # no can do 542 return $cb->() if $family || $service !~ /^\//; # no can do
384 543
385 return $cb->([AF_UNIX, $type, 0, Socket::pack_sockaddr_un $service]); 544 return $cb->([AF_UNIX, defined $type ? $type : SOCK_STREAM, 0, Socket::pack_sockaddr_un $service]);
386 } 545 }
387 546
388 unless (AF_INET6) { 547 unless (AF_INET6) {
389 $family != 6 548 $family != 6
390 or return $cb->(); 549 or return $cb->();
399 $family ||= 6 unless $AnyEvent::PROTOCOL{ipv4}; 558 $family ||= 6 unless $AnyEvent::PROTOCOL{ipv4};
400 559
401 $proto ||= "tcp"; 560 $proto ||= "tcp";
402 $type ||= $proto eq "udp" ? SOCK_DGRAM : SOCK_STREAM; 561 $type ||= $proto eq "udp" ? SOCK_DGRAM : SOCK_STREAM;
403 562
404 my $proton = (getprotobyname $proto)[2] 563 my $proton = getprotobyname $proto
405 or Carp::croak "$proto: protocol unknown"; 564 or Carp::croak "$proto: protocol unknown";
406 565
407 my $port; 566 my $port;
408 567
409 if ($service =~ /^(\S+)=(\d+)$/) { 568 if ($service =~ /^(\S+)=(\d+)$/) {
578 or die "unable to connect: $!"; 737 or die "unable to connect: $!";
579 738
580 my $handle; # avoid direct assignment so on_eof has it in scope. 739 my $handle; # avoid direct assignment so on_eof has it in scope.
581 $handle = new AnyEvent::Handle 740 $handle = new AnyEvent::Handle
582 fh => $fh, 741 fh => $fh,
742 on_error => sub {
743 warn "error $_[2]\n";
744 $_[0]->destroy;
745 },
583 on_eof => sub { 746 on_eof => sub {
584 undef $handle; # keep it alive till eof 747 $handle->destroy; # destroy handle
585 warn "done.\n"; 748 warn "done.\n";
586 }; 749 };
587 750
588 $handle->push_write ("GET / HTTP/1.0\015\012\015\012"); 751 $handle->push_write ("GET / HTTP/1.0\015\012\015\012");
589 752
621 # also http://advogato.org/article/672.html 784 # also http://advogato.org/article/672.html
622 785
623 my %state = ( fh => undef ); 786 my %state = ( fh => undef );
624 787
625 # name/service to type/sockaddr resolution 788 # name/service to type/sockaddr resolution
626 resolve_sockaddr $host, $port, 0, 0, 0, sub { 789 resolve_sockaddr $host, $port, 0, 0, undef, sub {
627 my @target = @_; 790 my @target = @_;
628 791
629 $state{next} = sub { 792 $state{next} = sub {
630 return unless exists $state{fh}; 793 return unless exists $state{fh};
631 794
632 my $target = shift @target 795 my $target = shift @target
633 or do {
634 %state = ();
635 return $connect->(); 796 or return (%state = (), $connect->());
636 };
637 797
638 my ($domain, $type, $proto, $sockaddr) = @$target; 798 my ($domain, $type, $proto, $sockaddr) = @$target;
639 799
640 # socket creation 800 # socket creation
641 socket $state{fh}, $domain, $type, $proto 801 socket $state{fh}, $domain, $type, $proto
646 my $timeout = $prepare && $prepare->($state{fh}); 806 my $timeout = $prepare && $prepare->($state{fh});
647 807
648 $timeout ||= 30 if AnyEvent::WIN32; 808 $timeout ||= 30 if AnyEvent::WIN32;
649 809
650 $state{to} = AnyEvent->timer (after => $timeout, cb => sub { 810 $state{to} = AnyEvent->timer (after => $timeout, cb => sub {
651 $! = &Errno::ETIMEDOUT; 811 $! = Errno::ETIMEDOUT;
652 $state{next}(); 812 $state{next}();
653 }) if $timeout; 813 }) if $timeout;
654 814
655 # called when the connect was successful, which, 815 # called when the connect was successful, which,
656 # in theory, could be the case immediately (but never is in practise) 816 # in theory, could be the case immediately (but never is in practise)
657 my $connected = sub { 817 $state{connected} = sub {
658 delete $state{ww};
659 delete $state{to};
660
661 # we are connected, or maybe there was an error 818 # we are connected, or maybe there was an error
662 if (my $sin = getpeername $state{fh}) { 819 if (my $sin = getpeername $state{fh}) {
663 my ($port, $host) = unpack_sockaddr $sin; 820 my ($port, $host) = unpack_sockaddr $sin;
664 821
822 delete $state{ww}; delete $state{to};
823
665 my $guard = guard { 824 my $guard = guard { %state = () };
666 %state = ();
667 };
668 825
669 $connect->($state{fh}, format_address $host, $port, sub { 826 $connect->(delete $state{fh}, format_address $host, $port, sub {
670 $guard->cancel; 827 $guard->cancel;
671 $state{next}(); 828 $state{next}();
672 }); 829 });
673 } else { 830 } else {
674 # dummy read to fetch real error code 831 # dummy read to fetch real error code
675 sysread $state{fh}, my $buf, 1 if $! == &Errno::ENOTCONN; 832 sysread $state{fh}, my $buf, 1 if $! == Errno::ENOTCONN;
833
834 return if $! == Errno::EAGAIN; # skip spurious wake-ups
835
836 delete $state{ww}; delete $state{to};
837
676 $state{next}(); 838 $state{next}();
677 } 839 }
678 }; 840 };
679 841
680 # now connect 842 # now connect
681 if (connect $state{fh}, $sockaddr) { 843 if (connect $state{fh}, $sockaddr) {
682 $connected->(); 844 $state{connected}->();
683 } elsif ($! == &Errno::EINPROGRESS # POSIX 845 } elsif ($! == Errno::EINPROGRESS # POSIX
684 || $! == &Errno::EWOULDBLOCK 846 || $! == Errno::EWOULDBLOCK
685 # WSAEINPROGRESS intentionally not checked - it means something else entirely 847 # WSAEINPROGRESS intentionally not checked - it means something else entirely
686 || $! == AnyEvent::Util::WSAEINVAL # not convinced, but doesn't hurt 848 || $! == AnyEvent::Util::WSAEINVAL # not convinced, but doesn't hurt
687 || $! == AnyEvent::Util::WSAEWOULDBLOCK) { 849 || $! == AnyEvent::Util::WSAEWOULDBLOCK) {
688 $state{ww} = AnyEvent->io (fh => $state{fh}, poll => 'w', cb => $connected); 850 $state{ww} = AnyEvent->io (fh => $state{fh}, poll => 'w', cb => $state{connected});
689 } else { 851 } else {
690 $state{next}(); 852 $state{next}();
691 } 853 }
692 }; 854 };
693 855
694 $! = &Errno::ENXIO; 856 $! = Errno::ENXIO;
695 $state{next}(); 857 $state{next}();
696 }; 858 };
697 859
698 defined wantarray && guard { %state = () } 860 defined wantarray && guard { %state = () }
699} 861}
758 }, sub { 920 }, sub {
759 my ($fh, $thishost, $thisport) = @_; 921 my ($fh, $thishost, $thisport) = @_;
760 warn "bound to $thishost, port $thisport\n"; 922 warn "bound to $thishost, port $thisport\n";
761 }; 923 };
762 924
925Example: bind a server on a unix domain socket.
926
927 tcp_server "unix/", "/tmp/mydir/mysocket", sub {
928 my ($fh) = @_;
929 };
930
763=cut 931=cut
764 932
765sub tcp_server($$$;$) { 933sub tcp_server($$$;$) {
766 my ($host, $service, $accept, $prepare) = @_; 934 my ($host, $service, $accept, $prepare) = @_;
767 935

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines