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