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.36 by root, Wed May 28 21:29:03 2008 UTC vs.
Revision 1.83 by root, Mon Jun 29 21:00:32 2009 UTC

2 2
3AnyEvent::Socket - useful IPv4 and IPv6 stuff. 3AnyEvent::Socket - useful IPv4 and IPv6 stuff.
4 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent::Socket; 7 use AnyEvent::Socket;
8 8
9 tcp_connect "gameserver.deliantra.net", 13327, sub { 9 tcp_connect "gameserver.deliantra.net", 13327, sub {
10 my ($fh) = @_ 10 my ($fh) = @_
11 or die "gameserver.deliantra.net connect failed: $!"; 11 or die "gameserver.deliantra.net connect failed: $!";
12 12
13 # enjoy your filehandle 13 # enjoy your filehandle
14 }; 14 };
15 15
16 # a simple tcp server 16 # a simple tcp server
17 tcp_server undef, 8888, sub { 17 tcp_server undef, 8888, sub {
18 my ($fh, $host, $port) = @_; 18 my ($fh, $host, $port) = @_;
19 19
20 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012"; 20 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
21 }; 21 };
22 22
23=head1 DESCRIPTION 23=head1 DESCRIPTION
24 24
25This module implements various utility functions for handling internet 25This module implements various utility functions for handling internet
26protocol addresses and sockets, in an as transparent and simple way as 26protocol addresses and sockets, in an as transparent and simple way as
47use AnyEvent::DNS (); 47use AnyEvent::DNS ();
48 48
49use base 'Exporter'; 49use base 'Exporter';
50 50
51our @EXPORT = qw( 51our @EXPORT = qw(
52 parse_hostport
52 parse_ipv4 parse_ipv6 53 parse_ipv4 parse_ipv6
53 parse_ip parse_address 54 parse_ip parse_address
54 format_ip format_address 55 format_ip format_address
55 address_family 56 address_family
56 inet_aton 57 inet_aton
57 tcp_server 58 tcp_server
58 tcp_connect 59 tcp_connect
59); 60);
60 61
61our $VERSION = '1.0'; 62our $VERSION = 4.45;
62 63
63=item $ipn = parse_ipv4 $dotted_quad 64=item $ipn = parse_ipv4 $dotted_quad
64 65
65Tries to parse the given dotted quad IPv4 address and return it in 66Tries 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 67octet form (or undef when it isn't in a parsable format). Supports all
78 79
79 # check leading parts against range 80 # check leading parts against range
80 return undef if grep $_ >= 256, @_[0 .. @_ - 2]; 81 return undef if grep $_ >= 256, @_[0 .. @_ - 2];
81 82
82 # check trailing part against range 83 # check trailing part against range
83 return undef if $_[-1] >= 1 << (8 * (4 - $#_)); 84 return undef if $_[-1] >= 2 ** (8 * (4 - $#_));
84 85
85 pack "N", (pop) 86 pack "N", (pop)
86 + ($_[0] << 24) 87 + ($_[0] << 24)
87 + ($_[1] << 16) 88 + ($_[1] << 16)
88 + ($_[2] << 8); 89 + ($_[2] << 8);
143 ? pack "S", AF_UNIX 144 ? pack "S", AF_UNIX
144 : undef 145 : undef
145 146
146} 147}
147 148
148=item $ipn = parse_address $text 149=item $ipn = parse_address $ip
149 150
150Combines C<parse_ipv4> and C<parse_ipv6> in one function. The address 151Combines C<parse_ipv4> and C<parse_ipv6> in one function. The address
151here refers to the host address (not socket address) in network form 152here refers to the host address (not socket address) in network form
152(binary). 153(binary).
153 154
154If the C<$text> is C<unix/>, then this function returns a special token 155If 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 156recognised by the other functions in this module to mean "UNIX domain
156socket". 157socket".
157 158
159If the C<$text> to parse is a mapped IPv4 in IPv6 address (:ffff::<ipv4>),
160then it will be treated as an IPv4 address. If you don't want that, you
161have to call C<parse_ipv4> and/or C<parse_ipv6> manually.
162
163=item $ipn = AnyEvent::Socket::aton $ip
164
165Same as C<parse_address>, but not exported (think C<Socket::inet_aton> but
166I<without> name resolution).
167
158=cut 168=cut
159 169
160sub parse_address($) { 170sub parse_address($) {
161 &parse_ipv4 || &parse_ipv6 || &parse_unix 171 for (&parse_ipv6) {
172 if ($_) {
173 s/^\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff//;
174 return $_;
175 } else {
176 return &parse_ipv4 || &parse_unix
177 }
178 }
162} 179}
163 180
164*parse_ip =\&parse_address; #d# 181*aton = \&parse_address;
182
183=item ($host, $service) = parse_hostport $string[, $default_service]
184
185Splitting a string of the form C<hostname:port> is a common
186problem. Unfortunately, just splitting on the colon makes it hard to
187specify IPv6 addresses and doesn't support the less common but well
188standardised C<[ip literal]> syntax.
189
190This function tries to do this job in a better way, it supports the
191following formats, where C<port> can be a numerical port number of a
192service name, or a C<name=port> string, and the C< port> and C<:port>
193parts are optional. Also, everywhere where an IP address is supported
194a hostname or unix domain socket address is also supported (see
195C<parse_unix>).
196
197 hostname:port e.g. "www.linux.org", "www.x.de:443", "www.x.de:https=443"
198 ipv4:port e.g. "198.182.196.56", "127.1:22"
199 ipv6 e.g. "::1", "affe::1"
200 [ipv4or6]:port e.g. "[::1]", "[10.0.1]:80"
201 [ipv4or6] port e.g. "[127.0.0.1]", "[www.x.org] 17"
202 ipv4or6 port e.g. "::1 443", "10.0.0.1 smtp"
203
204It also supports defaulting the service name in a simple way by using
205C<$default_service> if no service was detected. If neither a service was
206detected nor a default was specified, then this function returns the
207empty list. The same happens when a parse error weas detected, such as a
208hostname with a colon in it (the function is rather conservative, though).
209
210Example:
211
212 print join ",", parse_hostport "localhost:443";
213 # => "localhost,443"
214
215 print join ",", parse_hostport "localhost", "https";
216 # => "localhost,https"
217
218 print join ",", parse_hostport "[::1]";
219 # => "," (empty list)
220
221=cut
222
223sub parse_hostport($;$) {
224 my ($host, $port);
225
226 for ("$_[0]") { # work on a copy, just in case, and also reset pos
227
228 # parse host, special cases: "ipv6" or "ipv6 port"
229 unless (
230 ($host) = /^\s* ([0-9a-fA-F:]*:[0-9a-fA-F:]*:[0-9a-fA-F\.:]*)/xgc
231 and parse_ipv6 $host
232 ) {
233 /^\s*/xgc;
234
235 if (/^ \[ ([^\[\]]+) \]/xgc) {
236 $host = $1;
237 } elsif (/^ ([^\[\]:\ ]+) /xgc) {
238 $host = $1;
239 } else {
240 return;
241 }
242 }
243
244 # parse port
245 if (/\G (?:\s+|:) ([^:[:space:]]+) \s*$/xgc) {
246 $port = $1;
247 } elsif (/\G\s*$/gc && length $_[1]) {
248 $port = $_[1];
249 } else {
250 return;
251 }
252 }
253
254 # hostnames must not contain :'s
255 return if $host =~ /:/ && !parse_ipv6 $host;
256
257 ($host, $port)
258}
165 259
166=item $sa_family = address_family $ipn 260=item $sa_family = address_family $ipn
167 261
168Returns the address family/protocol-family (AF_xxx/PF_xxx, in one value :) 262Returns the address family/protocol-family (AF_xxx/PF_xxx, in one value :)
169of the given host address in network format. 263of the given host address in network format.
176 : 16 == length $_[0] 270 : 16 == length $_[0]
177 ? AF_INET6 271 ? AF_INET6
178 : unpack "S", $_[0] 272 : unpack "S", $_[0]
179} 273}
180 274
275=item $text = format_ipv4 $ipn
276
277Expects a four octet string representing a binary IPv4 address and returns
278its textual format. Rarely used, see C<format_address> for a nicer
279interface.
280
281=item $text = format_ipv6 $ipn
282
283Expects a sixteen octet string representing a binary IPv6 address and
284returns its textual format. Rarely used, see C<format_address> for a
285nicer interface.
286
181=item $text = format_address $ipn 287=item $text = format_address $ipn
182 288
183Covnvert a host address in network format (e.g. 4 octets for IPv4 or 16 289Covnvert a host address in network format (e.g. 4 octets for IPv4 or 16
184octets for IPv6) and convert it into textual form. 290octets for IPv6) and convert it into textual form.
185 291
188This function works similarly to C<inet_ntop AF_INET || AF_INET6, ...>, 294This function works similarly to C<inet_ntop AF_INET || AF_INET6, ...>,
189except it automatically detects the address type. 295except it automatically detects the address type.
190 296
191Returns C<undef> if it cannot detect the type. 297Returns C<undef> if it cannot detect the type.
192 298
193=cut 299If the C<$ipn> is a mapped IPv4 in IPv6 address (:ffff::<ipv4>), then just
300the contained IPv4 address will be returned. If you do not want that, you
301have to call C<format_ipv6> manually.
194 302
195sub format_address; 303=item $text = AnyEvent::Socket::ntoa $ipn
304
305Same as format_address, but not exported (think C<inet_ntoa>).
306
307=cut
308
309sub format_ipv4($) {
310 join ".", unpack "C4", $_[0]
311}
312
313sub format_ipv6($) {
314 if (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0 eq $_[0]) {
315 return "::";
316 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 eq $_[0]) {
317 return "::1";
318 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0 eq substr $_[0], 0, 12) {
319 # v4compatible
320 return "::" . format_ipv4 substr $_[0], 12;
321 } elsif (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12) {
322 # v4mapped
323 return "::ffff:" . format_ipv4 substr $_[0], 12;
324 } elsif (v0.0.0.0.0.0.0.0.255.255.0.0 eq substr $_[0], 0, 12) {
325 # v4translated
326 return "::ffff:0:" . format_ipv4 substr $_[0], 12;
327 } else {
328 my $ip = sprintf "%x:%x:%x:%x:%x:%x:%x:%x", unpack "n8", $_[0];
329
330 # this is rather sucky, I admit
331 $ip =~ s/^0:(?:0:)*(0$)?/::/
332 or $ip =~ s/(:0){7}$/::/ or $ip =~ s/(:0){7}/:/
333 or $ip =~ s/(:0){6}$/::/ or $ip =~ s/(:0){6}/:/
334 or $ip =~ s/(:0){5}$/::/ or $ip =~ s/(:0){5}/:/
335 or $ip =~ s/(:0){4}$/::/ or $ip =~ s/(:0){4}/:/
336 or $ip =~ s/(:0){3}$/::/ or $ip =~ s/(:0){3}/:/
337 or $ip =~ s/(:0){2}$/::/ or $ip =~ s/(:0){2}/:/
338 or $ip =~ s/(:0){1}$/::/ or $ip =~ s/(:0){1}/:/;
339 return $ip
340 }
341}
342
196sub format_address($) { 343sub format_address($) {
197 my $af = address_family $_[0]; 344 my $af = address_family $_[0];
198 if ($af == AF_INET) { 345 if ($af == AF_INET) {
199 return join ".", unpack "C4", $_[0] 346 return &format_ipv4;
200 } elsif ($af == AF_INET6) { 347 } elsif ($af == AF_INET6) {
201 if (v0.0.0.0.0.0.0.0.0.0.0.0 eq substr $_[0], 0, 12) {
202 # v4compatible
203 return "::" . format_address substr $_[0], 12;
204 } elsif (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12) { 348 return (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12)
205 # v4mapped 349 ? format_ipv4 substr $_[0], 12
206 return "::ffff:" . format_address substr $_[0], 12; 350 : &format_ipv6;
207 } elsif (v0.0.0.0.0.0.0.0.255.255.0.0 eq substr $_[0], 0, 12) {
208 # v4translated
209 return "::ffff:0:" . format_address substr $_[0], 12;
210 } else {
211 my $ip = sprintf "%x:%x:%x:%x:%x:%x:%x:%x", unpack "n8", $_[0];
212
213 $ip =~ s/^0:(?:0:)*(0$)?/::/
214 or $ip =~ s/(:0)+$/::/
215 or $ip =~ s/(:0)+/:/;
216 return $ip
217 }
218 } elsif ($af == AF_UNIX) { 351 } elsif ($af == AF_UNIX) {
219 return "unix/" 352 return "unix/"
220 } else { 353 } else {
221 return undef 354 return undef
222 } 355 }
223} 356}
224 357
225*format_ip = \&format_address; 358*ntoa = \&format_address;
226 359
227=item inet_aton $name_or_address, $cb->(@addresses) 360=item inet_aton $name_or_address, $cb->(@addresses)
228 361
229Works similarly to its Socket counterpart, except that it uses a 362Works similarly to its Socket counterpart, except that it uses a
230callback. Also, if a host has only an IPv6 address, this might be passed 363callback. Also, if a host has only an IPv6 address, this might be passed
262 395
263# check for broken platforms with extra field in sockaddr structure 396# check for broken platforms with extra field in sockaddr structure
264# kind of a rfc vs. bsd issue, as usual (ok, normally it's a 397# kind of a rfc vs. bsd issue, as usual (ok, normally it's a
265# unix vs. bsd issue, a iso C vs. bsd issue or simply a 398# unix vs. bsd issue, a iso C vs. bsd issue or simply a
266# correctness vs. bsd issue. 399# correctness vs. bsd issue.
267my $pack_family = 0x55 == Socket::sockaddr_family "\x55\x55" 400my $pack_family = (0x55 == Socket::sockaddr_family "\x55\x55")
268 ? "xC" : "S"; 401 ? "xC" : "S";
269 402
270=item $sa = AnyEvent::Socket::pack_sockaddr $service, $host 403=item $sa = AnyEvent::Socket::pack_sockaddr $service, $host
271 404
272Pack the given port/host combination into a binary sockaddr 405Pack the given port/host combination into a binary sockaddr
346C<sctp>. The default is currently C<tcp>, but in the future, this function 479C<sctp>. The default is currently C<tcp>, but in the future, this function
347might try to use other protocols such as C<sctp>, depending on the socket 480might try to use other protocols such as C<sctp>, depending on the socket
348type and any SRV records it might find. 481type and any SRV records it might find.
349 482
350C<$family> must be either C<0> (meaning any protocol is OK), C<4> (use 483C<$family> must be either C<0> (meaning any protocol is OK), C<4> (use
351only IPv4) or C<6> (use only IPv6). This setting might be influenced by 484only IPv4) or C<6> (use only IPv6). The default is influenced by
352C<$ENV{PERL_ANYEVENT_PROTOCOLS}>. 485C<$ENV{PERL_ANYEVENT_PROTOCOLS}>.
353 486
354C<$type> must be C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_SEQPACKET> (or 487C<$type> must be C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_SEQPACKET> (or
355C<undef> in which case it gets automatically chosen). 488C<undef> in which case it gets automatically chosen to be C<SOCK_STREAM>
489unless C<$proto> is C<udp>).
356 490
357The callback will receive zero or more array references that contain 491The callback will receive zero or more array references that contain
358C<$family, $type, $proto> for use in C<socket> and a binary 492C<$family, $type, $proto> for use in C<socket> and a binary
359C<$sockaddr> for use in C<connect> (or C<bind>). 493C<$sockaddr> for use in C<connect> (or C<bind>).
360 494
364 498
365 resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... }; 499 resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... };
366 500
367=cut 501=cut
368 502
503# microsoft can't even get getprotobyname working (the etc/protocols file
504# gets lost fairly often on windows), so we have to hardcode some common
505# protocol numbers ourselves.
506our %PROTO_BYNAME;
507
508$PROTO_BYNAME{tcp} = &Socket::IPPROTO_TCP if defined &Socket::IPPROTO_TCP;
509$PROTO_BYNAME{udp} = &Socket::IPPROTO_UDP if defined &Socket::IPPROTO_UDP;
510$PROTO_BYNAME{icmp} = &Socket::IPPROTO_ICMP if defined &Socket::IPPROTO_ICMP;
511
369sub resolve_sockaddr($$$$$$) { 512sub resolve_sockaddr($$$$$$) {
370 my ($node, $service, $proto, $family, $type, $cb) = @_; 513 my ($node, $service, $proto, $family, $type, $cb) = @_;
371 514
372 if ($node eq "unix/") { 515 if ($node eq "unix/") {
373 return $cb->() if $family || !/^\//; # no can do 516 return $cb->() if $family || $service !~ /^\//; # no can do
374 517
375 return $cb->([AF_UNIX, $type, 0, Socket::pack_sockaddr_un $service]); 518 return $cb->([AF_UNIX, defined $type ? $type : SOCK_STREAM, 0, Socket::pack_sockaddr_un $service]);
376 } 519 }
377 520
378 unless (AF_INET6) { 521 unless (AF_INET6) {
379 $family != 6 522 $family != 6
380 or return $cb->(); 523 or return $cb->();
389 $family ||= 6 unless $AnyEvent::PROTOCOL{ipv4}; 532 $family ||= 6 unless $AnyEvent::PROTOCOL{ipv4};
390 533
391 $proto ||= "tcp"; 534 $proto ||= "tcp";
392 $type ||= $proto eq "udp" ? SOCK_DGRAM : SOCK_STREAM; 535 $type ||= $proto eq "udp" ? SOCK_DGRAM : SOCK_STREAM;
393 536
394 my $proton = (getprotobyname $proto)[2] 537 my $proton = $PROTO_BYNAME{lc $proto} || (getprotobyname $proto)[2]
395 or Carp::croak "$proto: protocol unknown"; 538 or Carp::croak "$proto: protocol unknown";
396 539
397 my $port; 540 my $port;
398 541
399 if ($service =~ /^(\S+)=(\d+)$/) { 542 if ($service =~ /^(\S+)=(\d+)$/) {
424 $cv->begin; 567 $cv->begin;
425 for my $idx (0 .. $#target) { 568 for my $idx (0 .. $#target) {
426 my ($node, $port) = @{ $target[$idx] }; 569 my ($node, $port) = @{ $target[$idx] };
427 570
428 if (my $noden = parse_address $node) { 571 if (my $noden = parse_address $node) {
572 my $af = address_family $noden;
573
429 if (4 == length $noden && $family != 6) { 574 if ($af == AF_INET && $family != 6) {
430 push @res, [$idx, "ipv4", [AF_INET, $type, $proton, 575 push @res, [$idx, "ipv4", [AF_INET, $type, $proton,
431 pack_sockaddr $port, $noden]] 576 pack_sockaddr $port, $noden]]
432 } 577 }
433 578
434 if (16 == length $noden && $family != 4) { 579 if ($af == AF_INET6 && $family != 4) {
435 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton, 580 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton,
436 pack_sockaddr $port, $noden]] 581 pack_sockaddr $port, $noden]]
437 } 582 }
438 } else { 583 } else {
439 # ipv4 584 # ipv4
440 if ($family != 6) { 585 if ($family != 6) {
441 $cv->begin; 586 $cv->begin;
442 a $node, sub { 587 AnyEvent::DNS::a $node, sub {
443 push @res, [$idx, "ipv4", [AF_INET, $type, $proton, 588 push @res, [$idx, "ipv4", [AF_INET, $type, $proton,
444 pack_sockaddr $port, parse_ipv4 $_]] 589 pack_sockaddr $port, parse_ipv4 $_]]
445 for @_; 590 for @_;
446 $cv->end; 591 $cv->end;
447 }; 592 };
448 } 593 }
449 594
450 # ipv6 595 # ipv6
451 if ($family != 4) { 596 if ($family != 4) {
452 $cv->begin; 597 $cv->begin;
453 aaaa $node, sub { 598 AnyEvent::DNS::aaaa $node, sub {
454 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton, 599 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton,
455 pack_sockaddr $port, parse_ipv6 $_]] 600 pack_sockaddr $port, parse_ipv6 $_]]
456 for @_; 601 for @_;
457 $cv->end; 602 $cv->end;
458 }; 603 };
465 # try srv records, if applicable 610 # try srv records, if applicable
466 if ($node eq "localhost") { 611 if ($node eq "localhost") {
467 @target = (["127.0.0.1", $port], ["::1", $port]); 612 @target = (["127.0.0.1", $port], ["::1", $port]);
468 &$resolve; 613 &$resolve;
469 } elsif (defined $service && !parse_address $node) { 614 } elsif (defined $service && !parse_address $node) {
470 srv $service, $proto, $node, sub { 615 AnyEvent::DNS::srv $service, $proto, $node, sub {
471 my (@srv) = @_; 616 my (@srv) = @_;
472 617
473 # no srv records, continue traditionally 618 # no srv records, continue traditionally
474 @srv 619 @srv
475 or return &$resolve; 620 or return &$resolve;
476 621
477 # only srv record has "." => abort 622 # the only srv record has "." ("" here) => abort
478 $srv[0][2] ne "." || $#srv 623 $srv[0][2] ne "" || $#srv
479 or return $cb->(); 624 or return $cb->();
480 625
481 # use srv records then 626 # use srv records then
482 @target = map ["$_->[3].", $_->[2]], 627 @target = map ["$_->[3].", $_->[2]],
483 grep $_->[3] ne ".", 628 grep $_->[3] ne ".",
548lessen the impact of this windows bug, a default timeout of 30 seconds 693lessen the impact of this windows bug, a default timeout of 30 seconds
549will be imposed on windows. Cygwin is not affected. 694will be imposed on windows. Cygwin is not affected.
550 695
551Simple Example: connect to localhost on port 22. 696Simple Example: connect to localhost on port 22.
552 697
553 tcp_connect localhost => 22, sub { 698 tcp_connect localhost => 22, sub {
554 my $fh = shift 699 my $fh = shift
555 or die "unable to connect: $!"; 700 or die "unable to connect: $!";
556 # do something 701 # do something
557 }; 702 };
558 703
559Complex Example: connect to www.google.com on port 80 and make a simple 704Complex Example: connect to www.google.com on port 80 and make a simple
560GET request without much error handling. Also limit the connection timeout 705GET request without much error handling. Also limit the connection timeout
561to 15 seconds. 706to 15 seconds.
562 707
609 # also http://advogato.org/article/672.html 754 # also http://advogato.org/article/672.html
610 755
611 my %state = ( fh => undef ); 756 my %state = ( fh => undef );
612 757
613 # name/service to type/sockaddr resolution 758 # name/service to type/sockaddr resolution
614 resolve_sockaddr $host, $port, 0, 0, 0, sub { 759 resolve_sockaddr $host, $port, 0, 0, undef, sub {
615 my @target = @_; 760 my @target = @_;
616 761
617 $state{next} = sub { 762 $state{next} = sub {
618 return unless exists $state{fh}; 763 return unless exists $state{fh};
619 764
640 $state{next}(); 785 $state{next}();
641 }) if $timeout; 786 }) if $timeout;
642 787
643 # called when the connect was successful, which, 788 # called when the connect was successful, which,
644 # in theory, could be the case immediately (but never is in practise) 789 # in theory, could be the case immediately (but never is in practise)
645 my $connected = sub { 790 $state{connected} = sub {
646 delete $state{ww}; 791 delete $state{ww};
647 delete $state{to}; 792 delete $state{to};
648 793
649 # we are connected, or maybe there was an error 794 # we are connected, or maybe there was an error
650 if (my $sin = getpeername $state{fh}) { 795 if (my $sin = getpeername $state{fh}) {
651 my ($port, $host) = unpack_sockaddr $sin; 796 my ($port, $host) = unpack_sockaddr $sin;
652 797
653 my $guard = guard { 798 my $guard = guard { %state = () };
654 %state = ();
655 };
656 799
657 $connect->($state{fh}, format_address $host, $port, sub { 800 $connect->(delete $state{fh}, format_address $host, $port, sub {
658 $guard->cancel; 801 $guard->cancel;
659 $state{next}(); 802 $state{next}();
660 }); 803 });
661 } else { 804 } else {
662 # dummy read to fetch real error code 805 # dummy read to fetch real error code
665 } 808 }
666 }; 809 };
667 810
668 # now connect 811 # now connect
669 if (connect $state{fh}, $sockaddr) { 812 if (connect $state{fh}, $sockaddr) {
670 $connected->(); 813 $state{connected}->();
671 } elsif ($! == &Errno::EINPROGRESS # POSIX 814 } elsif ($! == &Errno::EINPROGRESS # POSIX
672 || $! == &Errno::EWOULDBLOCK 815 || $! == &Errno::EWOULDBLOCK
673 # WSAEINPROGRESS intentionally not checked - it means something else entirely 816 # WSAEINPROGRESS intentionally not checked - it means something else entirely
674 || $! == AnyEvent::Util::WSAEINVAL # not convinced, but doesn't hurt 817 || $! == AnyEvent::Util::WSAEINVAL # not convinced, but doesn't hurt
675 || $! == AnyEvent::Util::WSAEWOULDBLOCK) { 818 || $! == AnyEvent::Util::WSAEWOULDBLOCK) {
676 $state{ww} = AnyEvent->io (fh => $state{fh}, poll => 'w', cb => $connected); 819 $state{ww} = AnyEvent->io (fh => $state{fh}, poll => 'w', cb => $state{connected});
677 } else { 820 } else {
678 $state{next}(); 821 $state{next}();
679 } 822 }
680 }; 823 };
681 824
691Create and bind a stream socket to the given host, and port, set the 834Create and bind a stream socket to the given host, and port, set the
692SO_REUSEADDR flag (if applicable) and call C<listen>. Unlike the name 835SO_REUSEADDR flag (if applicable) and call C<listen>. Unlike the name
693implies, this function can also bind on UNIX domain sockets. 836implies, this function can also bind on UNIX domain sockets.
694 837
695For internet sockets, C<$host> must be an IPv4 or IPv6 address (or 838For internet sockets, C<$host> must be an IPv4 or IPv6 address (or
696C<undef>, in which case it binds either to C<0> or to C<::>, depending on 839C<undef>, in which case it binds either to C<0> or to C<::>, depending
697whether IPv4 or IPv6 is the preferred protocol). 840on whether IPv4 or IPv6 is the preferred protocol, and maybe to both in
841future versions, as applicable).
698 842
699To bind to the IPv4 wildcard address, use C<0>, to bind to the IPv6 843To bind to the IPv4 wildcard address, use C<0>, to bind to the IPv6
700wildcard address, use C<::>. 844wildcard address, use C<::>.
701 845
702The port is specified by C<$service>, which must be either a service name or 846The port is specified by C<$service>, which must be either a service name or
726address and port number of the local socket endpoint as second and third 870address and port number of the local socket endpoint as second and third
727arguments. 871arguments.
728 872
729It should return the length of the listen queue (or C<0> for the default). 873It should return the length of the listen queue (or C<0> for the default).
730 874
875Note to IPv6 users: RFC-compliant behaviour for IPv6 sockets listening on
876C<::> is to bind to both IPv6 and IPv4 addresses by default on dual-stack
877hosts. Unfortunately, only GNU/Linux seems to implement this properly, so
878if you want both IPv4 and IPv6 listening sockets you should create the
879IPv6 socket first and then attempt to bind on the IPv4 socket, but ignore
880any C<EADDRINUSE> errors.
881
731Example: bind on some TCP port on the local machine and tell each client 882Example: bind on some TCP port on the local machine and tell each client
732to go away. 883to go away.
733 884
734 tcp_server undef, undef, sub { 885 tcp_server undef, undef, sub {
735 my ($fh, $host, $port) = @_; 886 my ($fh, $host, $port) = @_;
738 }, sub { 889 }, sub {
739 my ($fh, $thishost, $thisport) = @_; 890 my ($fh, $thishost, $thisport) = @_;
740 warn "bound to $thishost, port $thisport\n"; 891 warn "bound to $thishost, port $thisport\n";
741 }; 892 };
742 893
894Example: bind a server on a unix domain socket.
895
896 tcp_server "unix/", "/tmp/mydir/mysocket", sub {
897 my ($fh) = @_;
898 };
899
743=cut 900=cut
744 901
745sub tcp_server($$$;$) { 902sub tcp_server($$$;$) {
746 my ($host, $service, $accept, $prepare) = @_; 903 my ($host, $service, $accept, $prepare) = @_;
747 904
764 or Carp::croak "tcp_server/socket: $!"; 921 or Carp::croak "tcp_server/socket: $!";
765 922
766 if ($af == AF_INET || $af == AF_INET6) { 923 if ($af == AF_INET || $af == AF_INET6) {
767 setsockopt $state{fh}, SOL_SOCKET, SO_REUSEADDR, 1 924 setsockopt $state{fh}, SOL_SOCKET, SO_REUSEADDR, 1
768 or Carp::croak "tcp_server/so_reuseaddr: $!" 925 or Carp::croak "tcp_server/so_reuseaddr: $!"
769 unless !AnyEvent::WIN32; # work around windows bug 926 unless AnyEvent::WIN32; # work around windows bug
770 927
771 unless ($service =~ /^\d*$/) { 928 unless ($service =~ /^\d*$/) {
772 $service = (getservbyname $service, "tcp")[2] 929 $service = (getservbyname $service, "tcp")[2]
773 or Carp::croak "$service: service unknown" 930 or Carp::croak "$service: service unknown"
774 } 931 }
795 952
796 $state{aw} = AnyEvent->io (fh => $state{fh}, poll => 'r', cb => sub { 953 $state{aw} = AnyEvent->io (fh => $state{fh}, poll => 'r', cb => sub {
797 # this closure keeps $state alive 954 # this closure keeps $state alive
798 while (my $peer = accept my $fh, $state{fh}) { 955 while (my $peer = accept my $fh, $state{fh}) {
799 fh_nonblocking $fh, 1; # POSIX requires inheritance, the outside world does not 956 fh_nonblocking $fh, 1; # POSIX requires inheritance, the outside world does not
957
800 my ($service, $host) = unpack_sockaddr $peer; 958 my ($service, $host) = unpack_sockaddr $peer;
801 $accept->($fh, format_address $host, $service); 959 $accept->($fh, format_address $host, $service);
802 } 960 }
803 }); 961 });
804 962
809 967
8101; 9681;
811 969
812=back 970=back
813 971
972=head1 SECURITY CONSIDERATIONS
973
974This module is quite powerful, with with power comes the ability to abuse
975as well: If you accept "hostnames" and ports from untrusted sources,
976then note that this can be abused to delete files (host=C<unix/>). This
977is not really a problem with this module, however, as blindly accepting
978any address and protocol and trying to bind a server or connect to it is
979harmful in general.
980
814=head1 AUTHOR 981=head1 AUTHOR
815 982
816 Marc Lehmann <schmorp@schmorp.de> 983 Marc Lehmann <schmorp@schmorp.de>
817 http://home.schmorp.de/ 984 http://home.schmorp.de/
818 985

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines