blib/lib/AnyEvent/Socket.pm untested

filter: Statementstmt 0.0% 0 / 290 Branchbran 0.0% 0 / 162 Conditioncond 0.0% 0 / 176 MC/DCmcdc 0.0% 0 / 97 Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 20 totaltotal 0.0% 0 / 773 CC 78 SCAR 46.3
CC
78
Cov
0%
resolve_sockaddr
380.0
tcp_server
110.0
tcp_connect
72.0
CRAP 102.2
1 =head1 NAME
2  
3 AnyEvent::Socket - useful IPv4 and IPv6 stuff.
4  
5 =head1 SYNOPSIS
6  
7 use AnyEvent::Socket;
8
9 tcp_connect "gameserver.deliantra.net", 13327, sub {
10 my ($fh) = @_
11 or die "gameserver.deliantra.net connect failed: $!";
12
13 # enjoy your filehandle
14 };
15
16 # a simple tcp server
17 tcp_server undef, 8888, sub {
18 my ($fh, $host, $port) = @_;
19
20 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
21 };
22  
23 =head1 DESCRIPTION
24  
25 This module implements various utility functions for handling internet
26 protocol addresses and sockets, in an as transparent and simple way as
27 possible.
28  
29 All functions documented without C<AnyEvent::Socket::> prefix are exported
30 by default.
31  
32 =over 4
33  
34 =cut
35  
36 package AnyEvent::Socket;
37  
38 use Carp ();
39 use Errno ();
40 use Socket qw(AF_INET AF_UNIX SOCK_STREAM SOCK_DGRAM SOL_SOCKET SO_REUSEADDR);
41  
42 use AnyEvent (); BEGIN { AnyEvent::common_sense }
43 use AnyEvent::Util qw(guard fh_nonblocking AF_INET6);
44 use AnyEvent::DNS ();
45  
46 use base 'Exporter';
47  
48 our @EXPORT = qw(
49 getprotobyname
50 parse_hostport format_hostport
51 parse_ipv4 parse_ipv6
52 parse_ip parse_address
53 format_ipv4 format_ipv6
54 format_ip format_address
55 address_family
56 inet_aton
57 tcp_server
58 tcp_connect
59 );
60  
61 our $VERSION = $AnyEvent::VERSION;
62  
63 # used in cases where we may return immediately but want the
64 # caller to do stuff first
65 sub _postpone {
66 my ($cb, @args) = (@_, $!);
67  
68 my $w; $w = AE::timer 0, 0, sub {
69 undef $w;
70 $! = pop @args;
71 $cb->(@args);
72 };
73 }
74  
75 =item $ipn = parse_ipv4 $dotted_quad
76  
77 Tries to parse the given dotted quad IPv4 address and return it in
78 octet form (or undef when it isn't in a parsable format). Supports all
79 forms specified by POSIX (e.g. C<10.0.0.1>, C<10.1>, C<10.0x020304>,
80 C<0x12345678> or C<0377.0377.0377.0377>).
81  
82 =cut
83  
84 sub parse_ipv4($) {
85 $_[0] =~ /^ (?: 0x[0-9a-fA-F]+ | 0[0-7]* | [1-9][0-9]* )
86 (?:\. (?: 0x[0-9a-fA-F]+ | 0[0-7]* | [1-9][0-9]* ) ){0,3}$/x
87 or return undef;
88  
89 @_ = map /^0/ ? oct : $_, split /\./, $_[0];
90  
91 # check leading parts against range
92 return undef if grep $_ >= 256, @_[0 .. @_ - 2];
93  
94 # check trailing part against range
95 return undef if $_[-1] >= 2 ** (8 * (4 - $#_));
96  
97 pack "N", (pop)
98 + ($_[0] << 24)
99 + ($_[1] << 16)
100 + ($_[2] << 8);
101 }
102  
103 =item $ipn = parse_ipv6 $textual_ipv6_address
104  
105 Tries to parse the given IPv6 address and return it in
106 octet form (or undef when it isn't in a parsable format).
107  
108 Should support all forms specified by RFC 2373 (and additionally all IPv4
109 forms supported by parse_ipv4). Note that scope-id's are not supported
110 (and will not parse).
111  
112 This function works similarly to C<inet_pton AF_INET6, ...>.
113  
114 Example:
115  
116 print unpack "H*", parse_ipv6 "2002:5345::10.0.0.1";
117 # => 2002534500000000000000000a000001
118  
119 =cut
120  
121 sub parse_ipv6($) {
122 # quick test to avoid longer processing
123 my $n = $_[0] =~ y/://;
124 return undef if $n < 2 || $n > 8;
125  
126 my ($h, $t) = split /::/, $_[0], 2;
127  
128 unless (defined $t) {
129 ($h, $t) = (undef, $h);
130 }
131  
132 my @h = split /:/, $h;
133 my @t = split /:/, $t;
134  
135 # check for ipv4 tail
136 if (@t && $t[-1]=~ /\./) {
137 return undef if $n > 6;
138  
139 my $ipn = parse_ipv4 pop @t
140 or return undef;
141  
142 push @t, map +(sprintf "%x", $_), unpack "nn", $ipn;
143 }
144  
145 # no :: then we need to have exactly 8 components
146 return undef unless @h + @t == 8 || $_[0] =~ /::/;
147  
148 # now check all parts for validity
149 return undef if grep !/^[0-9a-fA-F]{1,4}$/, @h, @t;
150  
151 # now pad...
152 push @h, 0 while @h + @t < 8;
153  
154 # and done
155 pack "n*", map hex, @h, @t
156 }
157  
158 sub parse_unix($) {
159 $_[0] eq "unix/"
160 ? pack "S", AF_UNIX
161 : undef
162  
163 }
164  
165 =item $ipn = parse_address $ip
166  
167 Combines C<parse_ipv4> and C<parse_ipv6> in one function. The address
168 here refers to the host address (not socket address) in network form
169 (binary).
170  
171 If the C<$text> is C<unix/>, then this function returns a special token
172 recognised by the other functions in this module to mean "UNIX domain
173 socket".
174  
175 If the C<$text> to parse is a mapped IPv4 in IPv6 address (:ffff::<ipv4>),
176 then it will be treated as an IPv4 address. If you don't want that, you
177 have to call C<parse_ipv4> and/or C<parse_ipv6> manually.
178  
179 Example:
180  
181 print unpack "H*", parse_address "10.1.2.3";
182 # => 0a010203
183  
184 =item $ipn = AnyEvent::Socket::aton $ip
185  
186 Same as C<parse_address>, but not exported (think C<Socket::inet_aton> but
187 I<without> name resolution).
188  
189 =cut
190  
191 sub parse_address($) {
192 for (&parse_ipv6) {
193 if ($_) {
194 s/^\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff//;
195 return $_;
196 } else {
197 return &parse_ipv4 || &parse_unix
198 }
199 }
200 }
201  
202 *aton = \&parse_address;
203  
204 =item ($name, $aliases, $proto) = getprotobyname $name
205  
206 Works like the builtin function of the same name, except it tries hard to
207 work even on broken platforms (well, that's windows), where getprotobyname
208 is traditionally very unreliable.
209  
210 Example: get the protocol number for TCP (usually 6)
211  
212 my $proto = getprotobyname "tcp";
213  
214 =cut
215  
216 # microsoft can't even get getprotobyname working (the etc/protocols file
217 # gets lost fairly often on windows), so we have to hardcode some common
218 # protocol numbers ourselves.
219 our %PROTO_BYNAME;
220  
221 $PROTO_BYNAME{tcp} = Socket::IPPROTO_TCP () if defined &Socket::IPPROTO_TCP;
222 $PROTO_BYNAME{udp} = Socket::IPPROTO_UDP () if defined &Socket::IPPROTO_UDP;
223 $PROTO_BYNAME{icmp} = Socket::IPPROTO_ICMP() if defined &Socket::IPPROTO_ICMP;
224  
225 sub getprotobyname($) {
226 my $name = lc shift;
227  
228 defined (my $proton = $PROTO_BYNAME{$name} || (getprotobyname $name)[2])
229 or return;
230  
231 ($name, uc $name, $proton)
232 }
233  
234 =item ($host, $service) = parse_hostport $string[, $default_service]
235  
236 Splitting a string of the form C<hostname:port> is a common
237 problem. Unfortunately, just splitting on the colon makes it hard to
238 specify IPv6 addresses and doesn't support the less common but well
239 standardised C<[ip literal]> syntax.
240  
241 This function tries to do this job in a better way, it supports the
242 following formats, where C<port> can be a numerical port number of a
243 service name, or a C<name=port> string, and the C< port> and C<:port>
244 parts are optional. Also, everywhere where an IP address is supported
245 a hostname or unix domain socket address is also supported (see
246 C<parse_unix>).
247  
248 hostname:port e.g. "www.linux.org", "www.x.de:443", "www.x.de:https=443"
249 ipv4:port e.g. "198.182.196.56", "127.1:22"
250 ipv6 e.g. "::1", "affe::1"
251 [ipv4or6]:port e.g. "[::1]", "[10.0.1]:80"
252 [ipv4or6] port e.g. "[127.0.0.1]", "[www.x.org] 17"
253 ipv4or6 port e.g. "::1 443", "10.0.0.1 smtp"
254  
255 It also supports defaulting the service name in a simple way by using
256 C<$default_service> if no service was detected. If neither a service was
257 detected nor a default was specified, then this function returns the
258 empty list. The same happens when a parse error was detected, such as a
259 hostname with a colon in it (the function is rather conservative, though).
260  
261 Example:
262  
263 print join ",", parse_hostport "localhost:443";
264 # => "localhost,443"
265  
266 print join ",", parse_hostport "localhost", "https";
267 # => "localhost,https"
268  
269 print join ",", parse_hostport "[::1]";
270 # => "," (empty list)
271  
272 =cut
273  
274 sub parse_hostport($;$) {
275 my ($host, $port);
276  
277 for ("$_[0]") { # work on a copy, just in case, and also reset pos
278  
279 # parse host, special cases: "ipv6" or "ipv6 port"
280 unless (
281 ($host) = /^\s* ([0-9a-fA-F:]*:[0-9a-fA-F:]*:[0-9a-fA-F\.:]*)/xgc
282 and parse_ipv6 $host
283 ) {
284 /^\s*/xgc;
285  
286 if (/^ \[ ([^\[\]]+) \]/xgc) {
287 $host = $1;
288 } elsif (/^ ([^\[\]:\ ]+) /xgc) {
289 $host = $1;
290 } else {
291 return;
292 }
293 }
294  
295 # parse port
296 if (/\G (?:\s+|:) ([^:[:space:]]+) \s*$/xgc) {
297 $port = $1;
298 } elsif (/\G\s*$/gc && length $_[1]) {
299 $port = $_[1];
300 } else {
301 return;
302 }
303 }
304  
305 # hostnames must not contain :'s
306 return if $host =~ /:/ && !parse_ipv6 $host;
307  
308 ($host, $port)
309 }
310  
311 =item $string = format_hostport $host, $port
312  
313 Takes a host (in textual form) and a port and formats in unambigiously in
314 a way that C<parse_hostport> can parse it again. C<$port> can be C<undef>.
315  
316 =cut
317  
318 sub format_hostport($;$) {
319 my ($host, $port) = @_;
320  
321 $port = ":$port" if length $port;
322 $host = "[$host]" if $host =~ /:/;
323  
324 "$host$port"
325 }
326  
327 =item $sa_family = address_family $ipn
328  
329 Returns the address family/protocol-family (AF_xxx/PF_xxx, in one value :)
330 of the given host address in network format.
331  
332 =cut
333  
334 sub address_family($) {
335 4 == length $_[0]
336 ? AF_INET
337 : 16 == length $_[0]
338 ? AF_INET6
339 : unpack "S", $_[0]
340 }
341  
342 =item $text = format_ipv4 $ipn
343  
344 Expects a four octet string representing a binary IPv4 address and returns
345 its textual format. Rarely used, see C<format_address> for a nicer
346 interface.
347  
348 =item $text = format_ipv6 $ipn
349  
350 Expects a sixteen octet string representing a binary IPv6 address and
351 returns its textual format. Rarely used, see C<format_address> for a
352 nicer interface.
353  
354 =item $text = format_address $ipn
355  
356 Covnvert a host address in network format (e.g. 4 octets for IPv4 or 16
357 octets for IPv6) and convert it into textual form.
358  
359 Returns C<unix/> for UNIX domain sockets.
360  
361 This function works similarly to C<inet_ntop AF_INET || AF_INET6, ...>,
362 except it automatically detects the address type.
363  
364 Returns C<undef> if it cannot detect the type.
365  
366 If the C<$ipn> is a mapped IPv4 in IPv6 address (:ffff::<ipv4>), then just
367 the contained IPv4 address will be returned. If you do not want that, you
368 have to call C<format_ipv6> manually.
369  
370 Example:
371  
372 print format_address "\x01\x02\x03\x05";
373 => 1.2.3.5
374  
375 =item $text = AnyEvent::Socket::ntoa $ipn
376  
377 Same as format_address, but not exported (think C<inet_ntoa>).
378  
379 =cut
380  
381 sub format_ipv4($) {
382 join ".", unpack "C4", $_[0]
383 }
384  
385 sub format_ipv6($) {
386 if (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0 eq $_[0]) {
387 return "::";
388 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 eq $_[0]) {
389 return "::1";
390 } elsif (v0.0.0.0.0.0.0.0.0.0.0.0 eq substr $_[0], 0, 12) {
391 # v4compatible
392 return "::" . format_ipv4 substr $_[0], 12;
393 } elsif (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12) {
394 # v4mapped
395 return "::ffff:" . format_ipv4 substr $_[0], 12;
396 } elsif (v0.0.0.0.0.0.0.0.255.255.0.0 eq substr $_[0], 0, 12) {
397 # v4translated
398 return "::ffff:0:" . format_ipv4 substr $_[0], 12;
399 } else {
400 my $ip = sprintf "%x:%x:%x:%x:%x:%x:%x:%x", unpack "n8", $_[0];
401  
402 # this is rather sucky, I admit
403 $ip =~ s/^0:(?:0:)*(0$)?/::/
404 or $ip =~ s/(:0){7}$/::/ or $ip =~ s/(:0){7}/:/
405 or $ip =~ s/(:0){6}$/::/ or $ip =~ s/(:0){6}/:/
406 or $ip =~ s/(:0){5}$/::/ or $ip =~ s/(:0){5}/:/
407 or $ip =~ s/(:0){4}$/::/ or $ip =~ s/(:0){4}/:/
408 or $ip =~ s/(:0){3}$/::/ or $ip =~ s/(:0){3}/:/
409 or $ip =~ s/(:0){2}$/::/ or $ip =~ s/(:0){2}/:/
410 or $ip =~ s/(:0){1}$/::/ or $ip =~ s/(:0){1}/:/;
411 return $ip
412 }
413 }
414  
415 sub format_address($) {
416 my $af = address_family $_[0];
417 if ($af == AF_INET) {
418 return &format_ipv4;
419 } elsif ($af == AF_INET6) {
420 return (v0.0.0.0.0.0.0.0.0.0.255.255 eq substr $_[0], 0, 12)
421 ? format_ipv4 substr $_[0], 12
422 : &format_ipv6;
423 } elsif ($af == AF_UNIX) {
424 return "unix/"
425 } else {
426 return undef
427 }
428 }
429  
430 *ntoa = \&format_address;
431  
432 =item inet_aton $name_or_address, $cb->(@addresses)
433  
434 Works similarly to its Socket counterpart, except that it uses a
435 callback. Use the length to distinguish between ipv4 and ipv6 (4 octets
436 for IPv4, 16 for IPv6), or use C<format_address> to convert it to a more
437 readable format.
438  
439 Note that C<resolve_sockaddr>, while initially a more complex interface,
440 resolves host addresses, service names and SRV records and gives you an
441 ordered list of socket addresses to try and should be preferred over
442 C<inet_aton>.
443  
444 Example.
445  
446 inet_aton "www.google.com", my $cv = AE::cv;
447 say unpack "H*", $_
448 for $cv->recv;
449 # => d155e363
450 # => d155e367 etc.
451  
452 inet_aton "ipv6.google.com", my $cv = AE::cv;
453 say unpack "H*", $_
454 for $cv->recv;
455 # => 20014860a00300000000000000000068
456  
457 =cut
458  
459 sub inet_aton {
460 my ($name, $cb) = @_;
461  
462 if (my $ipn = &parse_ipv4) {
463 $cb->($ipn);
464 } elsif (my $ipn = &parse_ipv6) {
465 $cb->($ipn);
466 } elsif ($name eq "localhost") { # rfc2606 et al.
467 $cb->(v127.0.0.1, v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1);
468 } else {
469 require AnyEvent::DNS;
470  
471 my $ipv4 = $AnyEvent::PROTOCOL{ipv4};
472 my $ipv6 = $AnyEvent::PROTOCOL{ipv6};
473  
474 my @res;
475  
476 my $cv = AE::cv {
477 $cb->(map @$_, reverse @res);
478 };
479  
480 $cv->begin;
481  
482 if ($ipv4) {
483 $cv->begin;
484 AnyEvent::DNS::a ($name, sub {
485 $res[$ipv4] = [map &parse_ipv4, @_];
486 $cv->end;
487 });
488 };
489  
490 if ($ipv6) {
491 $cv->begin;
492 AnyEvent::DNS::aaaa ($name, sub {
493 $res[$ipv6] = [map &parse_ipv6, @_];
494 $cv->end;
495 });
496 };
497  
498 $cv->end;
499 }
500 }
501  
502 BEGIN {
503 *sockaddr_family = $Socket::VERSION >= 1.75
504 ? \&Socket::sockaddr_family
505 : # for 5.6.x, we need to do something much more horrible
506 (Socket::pack_sockaddr_in 0x5555, "\x55\x55\x55\x55"
507 | eval { Socket::pack_sockaddr_un "U" }) =~ /^\x00/
508 ? sub { unpack "xC", $_[0] }
509 : sub { unpack "S" , $_[0] };
510 }
511  
512 # check for broken platforms with an extra field in sockaddr structure
513 # kind of a rfc vs. bsd issue, as usual (ok, normally it's a
514 # unix vs. bsd issue, a iso C vs. bsd issue or simply a
515 # correctness vs. bsd issue.)
516 my $pack_family = 0x55 == sockaddr_family ("\x55\x55")
517 ? "xC" : "S";
518  
519 =item $sa = AnyEvent::Socket::pack_sockaddr $service, $host
520  
521 Pack the given port/host combination into a binary sockaddr
522 structure. Handles both IPv4 and IPv6 host addresses, as well as UNIX
523 domain sockets (C<$host> == C<unix/> and C<$service> == absolute
524 pathname).
525  
526 Example:
527  
528 my $bind = AnyEvent::Socket::pack_sockaddr 43, v195.234.53.120;
529 bind $socket, $bind
530 or die "bind: $!";
531  
532 =cut
533  
534 sub pack_sockaddr($$) {
535 my $af = address_family $_[1];
536  
537 if ($af == AF_INET) {
538 Socket::pack_sockaddr_in $_[0], $_[1]
539 } elsif ($af == AF_INET6) {
540 pack "$pack_family nL a16 L",
541 AF_INET6,
542 $_[0], # port
543 0, # flowinfo
544 $_[1], # addr
545 0 # scope id
546 } elsif ($af == AF_UNIX) {
547 Socket::pack_sockaddr_un $_[0]
548 } else {
549 Carp::croak "pack_sockaddr: invalid host";
550 }
551 }
552  
553 =item ($service, $host) = AnyEvent::Socket::unpack_sockaddr $sa
554  
555 Unpack the given binary sockaddr structure (as used by bind, getpeername
556 etc.) into a C<$service, $host> combination.
557  
558 For IPv4 and IPv6, C<$service> is the port number and C<$host> the host
559 address in network format (binary).
560  
561 For UNIX domain sockets, C<$service> is the absolute pathname and C<$host>
562 is a special token that is understood by the other functions in this
563 module (C<format_address> converts it to C<unix/>).
564  
565 =cut
566  
567 # perl contains a bug (imho) where it requires that the kernel always returns
568 # sockaddr_un structures of maximum length (which is not, AFAICS, required
569 # by any standard). try to 0-pad structures for the benefit of those platforms.
570  
571 my $sa_un_zero = eval { Socket::pack_sockaddr_un "" }; $sa_un_zero ^= $sa_un_zero;
572  
573 sub unpack_sockaddr($) {
574 my $af = sockaddr_family $_[0];
575  
576 if ($af == AF_INET) {
577 Socket::unpack_sockaddr_in $_[0]
578 } elsif ($af == AF_INET6) {
579 unpack "x2 n x4 a16", $_[0]
580 } elsif ($af == AF_UNIX) {
581 ((Socket::unpack_sockaddr_un $_[0] ^ $sa_un_zero), pack "S", AF_UNIX)
582 } else {
583 Carp::croak "unpack_sockaddr: unsupported protocol family $af";
584 }
585 }
586  
587 =item resolve_sockaddr $node, $service, $proto, $family, $type, $cb->([$family, $type, $proto, $sockaddr], ...)
588  
589 Tries to resolve the given nodename and service name into protocol families
590 and sockaddr structures usable to connect to this node and service in a
591 protocol-independent way. It works remotely similar to the getaddrinfo
592 posix function.
593  
594 For internet addresses, C<$node> is either an IPv4 or IPv6 address or an
595 internet hostname, and C<$service> is either a service name (port name
596 from F</etc/services>) or a numerical port number. If both C<$node> and
597 C<$service> are names, then SRV records will be consulted to find the real
598 service, otherwise they will be used as-is. If you know that the service
599 name is not in your services database, then you can specify the service in
600 the format C<name=port> (e.g. C<http=80>).
601  
602 For UNIX domain sockets, C<$node> must be the string C<unix/> and
603 C<$service> must be the absolute pathname of the socket. In this case,
604 C<$proto> will be ignored.
605  
606 C<$proto> must be a protocol name, currently C<tcp>, C<udp> or
607 C<sctp>. The default is currently C<tcp>, but in the future, this function
608 might try to use other protocols such as C<sctp>, depending on the socket
609 type and any SRV records it might find.
610  
611 C<$family> must be either C<0> (meaning any protocol is OK), C<4> (use
612 only IPv4) or C<6> (use only IPv6). The default is influenced by
613 C<$ENV{PERL_ANYEVENT_PROTOCOLS}>.
614  
615 C<$type> must be C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_SEQPACKET> (or
616 C<undef> in which case it gets automatically chosen to be C<SOCK_STREAM>
617 unless C<$proto> is C<udp>).
618  
619 The callback will receive zero or more array references that contain
620 C<$family, $type, $proto> for use in C<socket> and a binary
621 C<$sockaddr> for use in C<connect> (or C<bind>).
622  
623 The application should try these in the order given.
624  
625 Example:
626  
627 resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... };
628  
629 =cut
630  
631 sub resolve_sockaddr($$$$$$) {
632 my ($node, $service, $proto, $family, $type, $cb) = @_;
633  
634 if ($node eq "unix/") {
635 return $cb->() if $family || $service !~ /^\//; # no can do
636  
637 return $cb->([AF_UNIX, defined $type ? $type : SOCK_STREAM, 0, Socket::pack_sockaddr_un $service]);
638 }
639  
640 unless (AF_INET6) {
641 $family != 6
642 or return $cb->();
643  
644 $family = 4;
645 }
646  
647 $cb->() if $family == 4 && !$AnyEvent::PROTOCOL{ipv4};
648 $cb->() if $family == 6 && !$AnyEvent::PROTOCOL{ipv6};
649  
650 $family ||= 4 unless $AnyEvent::PROTOCOL{ipv6};
651 $family ||= 6 unless $AnyEvent::PROTOCOL{ipv4};
652  
653 $proto ||= "tcp";
654 $type ||= $proto eq "udp" ? SOCK_DGRAM : SOCK_STREAM;
655  
656 my $proton = getprotobyname $proto
657 or Carp::croak "$proto: protocol unknown";
658  
659 my $port;
660  
661 if ($service =~ /^(\S+)=(\d+)$/) {
662 ($service, $port) = ($1, $2);
663 } elsif ($service =~ /^\d+$/) {
664 ($service, $port) = (undef, $service);
665 } else {
666 $port = (getservbyname $service, $proto)[2]
667 or Carp::croak "$service/$proto: service unknown";
668 }
669  
670 my @target = [$node, $port];
671  
672 # resolve a records / provide sockaddr structures
673 my $resolve = sub {
674 my @res;
675 my $cv = AE::cv {
676 $cb->(
677 map $_->[2],
678 sort {
679 $AnyEvent::PROTOCOL{$b->[1]} <=> $AnyEvent::PROTOCOL{$a->[1]}
680 or $a->[0] <=> $b->[0]
681 }
682 @res
683 )
684 };
685  
686 $cv->begin;
687 for my $idx (0 .. $#target) {
688 my ($node, $port) = @{ $target[$idx] };
689  
690 if (my $noden = parse_address $node) {
691 my $af = address_family $noden;
692  
693 if ($af == AF_INET && $family != 6) {
694 push @res, [$idx, "ipv4", [AF_INET, $type, $proton,
695 pack_sockaddr $port, $noden]]
696 }
697  
698 if ($af == AF_INET6 && $family != 4) {
699 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton,
700 pack_sockaddr $port, $noden]]
701 }
702 } else {
703 # ipv4
704 if ($family != 6) {
705 $cv->begin;
706 AnyEvent::DNS::a $node, sub {
707 push @res, [$idx, "ipv4", [AF_INET, $type, $proton,
708 pack_sockaddr $port, parse_ipv4 $_]]
709 for @_;
710 $cv->end;
711 };
712 }
713  
714 # ipv6
715 if ($family != 4) {
716 $cv->begin;
717 AnyEvent::DNS::aaaa $node, sub {
718 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton,
719 pack_sockaddr $port, parse_ipv6 $_]]
720 for @_;
721 $cv->end;
722 };
723 }
724 }
725 }
726 $cv->end;
727 };
728  
729 # try srv records, if applicable
730 if ($node eq "localhost") {
731 @target = (["127.0.0.1", $port], ["::1", $port]);
732 &$resolve;
733 } elsif (defined $service && !parse_address $node) {
734 AnyEvent::DNS::srv $service, $proto, $node, sub {
735 my (@srv) = @_;
736  
737 # no srv records, continue traditionally
738 @srv
739 or return &$resolve;
740  
741 # the only srv record has "." ("" here) => abort
742 $srv[0][2] ne "" || $#srv
743 or return $cb->();
744  
745 # use srv records then
746 @target = map ["$_->[3].", $_->[2]],
747 grep $_->[3] ne ".",
748 @srv;
749  
750 &$resolve;
751 };
752 } else {
753 &$resolve;
754 }
755 }
756  
757 =item $guard = tcp_connect $host, $service, $connect_cb[, $prepare_cb]
758  
759 This is a convenience function that creates a TCP socket and makes a 100%
760 non-blocking connect to the given C<$host> (which can be a hostname or
761 a textual IP address, or the string C<unix/> for UNIX domain sockets)
762 and C<$service> (which can be a numeric port number or a service name,
763 or a C<servicename=portnumber> string, or the pathname to a UNIX domain
764 socket).
765  
766 If both C<$host> and C<$port> are names, then this function will use SRV
767 records to locate the real target(s).
768  
769 In either case, it will create a list of target hosts (e.g. for multihomed
770 hosts or hosts with both IPv4 and IPv6 addresses) and try to connect to
771 each in turn.
772  
773 After the connection is established, then the C<$connect_cb> will be
774 invoked with the socket file handle (in non-blocking mode) as first and
775 the peer host (as a textual IP address) and peer port as second and third
776 arguments, respectively. The fourth argument is a code reference that you
777 can call if, for some reason, you don't like this connection, which will
778 cause C<tcp_connect> to try the next one (or call your callback without
779 any arguments if there are no more connections). In most cases, you can
780 simply ignore this argument.
781  
782 $cb->($filehandle, $host, $port, $retry)
783  
784 If the connect is unsuccessful, then the C<$connect_cb> will be invoked
785 without any arguments and C<$!> will be set appropriately (with C<ENXIO>
786 indicating a DNS resolution failure).
787  
788 The callback will I<never> be invoked before C<tcp_connect> returns, even
789 if C<tcp_connect> was able to connect immediately (e.g. on unix domain
790 sockets).
791  
792 The file handle is perfect for being plugged into L<AnyEvent::Handle>, but
793 can be used as a normal perl file handle as well.
794  
795 Unless called in void context, C<tcp_connect> returns a guard object that
796 will automatically abort connecting when it gets destroyed (it does not do
797 anything to the socket after the connect was successful).
798  
799 Sometimes you need to "prepare" the socket before connecting, for example,
800 to C<bind> it to some port, or you want a specific connect timeout that
801 is lower than your kernel's default timeout. In this case you can specify
802 a second callback, C<$prepare_cb>. It will be called with the file handle
803 in not-yet-connected state as only argument and must return the connection
804 timeout value (or C<0>, C<undef> or the empty list to indicate the default
805 timeout is to be used).
806  
807 Note that the socket could be either a IPv4 TCP socket or an IPv6 TCP
808 socket (although only IPv4 is currently supported by this module).
809  
810 Note to the poor Microsoft Windows users: Windows (of course) doesn't
811 correctly signal connection errors, so unless your event library works
812 around this, failed connections will simply hang. The only event libraries
813 that handle this condition correctly are L<EV> and L<Glib>. Additionally,
814 AnyEvent works around this bug with L<Event> and in its pure-perl
815 backend. All other libraries cannot correctly handle this condition. To
816 lessen the impact of this windows bug, a default timeout of 30 seconds
817 will be imposed on windows. Cygwin is not affected.
818  
819 Simple Example: connect to localhost on port 22.
820  
821 tcp_connect localhost => 22, sub {
822 my $fh = shift
823 or die "unable to connect: $!";
824 # do something
825 };
826  
827 Complex Example: connect to www.google.com on port 80 and make a simple
828 GET request without much error handling. Also limit the connection timeout
829 to 15 seconds.
830  
831 tcp_connect "www.google.com", "http",
832 sub {
833 my ($fh) = @_
834 or die "unable to connect: $!";
835  
836 my $handle; # avoid direct assignment so on_eof has it in scope.
837 $handle = new AnyEvent::Handle
838 fh => $fh,
839 on_error => sub {
840 warn "error $_[2]\n";
841 $_[0]->destroy;
842 },
843 on_eof => sub {
844 $handle->destroy; # destroy handle
845 warn "done.\n";
846 };
847  
848 $handle->push_write ("GET / HTTP/1.0\015\012\015\012");
849  
850 $handle->push_read (line => "\015\012\015\012", sub {
851 my ($handle, $line) = @_;
852  
853 # print response header
854 print "HEADER\n$line\n\nBODY\n";
855  
856 $handle->on_read (sub {
857 # print response body
858 print $_[0]->rbuf;
859 $_[0]->rbuf = "";
860 });
861 });
862 }, sub {
863 my ($fh) = @_;
864 # could call $fh->bind etc. here
865  
866 15
867 };
868  
869 Example: connect to a UNIX domain socket.
870  
871 tcp_connect "unix/", "/tmp/.X11-unix/X0", sub {
872 ...
873 }
874  
875 =cut
876  
877 sub tcp_connect($$$;$) {
878 my ($host, $port, $connect, $prepare) = @_;
879  
880 # see http://cr.yp.to/docs/connect.html for some background
881 # also http://advogato.org/article/672.html
882  
883 my %state = ( fh => undef );
884  
885 # name/service to type/sockaddr resolution
886 resolve_sockaddr $host, $port, 0, 0, undef, sub {
887 my @target = @_;
888  
889 $state{next} = sub {
890 return unless exists $state{fh};
891  
892 my $target = shift @target
893 or return (%state = (), _postpone $connect);
894  
895 my ($domain, $type, $proto, $sockaddr) = @$target;
896  
897 # socket creation
898 socket $state{fh}, $domain, $type, $proto
899 or return $state{next}();
900  
901 fh_nonblocking $state{fh}, 1;
902
903 my $timeout = $prepare && $prepare->($state{fh});
904  
905 $timeout ||= 30 if AnyEvent::WIN32;
906  
907 $state{to} = AE::timer $timeout, 0, sub {
908 $! = Errno::ETIMEDOUT;
909 $state{next}();
910 } if $timeout;
911  
912 # now connect
913 if (
914 (connect $state{fh}, $sockaddr)
915 || ($! == Errno::EINPROGRESS # POSIX
916 || $! == Errno::EWOULDBLOCK
917 # WSAEINPROGRESS intentionally not checked - it means something else entirely
918 || $! == AnyEvent::Util::WSAEINVAL # not convinced, but doesn't hurt
919 || $! == AnyEvent::Util::WSAEWOULDBLOCK)
920 ) {
921 $state{ww} = AE::io $state{fh}, 1, sub {
922 # we are connected, or maybe there was an error
923 if (my $sin = getpeername $state{fh}) {
924 my ($port, $host) = unpack_sockaddr $sin;
925  
926 delete $state{ww}; delete $state{to};
927  
928 my $guard = guard { %state = () };
929  
930 $connect->(delete $state{fh}, format_address $host, $port, sub {
931 $guard->cancel;
932 $state{next}();
933 });
934 } else {
935 # dummy read to fetch real error code
936 sysread $state{fh}, my $buf, 1 if $! == Errno::ENOTCONN;
937  
938 return if $! == Errno::EAGAIN; # skip spurious wake-ups
939  
940 delete $state{ww}; delete $state{to};
941  
942 $state{next}();
943 }
944 };
945 } else {
946 $state{next}();
947 }
948 };
949  
950 $! = Errno::ENXIO;
951 $state{next}();
952 };
953  
954 defined wantarray && guard { %state = () }
955 }
956  
957 =item $guard = tcp_server $host, $service, $accept_cb[, $prepare_cb]
958  
959 Create and bind a stream socket to the given host, and port, set the
960 SO_REUSEADDR flag (if applicable) and call C<listen>. Unlike the name
961 implies, this function can also bind on UNIX domain sockets.
962  
963 For internet sockets, C<$host> must be an IPv4 or IPv6 address (or
964 C<undef>, in which case it binds either to C<0> or to C<::>, depending
965 on whether IPv4 or IPv6 is the preferred protocol, and maybe to both in
966 future versions, as applicable).
967  
968 To bind to the IPv4 wildcard address, use C<0>, to bind to the IPv6
969 wildcard address, use C<::>.
970  
971 The port is specified by C<$service>, which must be either a service name or
972 a numeric port number (or C<0> or C<undef>, in which case an ephemeral
973 port will be used).
974  
975 For UNIX domain sockets, C<$host> must be C<unix/> and C<$service> must be
976 the absolute pathname of the socket. This function will try to C<unlink>
977 the socket before it tries to bind to it. See SECURITY CONSIDERATIONS,
978 below.
979  
980 For each new connection that could be C<accept>ed, call the C<<
981 $accept_cb->($fh, $host, $port) >> with the file handle (in non-blocking
982 mode) as first and the peer host and port as second and third arguments
983 (see C<tcp_connect> for details).
984  
985 Croaks on any errors it can detect before the listen.
986  
987 If called in non-void context, then this function returns a guard object
988 whose lifetime it tied to the TCP server: If the object gets destroyed,
989 the server will be stopped (but existing accepted connections will
990 continue).
991  
992 If you need more control over the listening socket, you can provide a
993 C<< $prepare_cb->($fh, $host, $port) >>, which is called just before the
994 C<listen ()> call, with the listen file handle as first argument, and IP
995 address and port number of the local socket endpoint as second and third
996 arguments.
997  
998 It should return the length of the listen queue (or C<0> for the default).
999  
1000 Note to IPv6 users: RFC-compliant behaviour for IPv6 sockets listening on
1001 C<::> is to bind to both IPv6 and IPv4 addresses by default on dual-stack
1002 hosts. Unfortunately, only GNU/Linux seems to implement this properly, so
1003 if you want both IPv4 and IPv6 listening sockets you should create the
1004 IPv6 socket first and then attempt to bind on the IPv4 socket, but ignore
1005 any C<EADDRINUSE> errors.
1006  
1007 Example: bind on some TCP port on the local machine and tell each client
1008 to go away.
1009  
1010 tcp_server undef, undef, sub {
1011 my ($fh, $host, $port) = @_;
1012  
1013 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
1014 }, sub {
1015 my ($fh, $thishost, $thisport) = @_;
1016 warn "bound to $thishost, port $thisport\n";
1017 };
1018  
1019 Example: bind a server on a unix domain socket.
1020  
1021 tcp_server "unix/", "/tmp/mydir/mysocket", sub {
1022 my ($fh) = @_;
1023 };
1024  
1025 =cut
1026  
1027 sub tcp_server($$$;$) {
1028 my ($host, $service, $accept, $prepare) = @_;
1029  
1030 $host = $AnyEvent::PROTOCOL{ipv4} < $AnyEvent::PROTOCOL{ipv6} && AF_INET6
1031 ? "::" : "0"
1032 unless defined $host;
1033  
1034 my $ipn = parse_address $host
1035 or Carp::croak "AnyEvent::Socket::tcp_server: cannot parse '$host' as host address";
1036  
1037 my $af = address_family $ipn;
1038  
1039 my %state;
1040  
1041 # win32 perl is too stupid to get this right :/
1042 Carp::croak "tcp_server/socket: address family not supported"
1043 if AnyEvent::WIN32 && $af == AF_UNIX;
1044  
1045 socket $state{fh}, $af, SOCK_STREAM, 0
1046 or Carp::croak "tcp_server/socket: $!";
1047  
1048 if ($af == AF_INET || $af == AF_INET6) {
1049 setsockopt $state{fh}, SOL_SOCKET, SO_REUSEADDR, 1
1050 or Carp::croak "tcp_server/so_reuseaddr: $!"
1051 unless AnyEvent::WIN32; # work around windows bug
1052  
1053 unless ($service =~ /^\d*$/) {
1054 $service = (getservbyname $service, "tcp")[2]
1055 or Carp::croak "$service: service unknown"
1056 }
1057 } elsif ($af == AF_UNIX) {
1058 unlink $service;
1059 }
1060  
1061 bind $state{fh}, pack_sockaddr $service, $ipn
1062 or Carp::croak "bind: $!";
1063  
1064 fh_nonblocking $state{fh}, 1;
1065  
1066 my $len;
1067  
1068 if ($prepare) {
1069 my ($service, $host) = unpack_sockaddr getsockname $state{fh};
1070 $len = $prepare && $prepare->($state{fh}, format_address $host, $service);
1071 }
1072
1073 $len ||= 128;
1074  
1075 listen $state{fh}, $len
1076 or Carp::croak "listen: $!";
1077  
1078 $state{aw} = AE::io $state{fh}, 0, sub {
1079 # this closure keeps $state alive
1080 while ($state{fh} && (my $peer = accept my $fh, $state{fh})) {
1081 fh_nonblocking $fh, 1; # POSIX requires inheritance, the outside world does not
1082  
1083 my ($service, $host) = unpack_sockaddr $peer;
1084 $accept->($fh, format_address $host, $service);
1085 }
1086 };
1087  
1088 defined wantarray
1089 ? guard { %state = () } # clear fh and watcher, which breaks the circular dependency
1090 : ()
1091 }
1092  
1093 1;
1094  
1095 =back
1096  
1097 =head1 SECURITY CONSIDERATIONS
1098  
1099 This module is quite powerful, with with power comes the ability to abuse
1100 as well: If you accept "hostnames" and ports from untrusted sources,
1101 then note that this can be abused to delete files (host=C<unix/>). This
1102 is not really a problem with this module, however, as blindly accepting
1103 any address and protocol and trying to bind a server or connect to it is
1104 harmful in general.
1105  
1106 =head1 AUTHOR
1107  
1108 Marc Lehmann <schmorp@schmorp.de>
1109 http://home.schmorp.de/
1110  
1111 =cut
1112