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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines