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.19 by root, Sat May 24 18:52:10 2008 UTC vs.
Revision 1.76 by root, Sun Apr 26 18:12:53 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
38no warnings; 38no warnings;
39use strict; 39use strict;
40 40
41use Carp (); 41use Carp ();
42use Errno (); 42use Errno ();
43use Socket (); 43use Socket qw(AF_INET AF_UNIX SOCK_STREAM SOCK_DGRAM SOL_SOCKET SO_REUSEADDR);
44 44
45use AnyEvent (); 45use AnyEvent ();
46use AnyEvent::Util qw(guard fh_nonblocking); 46use AnyEvent::Util qw(guard fh_nonblocking AF_INET6);
47use AnyEvent::DNS (); 47use AnyEvent::DNS ();
48 48
49use base 'Exporter'; 49use base 'Exporter';
50 50
51BEGIN { 51our @EXPORT = qw(
52 *socket_inet_aton = \&Socket::inet_aton; # take a copy, in case Coro::LWP overrides it 52 parse_hostport
53} 53 parse_ipv4 parse_ipv6
54 parse_ip parse_address
55 format_ip format_address
56 address_family
57 inet_aton
58 tcp_server
59 tcp_connect
60);
54 61
55BEGIN {
56 my $af_inet6 = eval { &Socket::AF_INET6 };
57 eval "sub AF_INET6() { $af_inet6 }"; die if $@;
58
59 delete $AnyEvent::PROTOCOL{ipv6} unless $af_inet6;
60}
61
62our @EXPORT = qw(parse_ipv4 parse_ipv6 parse_ip format_ip inet_aton tcp_server tcp_connect);
63
64our $VERSION = '1.0'; 62our $VERSION = 4.4;
65 63
66=item $ipn = parse_ipv4 $dotted_quad 64=item $ipn = parse_ipv4 $dotted_quad
67 65
68Tries 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
69octet 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
81 79
82 # check leading parts against range 80 # check leading parts against range
83 return undef if grep $_ >= 256, @_[0 .. @_ - 2]; 81 return undef if grep $_ >= 256, @_[0 .. @_ - 2];
84 82
85 # check trailing part against range 83 # check trailing part against range
86 return undef if $_[-1] >= 1 << (8 * (4 - $#_)); 84 return undef if $_[-1] >= 2 ** (8 * (4 - $#_));
87 85
88 pack "N", (pop) 86 pack "N", (pop)
89 + ($_[0] << 24) 87 + ($_[0] << 24)
90 + ($_[1] << 16) 88 + ($_[1] << 16)
91 + ($_[2] << 8); 89 + ($_[2] << 8);
95 93
96Tries to parse the given IPv6 address and return it in 94Tries to parse the given IPv6 address and return it in
97octet form (or undef when it isn't in a parsable format). 95octet form (or undef when it isn't in a parsable format).
98 96
99Should support all forms specified by RFC 2373 (and additionally all IPv4 97Should support all forms specified by RFC 2373 (and additionally all IPv4
100forms supported by parse_ipv4). 98forms supported by parse_ipv4). Note that scope-id's are not supported
99(and will not parse).
101 100
102This function works similarly to C<inet_pton AF_INET6, ...>. 101This function works similarly to C<inet_pton AF_INET6, ...>.
103 102
104=cut 103=cut
105 104
138 137
139 # and done 138 # and done
140 pack "n*", map hex, @h, @t 139 pack "n*", map hex, @h, @t
141} 140}
142 141
142sub parse_unix($) {
143 $_[0] eq "unix/"
144 ? pack "S", AF_UNIX
145 : undef
146
147}
148
143=item $ipn = parse_ip $text 149=item $ipn = parse_address $text
144 150
145Combines C<parse_ipv4> and C<parse_ipv6> in one function. 151Combines C<parse_ipv4> and C<parse_ipv6> in one function. The address
152here refers to the host address (not socket address) in network form
153(binary).
146 154
147=cut 155If the C<$text> is C<unix/>, then this function returns a special token
156recognised by the other functions in this module to mean "UNIX domain
157socket".
148 158
159=item $text = AnyEvent::Socket::aton $ipn
160
161Same as C<parse_address>, but not exported (think C<Socket::inet_aton> but
162I<without> name resolution).
163
164=cut
165
149sub parse_ip($) { 166sub parse_address($) {
150 &parse_ipv4 || &parse_ipv6 167 &parse_ipv4 || &parse_ipv6 || &parse_unix
151} 168}
152 169
170*aton = \&parse_address;
171
172=item ($host, $service) = parse_hostport $string[, $default_service]
173
174Splitting a string of the form C<hostname:port> is a common
175problem. Unfortunately, just splitting on the colon makes it hard to
176specify IPv6 addresses and doesn't support the less common but well
177standardised C<[ip literal]> syntax.
178
179This function tries to do this job in a better way, it supports the
180following formats, where C<port> can be a numerical port number of a
181service name, or a C<name=port> string, and the C< port> and C<:port>
182parts are optional. Also, everywhere where an IP address is supported
183a hostname or unix domain socket address is also supported (see
184C<parse_unix>).
185
186 hostname:port e.g. "www.linux.org", "www.x.de:443", "www.x.de:https=443"
187 ipv4:port e.g. "198.182.196.56", "127.1:22"
188 ipv6 e.g. "::1", "affe::1"
189 [ipv4or6]:port e.g. "[::1]", "[10.0.1]:80"
190 [ipv4or6] port e.g. "[127.0.0.1]", "[www.x.org] 17"
191 ipv4or6 port e.g. "::1 443", "10.0.0.1 smtp"
192
193It also supports defaulting the service name in a simple way by using
194C<$default_service> if no service was detected. If neither a service was
195detected nor a default was specified, then this function returns the
196empty list. The same happens when a parse error weas detected, such as a
197hostname with a colon in it (the function is rather conservative, though).
198
199Example:
200
201 print join ",", parse_hostport "localhost:443";
202 # => "localhost,443"
203
204 print join ",", parse_hostport "localhost", "https";
205 # => "localhost,https"
206
207 print join ",", parse_hostport "[::1]";
208 # => "," (empty list)
209
210=cut
211
212sub parse_hostport($;$) {
213 my ($host, $port);
214
215 for ("$_[0]") { # work on a copy, just in case, and also reset pos
216
217 # parse host, special cases: "ipv6" or "ipv6 port"
218 unless (
219 ($host) = /^\s* ([0-9a-fA-F:]*:[0-9a-fA-F:]*:[0-9a-fA-F\.:]*)/xgc
220 and parse_ipv6 $host
221 ) {
222 /^\s*/xgc;
223
224 if (/^ \[ ([^\[\]]+) \]/xgc) {
225 $host = $1;
226 } elsif (/^ ([^\[\]:\ ]+) /xgc) {
227 $host = $1;
228 } else {
229 return;
230 }
231 }
232
233 # parse port
234 if (/\G (?:\s+|:) ([^:[:space:]]+) \s*$/xgc) {
235 $port = $1;
236 } elsif (/\G\s*$/gc && length $_[1]) {
237 $port = $_[1];
238 } else {
239 return;
240 }
241 }
242
243 # hostnames must not contain :'s
244 return if $host =~ /:/ && !parse_ipv6 $host;
245
246 ($host, $port)
247}
248
249=item $sa_family = address_family $ipn
250
251Returns the address family/protocol-family (AF_xxx/PF_xxx, in one value :)
252of the given host address in network format.
253
254=cut
255
256sub address_family($) {
257 4 == length $_[0]
258 ? AF_INET
259 : 16 == length $_[0]
260 ? AF_INET6
261 : unpack "S", $_[0]
262}
263
153=item $text = format_ip $ipn 264=item $text = format_address $ipn
154 265
155Takes either an IPv4 address (4 octets) or and IPv6 address (16 octets) 266Covnvert a host address in network format (e.g. 4 octets for IPv4 or 16
156and converts it into textual form. 267octets for IPv6) and convert it into textual form.
268
269Returns C<unix/> for UNIX domain sockets.
157 270
158This function works similarly to C<inet_ntop AF_INET || AF_INET6, ...>, 271This function works similarly to C<inet_ntop AF_INET || AF_INET6, ...>,
159except it automatically detects the address type. 272except it automatically detects the address type.
160 273
161=cut 274Returns C<undef> if it cannot detect the type.
162 275
163sub format_ip; 276=item $text = AnyEvent::Socket::ntoa $ipn
277
278Same as format_address, but not exported (think C<inet_ntoa>).
279
280=cut
281
282sub format_address;
164sub format_ip($) { 283sub format_address($) {
165 if (4 == length $_[0]) { 284 my $af = address_family $_[0];
285 if ($af == AF_INET) {
166 return join ".", unpack "C4", $_[0] 286 return join ".", unpack "C4", $_[0]
167 } elsif (16 == length $_[0]) { 287 } elsif ($af == AF_INET6) {
288 if (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0 eq $_[0]) {
289 return "::";
290 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 eq $_[0]) {
291 return "::1";
292 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0 eq substr $_[0], 0, 12) {
293 # v4compatible
294 return "::" . format_address substr $_[0], 12;
168 if (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12) { 295 } elsif (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12) {
169 # v4mapped 296 # v4mapped
170 return "::ffff:" . format_ip substr $_[0], 12; 297 return "::ffff:" . format_address substr $_[0], 12;
298 } elsif (v0.0.0.0.0.0.0.0.255.255.0.0 eq substr $_[0], 0, 12) {
299 # v4translated
300 return "::ffff:0:" . format_address substr $_[0], 12;
171 } else { 301 } else {
172 my $ip = sprintf "%x:%x:%x:%x:%x:%x:%x:%x", unpack "n8", $_[0]; 302 my $ip = sprintf "%x:%x:%x:%x:%x:%x:%x:%x", unpack "n8", $_[0];
173 303
304 # this is rather sucky, I admit
174 $ip =~ s/^0:(?:0:)*/::/ 305 $ip =~ s/^0:(?:0:)*(0$)?/::/
175 or $ip =~ s/(:0)+$/::/ 306 or $ip =~ s/(:0){7}$/::/ or $ip =~ s/(:0){7}/:/
176 or $ip =~ s/(:0)+/:/; 307 or $ip =~ s/(:0){6}$/::/ or $ip =~ s/(:0){6}/:/
308 or $ip =~ s/(:0){5}$/::/ or $ip =~ s/(:0){5}/:/
309 or $ip =~ s/(:0){4}$/::/ or $ip =~ s/(:0){4}/:/
310 or $ip =~ s/(:0){3}$/::/ or $ip =~ s/(:0){3}/:/
311 or $ip =~ s/(:0){2}$/::/ or $ip =~ s/(:0){2}/:/
312 or $ip =~ s/(:0){1}$/::/ or $ip =~ s/(:0){1}/:/;
177 return $ip 313 return $ip
178 } 314 }
315 } elsif ($af == AF_UNIX) {
316 return "unix/"
179 } else { 317 } else {
180 return undef 318 return undef
181 } 319 }
182} 320}
321
322*ntoa = \&format_address;
183 323
184=item inet_aton $name_or_address, $cb->(@addresses) 324=item inet_aton $name_or_address, $cb->(@addresses)
185 325
186Works similarly to its Socket counterpart, except that it uses a 326Works similarly to its Socket counterpart, except that it uses a
187callback. Also, if a host has only an IPv6 address, this might be passed 327callback. Also, if a host has only an IPv6 address, this might be passed
188to the callback instead (use the length to detect this - 4 for IPv4, 16 328to the callback instead (use the length to detect this - 4 for IPv4, 16
189for IPv6). 329for IPv6).
190 330
191Unlike the L<Socket> function of the same name, you can get multiple IPv4 331Unlike the L<Socket> function of the same name, you can get multiple IPv4
192and IPv6 addresses as result. 332and IPv6 addresses as result (and maybe even other adrdess types).
193 333
194=cut 334=cut
195 335
196sub inet_aton { 336sub inet_aton {
197 my ($name, $cb) = @_; 337 my ($name, $cb) = @_;
215 } 355 }
216 }); 356 });
217 } 357 }
218} 358}
219 359
360# check for broken platforms with extra field in sockaddr structure
361# kind of a rfc vs. bsd issue, as usual (ok, normally it's a
362# unix vs. bsd issue, a iso C vs. bsd issue or simply a
363# correctness vs. bsd issue.
364my $pack_family = (0x55 == Socket::sockaddr_family "\x55\x55")
365 ? "xC" : "S";
366
220=item $sa = AnyEvent::Socket::pack_sockaddr $port, $host 367=item $sa = AnyEvent::Socket::pack_sockaddr $service, $host
221 368
222Pack the given port/host combination into a binary sockaddr structure. Handles 369Pack the given port/host combination into a binary sockaddr
223both IPv4 and IPv6 host addresses. 370structure. Handles both IPv4 and IPv6 host addresses, as well as UNIX
371domain sockets (C<$host> == C<unix/> and C<$service> == absolute
372pathname).
224 373
225=cut 374=cut
226 375
227sub pack_sockaddr($$) { 376sub pack_sockaddr($$) {
228 if (4 == length $_[1]) { 377 my $af = address_family $_[1];
378
379 if ($af == AF_INET) {
229 Socket::pack_sockaddr_in $_[0], $_[1] 380 Socket::pack_sockaddr_in $_[0], $_[1]
230 } elsif (16 == length $_[1]) { 381 } elsif ($af == AF_INET6) {
231 pack "SnL a16 L", 382 pack "$pack_family nL a16 L",
232 Socket::AF_INET6, 383 AF_INET6,
233 $_[0], # port 384 $_[0], # port
234 0, # flowinfo 385 0, # flowinfo
235 $_[1], # addr 386 $_[1], # addr
236 0 # scope id 387 0 # scope id
388 } elsif ($af == AF_UNIX) {
389 Socket::pack_sockaddr_un $_[0]
237 } else { 390 } else {
238 Carp::croak "pack_sockaddr: invalid host"; 391 Carp::croak "pack_sockaddr: invalid host";
239 } 392 }
240} 393}
241 394
242=item ($port, $host) = AnyEvent::Socket::unpack_sockaddr $sa 395=item ($service, $host) = AnyEvent::Socket::unpack_sockaddr $sa
243 396
244Unpack the given binary sockaddr structure (as used by bind, getpeername 397Unpack the given binary sockaddr structure (as used by bind, getpeername
245etc.) into a C<$port, $host> combination. 398etc.) into a C<$service, $host> combination.
246 399
247Handles both IPv4 and IPv6 sockaddr structures. 400For IPv4 and IPv6, C<$service> is the port number and C<$host> the host
401address in network format (binary).
402
403For UNIX domain sockets, C<$service> is the absolute pathname and C<$host>
404is a special token that is understood by the other functions in this
405module (C<format_address> converts it to C<unix/>).
248 406
249=cut 407=cut
250 408
251sub unpack_sockaddr($) { 409sub unpack_sockaddr($) {
252 my $af = unpack "S", $_[0]; 410 my $af = Socket::sockaddr_family $_[0];
253 411
254 if ($af == &Socket::AF_INET) { 412 if ($af == AF_INET) {
255 Socket::unpack_sockaddr_in $_[0] 413 Socket::unpack_sockaddr_in $_[0]
256 } elsif ($af == AF_INET6) { 414 } elsif ($af == AF_INET6) {
257 (unpack "SnL a16 L")[1, 3] 415 unpack "x2 n x4 a16", $_[0]
416 } elsif ($af == AF_UNIX) {
417 ((Socket::unpack_sockaddr_un $_[0]), pack "S", AF_UNIX)
258 } else { 418 } else {
259 Carp::croak "unpack_sockaddr: unsupported protocol family $af"; 419 Carp::croak "unpack_sockaddr: unsupported protocol family $af";
260 } 420 }
261} 421}
262 422
263sub _tcp_port($) { 423=item resolve_sockaddr $node, $service, $proto, $family, $type, $cb->([$family, $type, $proto, $sockaddr], ...)
264 $_[0] =~ /^(\d*)$/ and return $1*1;
265 424
266 (getservbyname $_[0], "tcp")[2] 425Tries to resolve the given nodename and service name into protocol families
426and sockaddr structures usable to connect to this node and service in a
427protocol-independent way. It works remotely similar to the getaddrinfo
428posix function.
429
430For internet addresses, C<$node> is either an IPv4 or IPv6 address or an
431internet hostname, and C<$service> is either a service name (port name
432from F</etc/services>) or a numerical port number. If both C<$node> and
433C<$service> are names, then SRV records will be consulted to find the real
434service, otherwise they will be used as-is. If you know that the service
435name is not in your services database, then you can specify the service in
436the format C<name=port> (e.g. C<http=80>).
437
438For UNIX domain sockets, C<$node> must be the string C<unix/> and
439C<$service> must be the absolute pathname of the socket. In this case,
440C<$proto> will be ignored.
441
442C<$proto> must be a protocol name, currently C<tcp>, C<udp> or
443C<sctp>. The default is currently C<tcp>, but in the future, this function
444might try to use other protocols such as C<sctp>, depending on the socket
445type and any SRV records it might find.
446
447C<$family> must be either C<0> (meaning any protocol is OK), C<4> (use
448only IPv4) or C<6> (use only IPv6). The default is influenced by
449C<$ENV{PERL_ANYEVENT_PROTOCOLS}>.
450
451C<$type> must be C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_SEQPACKET> (or
452C<undef> in which case it gets automatically chosen to be C<SOCK_STREAM>
453unless C<$proto> is C<udp>).
454
455The callback will receive zero or more array references that contain
456C<$family, $type, $proto> for use in C<socket> and a binary
457C<$sockaddr> for use in C<connect> (or C<bind>).
458
459The application should try these in the order given.
460
461Example:
462
463 resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... };
464
465=cut
466
467# microsoft can't even get getprotobyname working (the etc/protocols file
468# gets lost fairly often on windows), so we have to hardcode some common
469# protocol numbers ourselves.
470our %PROTO_BYNAME;
471
472$PROTO_BYNAME{tcp} = &Socket::IPPROTO_TCP if defined &Socket::IPPROTO_TCP;
473$PROTO_BYNAME{udp} = &Socket::IPPROTO_UDP if defined &Socket::IPPROTO_UDP;
474$PROTO_BYNAME{icmp} = &Socket::IPPROTO_ICMP if defined &Socket::IPPROTO_ICMP;
475
476sub resolve_sockaddr($$$$$$) {
477 my ($node, $service, $proto, $family, $type, $cb) = @_;
478
479 if ($node eq "unix/") {
480 return $cb->() if $family || $service !~ /^\//; # no can do
481
482 return $cb->([AF_UNIX, defined $type ? $type : SOCK_STREAM, 0, Socket::pack_sockaddr_un $service]);
483 }
484
485 unless (AF_INET6) {
486 $family != 6
487 or return $cb->();
488
489 $family = 4;
490 }
491
492 $cb->() if $family == 4 && !$AnyEvent::PROTOCOL{ipv4};
493 $cb->() if $family == 6 && !$AnyEvent::PROTOCOL{ipv6};
494
495 $family ||= 4 unless $AnyEvent::PROTOCOL{ipv6};
496 $family ||= 6 unless $AnyEvent::PROTOCOL{ipv4};
497
498 $proto ||= "tcp";
499 $type ||= $proto eq "udp" ? SOCK_DGRAM : SOCK_STREAM;
500
501 my $proton = $PROTO_BYNAME{lc $proto} || (getprotobyname $proto)[2]
267 or Carp::croak "$_[0]: service unknown" 502 or Carp::croak "$proto: protocol unknown";
503
504 my $port;
505
506 if ($service =~ /^(\S+)=(\d+)$/) {
507 ($service, $port) = ($1, $2);
508 } elsif ($service =~ /^\d+$/) {
509 ($service, $port) = (undef, $service);
510 } else {
511 $port = (getservbyname $service, $proto)[2]
512 or Carp::croak "$service/$proto: service unknown";
513 }
514
515 my @target = [$node, $port];
516
517 # resolve a records / provide sockaddr structures
518 my $resolve = sub {
519 my @res;
520 my $cv = AnyEvent->condvar (cb => sub {
521 $cb->(
522 map $_->[2],
523 sort {
524 $AnyEvent::PROTOCOL{$b->[1]} <=> $AnyEvent::PROTOCOL{$a->[1]}
525 or $a->[0] <=> $b->[0]
526 }
527 @res
528 )
529 });
530
531 $cv->begin;
532 for my $idx (0 .. $#target) {
533 my ($node, $port) = @{ $target[$idx] };
534
535 if (my $noden = parse_address $node) {
536 my $af = address_family $noden;
537
538 if ($af == AF_INET && $family != 6) {
539 push @res, [$idx, "ipv4", [AF_INET, $type, $proton,
540 pack_sockaddr $port, $noden]]
541 }
542
543 if ($af == AF_INET6 && $family != 4) {
544 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton,
545 pack_sockaddr $port, $noden]]
546 }
547 } else {
548 # ipv4
549 if ($family != 6) {
550 $cv->begin;
551 AnyEvent::DNS::a $node, sub {
552 push @res, [$idx, "ipv4", [AF_INET, $type, $proton,
553 pack_sockaddr $port, parse_ipv4 $_]]
554 for @_;
555 $cv->end;
556 };
557 }
558
559 # ipv6
560 if ($family != 4) {
561 $cv->begin;
562 AnyEvent::DNS::aaaa $node, sub {
563 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton,
564 pack_sockaddr $port, parse_ipv6 $_]]
565 for @_;
566 $cv->end;
567 };
568 }
569 }
570 }
571 $cv->end;
572 };
573
574 # try srv records, if applicable
575 if ($node eq "localhost") {
576 @target = (["127.0.0.1", $port], ["::1", $port]);
577 &$resolve;
578 } elsif (defined $service && !parse_address $node) {
579 AnyEvent::DNS::srv $service, $proto, $node, sub {
580 my (@srv) = @_;
581
582 # no srv records, continue traditionally
583 @srv
584 or return &$resolve;
585
586 # the only srv record has "." ("" here) => abort
587 $srv[0][2] ne "" || $#srv
588 or return $cb->();
589
590 # use srv records then
591 @target = map ["$_->[3].", $_->[2]],
592 grep $_->[3] ne ".",
593 @srv;
594
595 &$resolve;
596 };
597 } else {
598 &$resolve;
599 }
268} 600}
269 601
270=item $guard = tcp_connect $host, $service, $connect_cb[, $prepare_cb] 602=item $guard = tcp_connect $host, $service, $connect_cb[, $prepare_cb]
271 603
272This is a convenience function that creates a TCP socket and makes a 100% 604This is a convenience function that creates a TCP socket and makes a 100%
273non-blocking connect to the given C<$host> (which can be a hostname or a 605non-blocking connect to the given C<$host> (which can be a hostname or
606a textual IP address, or the string C<unix/> for UNIX domain sockets)
274textual IP address) and C<$service> (which can be a numeric port number or 607and C<$service> (which can be a numeric port number or a service name,
275a service name, or a C<servicename=portnumber> string). 608or a C<servicename=portnumber> string, or the pathname to a UNIX domain
609socket).
276 610
277If both C<$host> and C<$port> are names, then this function will use SRV 611If both C<$host> and C<$port> are names, then this function will use SRV
278records to locate the real target(s). 612records to locate the real target(s).
279 613
280In either case, it will create a list of target hosts (e.g. for multihomed 614In either case, it will create a list of target hosts (e.g. for multihomed
312timeout is to be used). 646timeout is to be used).
313 647
314Note that the socket could be either a IPv4 TCP socket or an IPv6 TCP 648Note that the socket could be either a IPv4 TCP socket or an IPv6 TCP
315socket (although only IPv4 is currently supported by this module). 649socket (although only IPv4 is currently supported by this module).
316 650
651Note to the poor Microsoft Windows users: Windows (of course) doesn't
652correctly signal connection errors, so unless your event library works
653around this, failed connections will simply hang. The only event libraries
654that handle this condition correctly are L<EV> and L<Glib>. Additionally,
655AnyEvent works around this bug with L<Event> and in its pure-perl
656backend. All other libraries cannot correctly handle this condition. To
657lessen the impact of this windows bug, a default timeout of 30 seconds
658will be imposed on windows. Cygwin is not affected.
659
317Simple Example: connect to localhost on port 22. 660Simple Example: connect to localhost on port 22.
318 661
319 tcp_connect localhost => 22, sub { 662 tcp_connect localhost => 22, sub {
320 my $fh = shift 663 my $fh = shift
321 or die "unable to connect: $!"; 664 or die "unable to connect: $!";
322 # do something 665 # do something
323 }; 666 };
324 667
325Complex Example: connect to www.google.com on port 80 and make a simple 668Complex Example: connect to www.google.com on port 80 and make a simple
326GET request without much error handling. Also limit the connection timeout 669GET request without much error handling. Also limit the connection timeout
327to 15 seconds. 670to 15 seconds.
328 671
358 # could call $fh->bind etc. here 701 # could call $fh->bind etc. here
359 702
360 15 703 15
361 }; 704 };
362 705
706Example: connect to a UNIX domain socket.
707
708 tcp_connect "unix/", "/tmp/.X11-unix/X0", sub {
709 ...
710 }
711
363=cut 712=cut
364 713
365sub tcp_connect($$$;$) { 714sub tcp_connect($$$;$) {
366 my ($host, $port, $connect, $prepare) = @_; 715 my ($host, $port, $connect, $prepare) = @_;
367 716
368 # see http://cr.yp.to/docs/connect.html for some background 717 # see http://cr.yp.to/docs/connect.html for some background
718 # also http://advogato.org/article/672.html
369 719
370 my %state = ( fh => undef ); 720 my %state = ( fh => undef );
371 721
372 # name resolution 722 # name/service to type/sockaddr resolution
373 AnyEvent::DNS::addr $host, $port, 0, 0, 0, sub { 723 resolve_sockaddr $host, $port, 0, 0, undef, sub {
374 my @target = @_; 724 my @target = @_;
375 725
376 $state{next} = sub { 726 $state{next} = sub {
377 return unless exists $state{fh}; 727 return unless exists $state{fh};
378 728
388 socket $state{fh}, $domain, $type, $proto 738 socket $state{fh}, $domain, $type, $proto
389 or return $state{next}(); 739 or return $state{next}();
390 740
391 fh_nonblocking $state{fh}, 1; 741 fh_nonblocking $state{fh}, 1;
392 742
393 # prepare and optional timeout
394 if ($prepare) {
395 my $timeout = $prepare->($state{fh}); 743 my $timeout = $prepare && $prepare->($state{fh});
396 744
745 $timeout ||= 30 if AnyEvent::WIN32;
746
397 $state{to} = AnyEvent->timer (after => $timeout, cb => sub { 747 $state{to} = AnyEvent->timer (after => $timeout, cb => sub {
398 $! = &Errno::ETIMEDOUT; 748 $! = &Errno::ETIMEDOUT;
399 $state{next}(); 749 $state{next}();
400 }) if $timeout; 750 }) if $timeout;
401 }
402 751
403 # called when the connect was successful, which, 752 # called when the connect was successful, which,
404 # in theory, could be the case immediately (but never is in practise) 753 # in theory, could be the case immediately (but never is in practise)
405 my $connected = sub { 754 $state{connected} = sub {
406 delete $state{ww}; 755 delete $state{ww};
407 delete $state{to}; 756 delete $state{to};
408 757
409 # we are connected, or maybe there was an error 758 # we are connected, or maybe there was an error
410 if (my $sin = getpeername $state{fh}) { 759 if (my $sin = getpeername $state{fh}) {
411 my ($port, $host) = unpack_sockaddr $sin; 760 my ($port, $host) = unpack_sockaddr $sin;
412 761
413 my $guard = guard { 762 my $guard = guard { %state = () };
414 %state = ();
415 };
416 763
417 $connect->($state{fh}, format_ip $host, $port, sub { 764 $connect->(delete $state{fh}, format_address $host, $port, sub {
418 $guard->cancel; 765 $guard->cancel;
419 $state{next}(); 766 $state{next}();
420 }); 767 });
421 } else { 768 } else {
422 # dummy read to fetch real error code 769 # dummy read to fetch real error code
425 } 772 }
426 }; 773 };
427 774
428 # now connect 775 # now connect
429 if (connect $state{fh}, $sockaddr) { 776 if (connect $state{fh}, $sockaddr) {
430 $connected->(); 777 $state{connected}->();
431 } elsif ($! == &Errno::EINPROGRESS || $! == &Errno::EWOULDBLOCK) { # EINPROGRESS is POSIX 778 } elsif ($! == &Errno::EINPROGRESS # POSIX
779 || $! == &Errno::EWOULDBLOCK
780 # WSAEINPROGRESS intentionally not checked - it means something else entirely
781 || $! == AnyEvent::Util::WSAEINVAL # not convinced, but doesn't hurt
782 || $! == AnyEvent::Util::WSAEWOULDBLOCK) {
432 $state{ww} = AnyEvent->io (fh => $state{fh}, poll => 'w', cb => $connected); 783 $state{ww} = AnyEvent->io (fh => $state{fh}, poll => 'w', cb => $state{connected});
433 } else { 784 } else {
434 %state = (); 785 $state{next}();
435 $connect->();
436 } 786 }
437 }; 787 };
438 788
439 $! = &Errno::ENXIO; 789 $! = &Errno::ENXIO;
440 $state{next}(); 790 $state{next}();
441 }; 791 };
442 792
443 defined wantarray && guard { %state = () } 793 defined wantarray && guard { %state = () }
444} 794}
445 795
446=item $guard = tcp_server $host, $port, $accept_cb[, $prepare_cb] 796=item $guard = tcp_server $host, $service, $accept_cb[, $prepare_cb]
447 797
448Create and bind a TCP socket to the given host (any IPv4 host if undef, 798Create and bind a stream socket to the given host, and port, set the
449otherwise it must be an IPv4 or IPv6 address) and port (service name or 799SO_REUSEADDR flag (if applicable) and call C<listen>. Unlike the name
450numeric port number, or an ephemeral port if given as zero or undef), set 800implies, this function can also bind on UNIX domain sockets.
451the SO_REUSEADDR flag and call C<listen>.
452 801
802For internet sockets, C<$host> must be an IPv4 or IPv6 address (or
803C<undef>, in which case it binds either to C<0> or to C<::>, depending
804on whether IPv4 or IPv6 is the preferred protocol, and maybe to both in
805future versions, as applicable).
806
807To bind to the IPv4 wildcard address, use C<0>, to bind to the IPv6
808wildcard address, use C<::>.
809
810The port is specified by C<$service>, which must be either a service name or
811a numeric port number (or C<0> or C<undef>, in which case an ephemeral
812port will be used).
813
814For UNIX domain sockets, C<$host> must be C<unix/> and C<$service> must be
815the absolute pathname of the socket. This function will try to C<unlink>
816the socket before it tries to bind to it. See SECURITY CONSIDERATIONS,
817below.
818
453For each new connection that could be C<accept>ed, call the C<$accept_cb> 819For each new connection that could be C<accept>ed, call the C<<
454with the file handle (in non-blocking mode) as first and the peer host and 820$accept_cb->($fh, $host, $port) >> with the file handle (in non-blocking
455port as second and third arguments (see C<tcp_connect> for details). 821mode) as first and the peer host and port as second and third arguments
822(see C<tcp_connect> for details).
456 823
457Croaks on any errors. 824Croaks on any errors it can detect before the listen.
458 825
459If called in non-void context, then this function returns a guard object 826If called in non-void context, then this function returns a guard object
460whose lifetime it tied to the TCP server: If the object gets destroyed, 827whose lifetime it tied to the TCP server: If the object gets destroyed,
461the server will be stopped (but existing accepted connections will 828the server will be stopped (but existing accepted connections will
462continue). 829continue).
463 830
464If you need more control over the listening socket, you can provide a 831If you need more control over the listening socket, you can provide a
465C<$prepare_cb>, which is called just before the C<listen ()> call, with 832C<< $prepare_cb->($fh, $host, $port) >>, which is called just before the
466the listen file handle as first argument. 833C<listen ()> call, with the listen file handle as first argument, and IP
834address and port number of the local socket endpoint as second and third
835arguments.
467 836
468It should return the length of the listen queue (or C<0> for the default). 837It should return the length of the listen queue (or C<0> for the default).
469 838
839Note to IPv6 users: RFC-compliant behaviour for IPv6 sockets listening on
840C<::> is to bind to both IPv6 and IPv4 addresses by default on dual-stack
841hosts. Unfortunately, only GNU/Linux seems to implement this properly, so
842if you want both IPv4 and IPv6 listening sockets you should create the
843IPv6 socket first and then attempt to bind on the IPv4 socket, but ignore
844any C<EADDRINUSE> errors.
845
470Example: bind on TCP port 8888 on the local machine and tell each client 846Example: bind on some TCP port on the local machine and tell each client
471to go away. 847to go away.
472 848
473 tcp_server undef, 8888, sub { 849 tcp_server undef, undef, sub {
474 my ($fh, $host, $port) = @_; 850 my ($fh, $host, $port) = @_;
475 851
476 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012"; 852 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
853 }, sub {
854 my ($fh, $thishost, $thisport) = @_;
855 warn "bound to $thishost, port $thisport\n";
477 }; 856 };
478 857
858Example: bind a server on a unix domain socket.
859
860 tcp_server "unix/", "/tmp/mydir/mysocket", sub {
861 my ($fh) = @_;
862 };
863
479=cut 864=cut
480 865
481sub tcp_server($$$;$) { 866sub tcp_server($$$;$) {
482 my ($host, $port, $accept, $prepare) = @_; 867 my ($host, $service, $accept, $prepare) = @_;
868
869 $host = $AnyEvent::PROTOCOL{ipv4} < $AnyEvent::PROTOCOL{ipv6} && AF_INET6
870 ? "::" : "0"
871 unless defined $host;
872
873 my $ipn = parse_address $host
874 or Carp::croak "AnyEvent::Socket::tcp_server: cannot parse '$host' as host address";
875
876 my $af = address_family $ipn;
483 877
484 my %state; 878 my %state;
485 879
486 socket $state{fh}, &Socket::AF_INET, &Socket::SOCK_STREAM, 0 880 # win32 perl is too stupid to get this right :/
881 Carp::croak "tcp_server/socket: address family not supported"
882 if AnyEvent::WIN32 && $af == AF_UNIX;
883
884 socket $state{fh}, $af, SOCK_STREAM, 0
487 or Carp::croak "socket: $!"; 885 or Carp::croak "tcp_server/socket: $!";
488 886
887 if ($af == AF_INET || $af == AF_INET6) {
489 setsockopt $state{fh}, &Socket::SOL_SOCKET, &Socket::SO_REUSEADDR, 1 888 setsockopt $state{fh}, SOL_SOCKET, SO_REUSEADDR, 1
490 or Carp::croak "so_reuseaddr: $!"; 889 or Carp::croak "tcp_server/so_reuseaddr: $!"
890 unless AnyEvent::WIN32; # work around windows bug
491 891
492 bind $state{fh}, Socket::pack_sockaddr_in _tcp_port $port, socket_inet_aton ($host || "0.0.0.0") 892 unless ($service =~ /^\d*$/) {
893 $service = (getservbyname $service, "tcp")[2]
894 or Carp::croak "$service: service unknown"
895 }
896 } elsif ($af == AF_UNIX) {
897 unlink $service;
898 }
899
900 bind $state{fh}, pack_sockaddr $service, $ipn
493 or Carp::croak "bind: $!"; 901 or Carp::croak "bind: $!";
494 902
495 fh_nonblocking $state{fh}, 1; 903 fh_nonblocking $state{fh}, 1;
496 904
497 my $len = ($prepare && $prepare->($state{fh})) || 128; 905 my $len;
906
907 if ($prepare) {
908 my ($service, $host) = unpack_sockaddr getsockname $state{fh};
909 $len = $prepare && $prepare->($state{fh}, format_address $host, $service);
910 }
911
912 $len ||= 128;
498 913
499 listen $state{fh}, $len 914 listen $state{fh}, $len
500 or Carp::croak "listen: $!"; 915 or Carp::croak "listen: $!";
501 916
502 $state{aw} = AnyEvent->io (fh => $state{fh}, poll => 'r', cb => sub { 917 $state{aw} = AnyEvent->io (fh => $state{fh}, poll => 'r', cb => sub {
503 # this closure keeps $state alive 918 # this closure keeps $state alive
504 while (my $peer = accept my $fh, $state{fh}) { 919 while (my $peer = accept my $fh, $state{fh}) {
505 fh_nonblocking $fh, 1; # POSIX requires inheritance, the outside world does not 920 fh_nonblocking $fh, 1; # POSIX requires inheritance, the outside world does not
921
506 my ($port, $host) = Socket::unpack_sockaddr_in $peer; 922 my ($service, $host) = unpack_sockaddr $peer;
507 $accept->($fh, (Socket::inet_ntoa $host), $port); 923 $accept->($fh, format_address $host, $service);
508 } 924 }
509 }); 925 });
510 926
511 defined wantarray 927 defined wantarray
512 ? guard { %state = () } # clear fh and watcher, which breaks the circular dependency 928 ? guard { %state = () } # clear fh and watcher, which breaks the circular dependency
515 931
5161; 9321;
517 933
518=back 934=back
519 935
936=head1 SECURITY CONSIDERATIONS
937
938This module is quite powerful, with with power comes the ability to abuse
939as well: If you accept "hostnames" and ports from untrusted sources,
940then note that this can be abused to delete files (host=C<unix/>). This
941is not really a problem with this module, however, as blindly accepting
942any address and protocol and trying to bind a server or connect to it is
943harmful in general.
944
520=head1 AUTHOR 945=head1 AUTHOR
521 946
522 Marc Lehmann <schmorp@schmorp.de> 947 Marc Lehmann <schmorp@schmorp.de>
523 http://home.schmorp.de/ 948 http://home.schmorp.de/
524 949

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines