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.130 by root, Fri Jan 14 17:43:11 2011 UTC vs.
Revision 1.146 by root, Tue Mar 27 23:47:57 2012 UTC

1=head1 NAME 1=head1 NAME
2 2
3AnyEvent::Socket - useful IPv4 and IPv6 stuff. 3AnyEvent::Socket - useful IPv4 and IPv6 stuff. also unix domain sockets. and stuff.
4 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent::Socket; 7 use AnyEvent::Socket;
8 8
58 tcp_connect 58 tcp_connect
59); 59);
60 60
61our $VERSION = $AnyEvent::VERSION; 61our $VERSION = $AnyEvent::VERSION;
62 62
63# used in cases where we may return immediately but want the
64# caller to do stuff first
65sub _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 63=item $ipn = parse_ipv4 $dotted_quad
76 64
77Tries to parse the given dotted quad IPv4 address and return it in 65Tries to parse the given dotted quad IPv4 address and return it in
78octet form (or undef when it isn't in a parsable format). Supports all 66octet form (or undef when it isn't in a parsable format). Supports all
79forms specified by POSIX (e.g. C<10.0.0.1>, C<10.1>, C<10.0x020304>, 67forms specified by POSIX (e.g. C<10.0.0.1>, C<10.1>, C<10.0x020304>,
152 push @h, 0 while @h + @t < 8; 140 push @h, 0 while @h + @t < 8;
153 141
154 # and done 142 # and done
155 pack "n*", map hex, @h, @t 143 pack "n*", map hex, @h, @t
156} 144}
145
146=item $token = parse_unix $hostname
147
148This fucntion exists mainly for symmetry to the other C<parse_protocol>
149functions - it takes a hostname and, if it is C<unix/>, it returns a
150special address token, otherwise C<undef>.
151
152The only use for this function is probably to detect whether a hostname
153matches whatever AnyEvent uses for unix domain sockets.
154
155=cut
157 156
158sub parse_unix($) { 157sub parse_unix($) {
159 $_[0] eq "unix/" 158 $_[0] eq "unix/"
160 ? pack "S", AF_UNIX 159 ? pack "S", AF_UNIX
161 : undef 160 : undef
241This function tries to do this job in a better way, it supports the 240This function tries to do this job in a better way, it supports the
242following formats, where C<port> can be a numerical port number of a 241following formats, where C<port> can be a numerical port number of a
243service name, or a C<name=port> string, and the C< port> and C<:port> 242service name, or a C<name=port> string, and the C< port> and C<:port>
244parts are optional. Also, everywhere where an IP address is supported 243parts are optional. Also, everywhere where an IP address is supported
245a hostname or unix domain socket address is also supported (see 244a hostname or unix domain socket address is also supported (see
246C<parse_unix>). 245C<parse_unix>), and strings starting with C</> will also be interpreted as
246unix domain sockets.
247 247
248 hostname:port e.g. "www.linux.org", "www.x.de:443", "www.x.de:https=443" 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" 249 ipv4:port e.g. "198.182.196.56", "127.1:22"
250 ipv6 e.g. "::1", "affe::1" 250 ipv6 e.g. "::1", "affe::1"
251 [ipv4or6]:port e.g. "[::1]", "[10.0.1]:80" 251 [ipv4or6]:port e.g. "[::1]", "[10.0.1]:80"
252 [ipv4or6] port e.g. "[127.0.0.1]", "[www.x.org] 17" 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" 253 ipv4or6 port e.g. "::1 443", "10.0.0.1 smtp"
254 unix/:path e.g. "unix/:/path/to/socket"
255 /path e.g. "/path/to/socket"
254 256
255It also supports defaulting the service name in a simple way by using 257It also supports defaulting the service name in a simple way by using
256C<$default_service> if no service was detected. If neither a service was 258C<$default_service> if no service was detected. If neither a service was
257detected nor a default was specified, then this function returns the 259detected nor a default was specified, then this function returns the
258empty list. The same happens when a parse error was detected, such as a 260empty list. The same happens when a parse error was detected, such as a
267 # => "localhost,https" 269 # => "localhost,https"
268 270
269 print join ",", parse_hostport "[::1]"; 271 print join ",", parse_hostport "[::1]";
270 # => "," (empty list) 272 # => "," (empty list)
271 273
274 print join ",", parse_host_port "/tmp/debug.sock";
275 # => "unix/", "/tmp/debug.sock"
276
272=cut 277=cut
273 278
274sub parse_hostport($;$) { 279sub parse_hostport($;$) {
275 my ($host, $port); 280 my ($host, $port);
276 281
277 for ("$_[0]") { # work on a copy, just in case, and also reset pos 282 for ("$_[0]") { # work on a copy, just in case, and also reset pos
283
284 # shortcut for /path
285 return ("unix/", $_)
286 if m%^/%;
278 287
279 # parse host, special cases: "ipv6" or "ipv6 port" 288 # parse host, special cases: "ipv6" or "ipv6 port"
280 unless ( 289 unless (
281 ($host) = /^\s* ([0-9a-fA-F:]*:[0-9a-fA-F:]*:[0-9a-fA-F\.:]*)/xgc 290 ($host) = /^\s* ([0-9a-fA-F:]*:[0-9a-fA-F:]*:[0-9a-fA-F\.:]*)/xgc
282 and parse_ipv6 $host 291 and parse_ipv6 $host
298 } elsif (/\G\s*$/gc && length $_[1]) { 307 } elsif (/\G\s*$/gc && length $_[1]) {
299 $port = $_[1]; 308 $port = $_[1];
300 } else { 309 } else {
301 return; 310 return;
302 } 311 }
312
303 } 313 }
304 314
305 # hostnames must not contain :'s 315 # hostnames must not contain :'s
306 return if $host =~ /:/ && !parse_ipv6 $host; 316 return if $host =~ /:/ && !parse_ipv6 $host;
307 317
465 } elsif (my $ipn = &parse_ipv6) { 475 } elsif (my $ipn = &parse_ipv6) {
466 $cb->($ipn); 476 $cb->($ipn);
467 } elsif ($name eq "localhost") { # rfc2606 et al. 477 } elsif ($name eq "localhost") { # rfc2606 et al.
468 $cb->(v127.0.0.1, v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1); 478 $cb->(v127.0.0.1, v0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1);
469 } else { 479 } else {
470 require AnyEvent::DNS; 480 require AnyEvent::DNS unless $AnyEvent::DNS::VERSION;
471 481
472 my $ipv4 = $AnyEvent::PROTOCOL{ipv4}; 482 my $ipv4 = $AnyEvent::PROTOCOL{ipv4};
473 my $ipv6 = $AnyEvent::PROTOCOL{ipv6}; 483 my $ipv6 = $AnyEvent::PROTOCOL{ipv6};
474 484
475 my @res; 485 my @res;
599will be consulted to find the real service, otherwise they will be 609will be consulted to find the real service, otherwise they will be
600used as-is. If you know that the service name is not in your services 610used as-is. If you know that the service name is not in your services
601database, then you can specify the service in the format C<name=port> 611database, then you can specify the service in the format C<name=port>
602(e.g. C<http=80>). 612(e.g. C<http=80>).
603 613
614If a host cannot be found via DNS, then it will be looked up in
615F</etc/hosts> (or the file specified via C<< $ENV{PERL_ANYEVENT_HOSTS}
616>>). If they are found, the addresses there will be used. The effect is as
617if entries from F</etc/hosts> would yield C<A> and C<AAAA> records for the
618host name unless DNS already had records for them.
619
604For UNIX domain sockets, C<$node> must be the string C<unix/> and 620For UNIX domain sockets, C<$node> must be the string C<unix/> and
605C<$service> must be the absolute pathname of the socket. In this case, 621C<$service> must be the absolute pathname of the socket. In this case,
606C<$proto> will be ignored. 622C<$proto> will be ignored.
607 623
608C<$proto> must be a protocol name, currently C<tcp>, C<udp> or 624C<$proto> must be a protocol name, currently C<tcp>, C<udp> or
627Example: 643Example:
628 644
629 resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... }; 645 resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... };
630 646
631=cut 647=cut
648
649our %HOSTS;
650our $HOSTS;
651
652if (
653 open my $fh, "<",
654 length $ENV{PERL_ANYEVENT_HOSTS} ? $ENV{PERL_ANYEVENT_HOSTS}
655 : AnyEvent::WIN32 ? "$ENV{SystemRoot}/system32/drivers/etc/hosts"
656 : "/etc/hosts"
657) {
658 local $/;
659 binmode $fh;
660 $HOSTS = <$fh>;
661} else {
662 $HOSTS = "";
663}
664
665sub _parse_hosts() {
666 #%HOSTS = ();
667
668 for (split /\n/, $HOSTS) {
669 s/#.*$//;
670 s/^[ \t]+//;
671 y/A-Z/a-z/;
672
673 my ($addr, @aliases) = split /[ \t]+/;
674 next unless @aliases;
675
676 if (my $ip = parse_ipv4 $addr) {
677 push @{ $HOSTS{$_}[0] }, $ip
678 for @aliases;
679 } elsif (my $ip = parse_ipv6 $addr) {
680 push @{ $HOSTS{$_}[1] }, $ip
681 for @aliases;
682 }
683 }
684
685 undef $HOSTS;
686}
632 687
633sub resolve_sockaddr($$$$$$) { 688sub resolve_sockaddr($$$$$$) {
634 my ($node, $service, $proto, $family, $type, $cb) = @_; 689 my ($node, $service, $proto, $family, $type, $cb) = @_;
635 690
636 if ($node eq "unix/") { 691 if ($node eq "unix/") {
700 if ($af == AF_INET6 && $family != 4) { 755 if ($af == AF_INET6 && $family != 4) {
701 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton, 756 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton,
702 pack_sockaddr $port, $noden]] 757 pack_sockaddr $port, $noden]]
703 } 758 }
704 } else { 759 } else {
705 # ipv4 760 $node =~ y/A-Z/a-z/;
761
762 my $hosts = $HOSTS{$node};
763
764 # a records
706 if ($family != 6) { 765 if ($family != 6) {
707 $cv->begin; 766 $cv->begin;
708 AnyEvent::DNS::a $node, sub { 767 AnyEvent::DNS::a $node, sub {
709 push @res, [$idx, "ipv4", [AF_INET, $type, $proton, 768 push @res, [$idx, "ipv4", [AF_INET , $type, $proton, pack_sockaddr $port, parse_ipv4 $_]]
710 pack_sockaddr $port, parse_ipv4 $_]]
711 for @_; 769 for @_;
770
771 # dns takes precedence over hosts
772 push @res,
773 map [$idx, "ipv4", [AF_INET , $type, $proton, pack_sockaddr $port, $_]],
774 @{ $hosts->[0] }
775 unless @_;
776
712 $cv->end; 777 $cv->end;
713 }; 778 };
714 } 779 }
715 780
716 # ipv6 781 # aaaa records
717 if ($family != 4) { 782 if ($family != 4) {
718 $cv->begin; 783 $cv->begin;
719 AnyEvent::DNS::aaaa $node, sub { 784 AnyEvent::DNS::aaaa $node, sub {
720 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton, 785 push @res, [$idx, "ipv6", [AF_INET6, $type, $proton, pack_sockaddr $port, parse_ipv6 $_]]
721 pack_sockaddr $port, parse_ipv6 $_]]
722 for @_; 786 for @_;
787
788 push @res,
789 map [$idx + 0.5, "ipv6", [AF_INET6, $type, $proton, pack_sockaddr $port, $_]],
790 @{ $hosts->[1] }
791 unless @_;
792
723 $cv->end; 793 $cv->end;
724 }; 794 };
725 } 795 }
726 } 796 }
727 } 797 }
728 $cv->end; 798 $cv->end;
729 }; 799 };
730 800
731 $node = AnyEvent::Util::idn_to_ascii $node 801 $node = AnyEvent::Util::idn_to_ascii $node
732 if $node =~ /[^\x00-\x7f]/; 802 if $node =~ /[^\x00-\x7f]/;
803
804 # parse hosts
805 if (defined $HOSTS) {
806 _parse_hosts;
807 undef &_parse_hosts;
808 }
733 809
734 # try srv records, if applicable 810 # try srv records, if applicable
735 if ($node eq "localhost") { 811 if ($node eq "localhost") {
736 $resolve->(["127.0.0.1", $port], ["::1", $port]); 812 $resolve->(["127.0.0.1", $port], ["::1", $port]);
737 } elsif (defined $service && !parse_address $node) { 813 } elsif (defined $service && !parse_address $node) {
843 919
844 my $handle; # avoid direct assignment so on_eof has it in scope. 920 my $handle; # avoid direct assignment so on_eof has it in scope.
845 $handle = new AnyEvent::Handle 921 $handle = new AnyEvent::Handle
846 fh => $fh, 922 fh => $fh,
847 on_error => sub { 923 on_error => sub {
848 warn "error $_[2]\n"; 924 AE::log error => $_[2];
849 $_[0]->destroy; 925 $_[0]->destroy;
850 }, 926 },
851 on_eof => sub { 927 on_eof => sub {
852 $handle->destroy; # destroy handle 928 $handle->destroy; # destroy handle
853 warn "done.\n"; 929 AE::log info => "Done.";
854 }; 930 };
855 931
856 $handle->push_write ("GET / HTTP/1.0\015\012\015\012"); 932 $handle->push_write ("GET / HTTP/1.0\015\012\015\012");
857 933
858 $handle->push_read (line => "\015\012\015\012", sub { 934 $handle->push_read (line => "\015\012\015\012", sub {
895 my @target = @_; 971 my @target = @_;
896 972
897 $state{next} = sub { 973 $state{next} = sub {
898 return unless exists $state{fh}; 974 return unless exists $state{fh};
899 975
976 my $errno = $!;
900 my $target = shift @target 977 my $target = shift @target
901 or return _postpone sub { 978 or return AE::postpone {
902 return unless exists $state{fh}; 979 return unless exists $state{fh};
903 %state = (); 980 %state = ();
981 $! = $errno;
904 $connect->(); 982 $connect->();
905 }; 983 };
906 984
907 my ($domain, $type, $proto, $sockaddr) = @$target; 985 my ($domain, $type, $proto, $sockaddr) = @$target;
908 986
976 defined wantarray && guard { %state = () } 1054 defined wantarray && guard { %state = () }
977} 1055}
978 1056
979=item $guard = tcp_server $host, $service, $accept_cb[, $prepare_cb] 1057=item $guard = tcp_server $host, $service, $accept_cb[, $prepare_cb]
980 1058
981Create and bind a stream socket to the given host, and port, set the 1059Create and bind a stream socket to the given host address and port, set
982SO_REUSEADDR flag (if applicable) and call C<listen>. Unlike the name 1060the SO_REUSEADDR flag (if applicable) and call C<listen>. Unlike the name
983implies, this function can also bind on UNIX domain sockets. 1061implies, this function can also bind on UNIX domain sockets.
984 1062
985For internet sockets, C<$host> must be an IPv4 or IPv6 address (or 1063For internet sockets, C<$host> must be an IPv4 or IPv6 address (or
986C<undef>, in which case it binds either to C<0> or to C<::>, depending 1064C<undef>, in which case it binds either to C<0> or to C<::>, depending
987on whether IPv4 or IPv6 is the preferred protocol, and maybe to both in 1065on whether IPv4 or IPv6 is the preferred protocol, and maybe to both in
988future versions, as applicable). 1066future versions, as applicable).
989 1067
990To bind to the IPv4 wildcard address, use C<0>, to bind to the IPv6 1068To bind to the IPv4 wildcard address, use C<0>, to bind to the IPv6
991wildcard address, use C<::>. 1069wildcard address, use C<::>.
992 1070
993The port is specified by C<$service>, which must be either a service name or 1071The port is specified by C<$service>, which must be either a service name
994a numeric port number (or C<0> or C<undef>, in which case an ephemeral 1072or a numeric port number (or C<0> or C<undef>, in which case an ephemeral
995port will be used). 1073port will be used).
996 1074
997For UNIX domain sockets, C<$host> must be C<unix/> and C<$service> must be 1075For UNIX domain sockets, C<$host> must be C<unix/> and C<$service> must be
998the absolute pathname of the socket. This function will try to C<unlink> 1076the absolute pathname of the socket. This function will try to C<unlink>
999the socket before it tries to bind to it. See SECURITY CONSIDERATIONS, 1077the socket before it tries to bind to it, and will try to unlink it after
1000below. 1078it stops using it. See SECURITY CONSIDERATIONS, below.
1001 1079
1002For each new connection that could be C<accept>ed, call the C<< 1080For each new connection that could be C<accept>ed, call the C<<
1003$accept_cb->($fh, $host, $port) >> with the file handle (in non-blocking 1081$accept_cb->($fh, $host, $port) >> with the file handle (in non-blocking
1004mode) as first, and the peer host and port as second and third arguments 1082mode) as first, and the peer host and port as second and third arguments
1005(see C<tcp_connect> for details). 1083(see C<tcp_connect> for details).
1008 1086
1009If called in non-void context, then this function returns a guard object 1087If called in non-void context, then this function returns a guard object
1010whose lifetime it tied to the TCP server: If the object gets destroyed, 1088whose lifetime it tied to the TCP server: If the object gets destroyed,
1011the server will be stopped (but existing accepted connections will 1089the server will be stopped (but existing accepted connections will
1012not be affected). 1090not be affected).
1091
1092Regardless, when the function returns to the caller, the socket is bound
1093and in listening state.
1013 1094
1014If you need more control over the listening socket, you can provide a 1095If you need more control over the listening socket, you can provide a
1015C<< $prepare_cb->($fh, $host, $port) >>, which is called just before the 1096C<< $prepare_cb->($fh, $host, $port) >>, which is called just before the
1016C<listen ()> call, with the listen file handle as first argument, and IP 1097C<listen ()> call, with the listen file handle as first argument, and IP
1017address and port number of the local socket endpoint as second and third 1098address and port number of the local socket endpoint as second and third
1033 my ($fh, $host, $port) = @_; 1114 my ($fh, $host, $port) = @_;
1034 1115
1035 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012"; 1116 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
1036 }, sub { 1117 }, sub {
1037 my ($fh, $thishost, $thisport) = @_; 1118 my ($fh, $thishost, $thisport) = @_;
1038 warn "bound to $thishost, port $thisport\n"; 1119 AE::log info => "Bound to $thishost, port $thisport.";
1039 }; 1120 };
1040 1121
1041Example: bind a server on a unix domain socket. 1122Example: bind a server on a unix domain socket.
1042 1123
1043 tcp_server "unix/", "/tmp/mydir/mysocket", sub { 1124 tcp_server "unix/", "/tmp/mydir/mysocket", sub {
1081 } 1162 }
1082 1163
1083 bind $state{fh}, pack_sockaddr $service, $ipn 1164 bind $state{fh}, pack_sockaddr $service, $ipn
1084 or Carp::croak "bind: $!"; 1165 or Carp::croak "bind: $!";
1085 1166
1167 if ($af == AF_UNIX) {
1168 my $fh = $state{fh};
1169 my $ino = (stat $fh)[1];
1170 $state{unlink} = guard {
1171 # this is racy, but is not designed to be foolproof, just best-effort
1172 unlink $service
1173 if $ino == (stat $fh)[1];
1174 };
1175 }
1176
1086 fh_nonblocking $state{fh}, 1; 1177 fh_nonblocking $state{fh}, 1;
1087 1178
1088 my $len; 1179 my $len;
1089 1180
1090 if ($prepare) { 1181 if ($prepare) {
1138sub tcp_congestion($$) { 1229sub tcp_congestion($$) {
1139 defined TCP_CONGESTION 1230 defined TCP_CONGESTION
1140 ? setsockopt $_[0], Socket::IPPROTO_TCP (), TCP_CONGESTION, "$_[1]" 1231 ? setsockopt $_[0], Socket::IPPROTO_TCP (), TCP_CONGESTION, "$_[1]"
1141 : undef 1232 : undef
1142} 1233}
1143
11441;
1145 1234
1146=back 1235=back
1147 1236
1148=head1 SECURITY CONSIDERATIONS 1237=head1 SECURITY CONSIDERATIONS
1149 1238
1159 Marc Lehmann <schmorp@schmorp.de> 1248 Marc Lehmann <schmorp@schmorp.de>
1160 http://home.schmorp.de/ 1249 http://home.schmorp.de/
1161 1250
1162=cut 1251=cut
1163 1252
12531
1254

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines