1# You may distribute under the terms of either the GNU General Public License 2# or the Artistic License (the same terms as Perl itself) 3# 4# (C) Paul Evans, 2010-2023 -- leonerd@leonerd.org.uk 5 6package IO::Socket::IP 0.42; 7 8use v5.14; 9use warnings; 10 11use base qw( IO::Socket ); 12 13use Carp; 14 15use Socket 1.97 qw( 16 getaddrinfo getnameinfo 17 sockaddr_family 18 AF_INET 19 AI_PASSIVE 20 IPPROTO_TCP IPPROTO_UDP 21 IPPROTO_IPV6 IPV6_V6ONLY 22 NI_DGRAM NI_NUMERICHOST NI_NUMERICSERV NIx_NOHOST NIx_NOSERV 23 SO_REUSEADDR SO_REUSEPORT SO_BROADCAST SO_ERROR 24 SOCK_DGRAM SOCK_STREAM 25 SOL_SOCKET 26); 27my $AF_INET6 = eval { Socket::AF_INET6() }; # may not be defined 28my $AI_ADDRCONFIG = eval { Socket::AI_ADDRCONFIG() } || 0; 29use POSIX qw( dup2 ); 30use Errno qw( EINVAL EINPROGRESS EISCONN ENOTCONN ETIMEDOUT EWOULDBLOCK EOPNOTSUPP ); 31 32use constant HAVE_MSWIN32 => ( $^O eq "MSWin32" ); 33 34# At least one OS (Android) is known not to have getprotobyname() 35use constant HAVE_GETPROTOBYNAME => defined eval { getprotobyname( "tcp" ) }; 36 37my $IPv6_re = do { 38 # translation of RFC 3986 3.2.2 ABNF to re 39 my $IPv4address = do { 40 my $dec_octet = q<(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])>; 41 qq<$dec_octet(?: \\. $dec_octet){3}>; 42 }; 43 my $IPv6address = do { 44 my $h16 = qq<[0-9A-Fa-f]{1,4}>; 45 my $ls32 = qq<(?: $h16 : $h16 | $IPv4address)>; 46 qq<(?: 47 (?: $h16 : ){6} $ls32 48 | :: (?: $h16 : ){5} $ls32 49 | (?: $h16 )? :: (?: $h16 : ){4} $ls32 50 | (?: (?: $h16 : ){0,1} $h16 )? :: (?: $h16 : ){3} $ls32 51 | (?: (?: $h16 : ){0,2} $h16 )? :: (?: $h16 : ){2} $ls32 52 | (?: (?: $h16 : ){0,3} $h16 )? :: $h16 : $ls32 53 | (?: (?: $h16 : ){0,4} $h16 )? :: $ls32 54 | (?: (?: $h16 : ){0,5} $h16 )? :: $h16 55 | (?: (?: $h16 : ){0,6} $h16 )? :: 56 )> 57 }; 58 qr<$IPv6address>xo; 59}; 60 61=head1 NAME 62 63C<IO::Socket::IP> - Family-neutral IP socket supporting both IPv4 and IPv6 64 65=head1 SYNOPSIS 66 67 use IO::Socket::IP; 68 69 my $sock = IO::Socket::IP->new( 70 PeerHost => "www.google.com", 71 PeerPort => "http", 72 Type => SOCK_STREAM, 73 ) or die "Cannot construct socket - $IO::Socket::errstr"; 74 75 my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" : 76 ( $sock->sockdomain == PF_INET ) ? "IPv4" : 77 "unknown"; 78 79 printf "Connected to google via %s\n", $familyname; 80 81=head1 DESCRIPTION 82 83This module provides a protocol-independent way to use IPv4 and IPv6 sockets, 84intended as a replacement for L<IO::Socket::INET>. Most constructor arguments 85and methods are provided in a backward-compatible way. For a list of known 86differences, see the C<IO::Socket::INET> INCOMPATIBILITES section below. 87 88It uses the C<getaddrinfo(3)> function to convert hostnames and service names 89or port numbers into sets of possible addresses to connect to or listen on. 90This allows it to work for IPv6 where the system supports it, while still 91falling back to IPv4-only on systems which don't. 92 93=head1 REPLACING C<IO::Socket> DEFAULT BEHAVIOUR 94 95By placing C<-register> in the import list to C<IO::Socket::IP>, it will 96register itself with L<IO::Socket> as the class that handles C<PF_INET>. It 97will also ask to handle C<PF_INET6> as well, provided that constant is 98available. 99 100Changing C<IO::Socket>'s default behaviour means that calling the 101C<IO::Socket> constructor with either C<PF_INET> or C<PF_INET6> as the 102C<Domain> parameter will yield an C<IO::Socket::IP> object. 103 104 use IO::Socket::IP -register; 105 106 my $sock = IO::Socket->new( 107 Domain => PF_INET6, 108 LocalHost => "::1", 109 Listen => 1, 110 ) or die "Cannot create socket - $IO::Socket::errstr\n"; 111 112 print "Created a socket of type " . ref($sock) . "\n"; 113 114Note that C<-register> is a global setting that applies to the entire program; 115it cannot be applied only for certain callers, removed, or limited by lexical 116scope. 117 118=cut 119 120sub import 121{ 122 my $pkg = shift; 123 my @symbols; 124 125 foreach ( @_ ) { 126 if( $_ eq "-register" ) { 127 IO::Socket::IP::_ForINET->register_domain( AF_INET ); 128 IO::Socket::IP::_ForINET6->register_domain( $AF_INET6 ) if defined $AF_INET6; 129 } 130 else { 131 push @symbols, $_; 132 } 133 } 134 135 @_ = ( $pkg, @symbols ); 136 goto &IO::Socket::import; 137} 138 139# Convenient capability test function 140{ 141 my $can_disable_v6only; 142 sub CAN_DISABLE_V6ONLY 143 { 144 return $can_disable_v6only if defined $can_disable_v6only; 145 146 socket my $testsock, Socket::PF_INET6(), SOCK_STREAM, 0 or 147 die "Cannot socket(PF_INET6) - $!"; 148 149 if( setsockopt $testsock, IPPROTO_IPV6, IPV6_V6ONLY, 0 ) { 150 if( $^O eq "dragonfly") { 151 # dragonflybsd 6.4 lies about successfully turning this off 152 if( getsockopt $testsock, IPPROTO_IPV6, IPV6_V6ONLY ) { 153 return $can_disable_v6only = 0; 154 } 155 } 156 return $can_disable_v6only = 1; 157 } 158 elsif( $! == EINVAL || $! == EOPNOTSUPP ) { 159 return $can_disable_v6only = 0; 160 } 161 else { 162 die "Cannot setsockopt() - $!"; 163 } 164 } 165} 166 167=head1 CONSTRUCTORS 168 169=cut 170 171=head2 new 172 173 $sock = IO::Socket::IP->new( %args ) 174 175Creates a new C<IO::Socket::IP> object, containing a newly created socket 176handle according to the named arguments passed. The recognised arguments are: 177 178=over 8 179 180=item PeerHost => STRING 181 182=item PeerService => STRING 183 184Hostname and service name for the peer to C<connect()> to. The service name 185may be given as a port number, as a decimal string. 186 187=item PeerAddr => STRING 188 189=item PeerPort => STRING 190 191For symmetry with the accessor methods and compatibility with 192C<IO::Socket::INET>, these are accepted as synonyms for C<PeerHost> and 193C<PeerService> respectively. 194 195=item PeerAddrInfo => ARRAY 196 197Alternate form of specifying the peer to C<connect()> to. This should be an 198array of the form returned by C<Socket::getaddrinfo>. 199 200This parameter takes precedence over the C<Peer*>, C<Family>, C<Type> and 201C<Proto> arguments. 202 203=item LocalHost => STRING 204 205=item LocalService => STRING 206 207Hostname and service name for the local address to C<bind()> to. 208 209=item LocalAddr => STRING 210 211=item LocalPort => STRING 212 213For symmetry with the accessor methods and compatibility with 214C<IO::Socket::INET>, these are accepted as synonyms for C<LocalHost> and 215C<LocalService> respectively. 216 217=item LocalAddrInfo => ARRAY 218 219Alternate form of specifying the local address to C<bind()> to. This should be 220an array of the form returned by C<Socket::getaddrinfo>. 221 222This parameter takes precedence over the C<Local*>, C<Family>, C<Type> and 223C<Proto> arguments. 224 225=item Family => INT 226 227The address family to pass to C<getaddrinfo> (e.g. C<AF_INET>, C<AF_INET6>). 228Normally this will be left undefined, and C<getaddrinfo> will search using any 229address family supported by the system. 230 231=item Type => INT 232 233The socket type to pass to C<getaddrinfo> (e.g. C<SOCK_STREAM>, 234C<SOCK_DGRAM>). Normally defined by the caller; if left undefined 235C<getaddrinfo> may attempt to infer the type from the service name. 236 237=item Proto => STRING or INT 238 239The IP protocol to use for the socket (e.g. C<'tcp'>, C<IPPROTO_TCP>, 240C<'udp'>,C<IPPROTO_UDP>). Normally this will be left undefined, and either 241C<getaddrinfo> or the kernel will choose an appropriate value. May be given 242either in string name or numeric form. 243 244=item GetAddrInfoFlags => INT 245 246More flags to pass to the C<getaddrinfo()> function. If not supplied, a 247default of C<AI_ADDRCONFIG> will be used. 248 249These flags will be combined with C<AI_PASSIVE> if the C<Listen> argument is 250given. For more information see the documentation about C<getaddrinfo()> in 251the L<Socket> module. 252 253=item Listen => INT 254 255If defined, puts the socket into listening mode where new connections can be 256accepted using the C<accept> method. The value given is used as the 257C<listen(2)> queue size. 258 259=item ReuseAddr => BOOL 260 261If true, set the C<SO_REUSEADDR> sockopt 262 263=item ReusePort => BOOL 264 265If true, set the C<SO_REUSEPORT> sockopt (not all OSes implement this sockopt) 266 267=item Broadcast => BOOL 268 269If true, set the C<SO_BROADCAST> sockopt 270 271=item Sockopts => ARRAY 272 273An optional array of other socket options to apply after the three listed 274above. The value is an ARRAY containing 2- or 3-element ARRAYrefs. Each inner 275array relates to a single option, giving the level and option name, and an 276optional value. If the value element is missing, it will be given the value of 277a platform-sized integer 1 constant (i.e. suitable to enable most of the 278common boolean options). 279 280For example, both options given below are equivalent to setting C<ReuseAddr>. 281 282 Sockopts => [ 283 [ SOL_SOCKET, SO_REUSEADDR ], 284 [ SOL_SOCKET, SO_REUSEADDR, pack( "i", 1 ) ], 285 ] 286 287=item V6Only => BOOL 288 289If defined, set the C<IPV6_V6ONLY> sockopt when creating C<PF_INET6> sockets 290to the given value. If true, a listening-mode socket will only listen on the 291C<AF_INET6> addresses; if false it will also accept connections from 292C<AF_INET> addresses. 293 294If not defined, the socket option will not be changed, and default value set 295by the operating system will apply. For repeatable behaviour across platforms 296it is recommended this value always be defined for listening-mode sockets. 297 298Note that not all platforms support disabling this option. Some, at least 299OpenBSD and MirBSD, will fail with C<EINVAL> if you attempt to disable it. 300To determine whether it is possible to disable, you may use the class method 301 302 if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) { 303 ... 304 } 305 else { 306 ... 307 } 308 309If your platform does not support disabling this option but you still want to 310listen for both C<AF_INET> and C<AF_INET6> connections you will have to create 311two listening sockets, one bound to each protocol. 312 313=item MultiHomed 314 315This C<IO::Socket::INET>-style argument is ignored, except if it is defined 316but false. See the C<IO::Socket::INET> INCOMPATIBILITES section below. 317 318However, the behaviour it enables is always performed by C<IO::Socket::IP>. 319 320=item Blocking => BOOL 321 322If defined but false, the socket will be set to non-blocking mode. Otherwise 323it will default to blocking mode. See the NON-BLOCKING section below for more 324detail. 325 326=item Timeout => NUM 327 328If defined, gives a maximum time in seconds to block per C<connect()> call 329when in blocking mode. If missing, no timeout is applied other than that 330provided by the underlying operating system. When in non-blocking mode this 331parameter is ignored. 332 333Note that if the hostname resolves to multiple address candidates, the same 334timeout will apply to each connection attempt individually, rather than to the 335operation as a whole. Further note that the timeout does not apply to the 336initial hostname resolve operation, if connecting by hostname. 337 338This behaviour is copied inspired by C<IO::Socket::INET>; for more fine 339grained control over connection timeouts, consider performing a nonblocking 340connect directly. 341 342=back 343 344If neither C<Type> nor C<Proto> hints are provided, a default of 345C<SOCK_STREAM> and C<IPPROTO_TCP> respectively will be set, to maintain 346compatibility with C<IO::Socket::INET>. Other named arguments that are not 347recognised are ignored. 348 349If neither C<Family> nor any hosts or addresses are passed, nor any 350C<*AddrInfo>, then the constructor has no information on which to decide a 351socket family to create. In this case, it performs a C<getaddinfo> call with 352the C<AI_ADDRCONFIG> flag, no host name, and a service name of C<"0">, and 353uses the family of the first returned result. 354 355If the constructor fails, it will set C<$IO::Socket::errstr> and C<$@> to 356an appropriate error message; this may be from C<$!> or it may be some other 357string; not every failure necessarily has an associated C<errno> value. 358 359=head2 new (one arg) 360 361 $sock = IO::Socket::IP->new( $peeraddr ) 362 363As a special case, if the constructor is passed a single argument (as 364opposed to an even-sized list of key/value pairs), it is taken to be the value 365of the C<PeerAddr> parameter. This is parsed in the same way, according to the 366behaviour given in the C<PeerHost> AND C<LocalHost> PARSING section below. 367 368=cut 369 370sub new 371{ 372 my $class = shift; 373 my %arg = (@_ == 1) ? (PeerHost => $_[0]) : @_; 374 return $class->SUPER::new(%arg); 375} 376 377# IO::Socket may call this one; neaten up the arguments from IO::Socket::INET 378# before calling our real _configure method 379sub configure 380{ 381 my $self = shift; 382 my ( $arg ) = @_; 383 384 $arg->{PeerHost} = delete $arg->{PeerAddr} 385 if exists $arg->{PeerAddr} && !exists $arg->{PeerHost}; 386 387 $arg->{PeerService} = delete $arg->{PeerPort} 388 if exists $arg->{PeerPort} && !exists $arg->{PeerService}; 389 390 $arg->{LocalHost} = delete $arg->{LocalAddr} 391 if exists $arg->{LocalAddr} && !exists $arg->{LocalHost}; 392 393 $arg->{LocalService} = delete $arg->{LocalPort} 394 if exists $arg->{LocalPort} && !exists $arg->{LocalService}; 395 396 for my $type (qw(Peer Local)) { 397 my $host = $type . 'Host'; 398 my $service = $type . 'Service'; 399 400 if( defined $arg->{$host} ) { 401 ( $arg->{$host}, my $s ) = $self->split_addr( $arg->{$host} ); 402 # IO::Socket::INET compat - *Host parsed port always takes precedence 403 $arg->{$service} = $s if defined $s; 404 } 405 } 406 407 $self->_io_socket_ip__configure( $arg ); 408} 409 410# Avoid simply calling it _configure, as some subclasses of IO::Socket::INET on CPAN already take that 411sub _io_socket_ip__configure 412{ 413 my $self = shift; 414 my ( $arg ) = @_; 415 416 my %hints; 417 my @localinfos; 418 my @peerinfos; 419 420 my $listenqueue = $arg->{Listen}; 421 if( defined $listenqueue and 422 ( defined $arg->{PeerHost} || defined $arg->{PeerService} || defined $arg->{PeerAddrInfo} ) ) { 423 croak "Cannot Listen with a peer address"; 424 } 425 426 if( defined $arg->{GetAddrInfoFlags} ) { 427 $hints{flags} = $arg->{GetAddrInfoFlags}; 428 } 429 else { 430 $hints{flags} = $AI_ADDRCONFIG; 431 } 432 433 if( defined( my $family = $arg->{Family} ) ) { 434 $hints{family} = $family; 435 } 436 437 if( defined( my $type = $arg->{Type} ) ) { 438 $hints{socktype} = $type; 439 } 440 441 if( defined( my $proto = $arg->{Proto} ) ) { 442 unless( $proto =~ m/^\d+$/ ) { 443 my $protonum = HAVE_GETPROTOBYNAME 444 ? getprotobyname( $proto ) 445 : eval { Socket->${\"IPPROTO_\U$proto"}() }; 446 defined $protonum or croak "Unrecognised protocol $proto"; 447 $proto = $protonum; 448 } 449 450 $hints{protocol} = $proto; 451 } 452 453 # To maintain compatibility with IO::Socket::INET, imply a default of 454 # SOCK_STREAM + IPPROTO_TCP if neither hint is given 455 if( !defined $hints{socktype} and !defined $hints{protocol} ) { 456 $hints{socktype} = SOCK_STREAM; 457 $hints{protocol} = IPPROTO_TCP; 458 } 459 460 # Some OSes (NetBSD) don't seem to like just a protocol hint without a 461 # socktype hint as well. We'll set a couple of common ones 462 if( !defined $hints{socktype} and defined $hints{protocol} ) { 463 $hints{socktype} = SOCK_STREAM if $hints{protocol} == IPPROTO_TCP; 464 $hints{socktype} = SOCK_DGRAM if $hints{protocol} == IPPROTO_UDP; 465 } 466 467 if( my $info = $arg->{LocalAddrInfo} ) { 468 ref $info eq "ARRAY" or croak "Expected 'LocalAddrInfo' to be an ARRAY ref"; 469 @localinfos = @$info; 470 } 471 elsif( defined $arg->{LocalHost} or 472 defined $arg->{LocalService} or 473 HAVE_MSWIN32 and $arg->{Listen} ) { 474 # Either may be undef 475 my $host = $arg->{LocalHost}; 476 my $service = $arg->{LocalService}; 477 478 unless ( defined $host or defined $service ) { 479 $service = 0; 480 } 481 482 local $1; # Placate a taint-related bug; [perl #67962] 483 defined $service and $service =~ s/\((\d+)\)$// and 484 my $fallback_port = $1; 485 486 my %localhints = %hints; 487 $localhints{flags} |= AI_PASSIVE; 488 ( my $err, @localinfos ) = getaddrinfo( $host, $service, \%localhints ); 489 490 if( $err and defined $fallback_port ) { 491 ( $err, @localinfos ) = getaddrinfo( $host, $fallback_port, \%localhints ); 492 } 493 494 if( $err ) { 495 $IO::Socket::errstr = $@ = "$err"; 496 $! = EINVAL; 497 return; 498 } 499 } 500 501 if( my $info = $arg->{PeerAddrInfo} ) { 502 ref $info eq "ARRAY" or croak "Expected 'PeerAddrInfo' to be an ARRAY ref"; 503 @peerinfos = @$info; 504 } 505 elsif( defined $arg->{PeerHost} or defined $arg->{PeerService} ) { 506 defined( my $host = $arg->{PeerHost} ) or 507 croak "Expected 'PeerHost'"; 508 defined( my $service = $arg->{PeerService} ) or 509 croak "Expected 'PeerService'"; 510 511 local $1; # Placate a taint-related bug; [perl #67962] 512 defined $service and $service =~ s/\((\d+)\)$// and 513 my $fallback_port = $1; 514 515 ( my $err, @peerinfos ) = getaddrinfo( $host, $service, \%hints ); 516 517 if( $err and defined $fallback_port ) { 518 ( $err, @peerinfos ) = getaddrinfo( $host, $fallback_port, \%hints ); 519 } 520 521 if( $err ) { 522 $IO::Socket::errstr = $@ = "$err"; 523 $! = EINVAL; 524 return; 525 } 526 } 527 528 my $INT_1 = pack "i", 1; 529 530 my @sockopts_enabled; 531 push @sockopts_enabled, [ SOL_SOCKET, SO_REUSEADDR, $INT_1 ] if $arg->{ReuseAddr}; 532 push @sockopts_enabled, [ SOL_SOCKET, SO_REUSEPORT, $INT_1 ] if $arg->{ReusePort}; 533 push @sockopts_enabled, [ SOL_SOCKET, SO_BROADCAST, $INT_1 ] if $arg->{Broadcast}; 534 535 if( my $sockopts = $arg->{Sockopts} ) { 536 ref $sockopts eq "ARRAY" or croak "Expected 'Sockopts' to be an ARRAY ref"; 537 foreach ( @$sockopts ) { 538 ref $_ eq "ARRAY" or croak "Bad Sockopts item - expected ARRAYref"; 539 @$_ >= 2 and @$_ <= 3 or 540 croak "Bad Sockopts item - expected 2 or 3 elements"; 541 542 my ( $level, $optname, $value ) = @$_; 543 # TODO: consider more sanity checking on argument values 544 545 defined $value or $value = $INT_1; 546 push @sockopts_enabled, [ $level, $optname, $value ]; 547 } 548 } 549 550 my $blocking = $arg->{Blocking}; 551 defined $blocking or $blocking = 1; 552 553 my $v6only = $arg->{V6Only}; 554 555 # IO::Socket::INET defines this key. IO::Socket::IP always implements the 556 # behaviour it requests, so we can ignore it, unless the caller is for some 557 # reason asking to disable it. 558 if( defined $arg->{MultiHomed} and !$arg->{MultiHomed} ) { 559 croak "Cannot disable the MultiHomed parameter"; 560 } 561 562 my @infos; 563 foreach my $local ( @localinfos ? @localinfos : {} ) { 564 foreach my $peer ( @peerinfos ? @peerinfos : {} ) { 565 next if defined $local->{family} and defined $peer->{family} and 566 $local->{family} != $peer->{family}; 567 next if defined $local->{socktype} and defined $peer->{socktype} and 568 $local->{socktype} != $peer->{socktype}; 569 next if defined $local->{protocol} and defined $peer->{protocol} and 570 $local->{protocol} != $peer->{protocol}; 571 572 my $family = $local->{family} || $peer->{family} or next; 573 my $socktype = $local->{socktype} || $peer->{socktype} or next; 574 my $protocol = $local->{protocol} || $peer->{protocol} || 0; 575 576 push @infos, { 577 family => $family, 578 socktype => $socktype, 579 protocol => $protocol, 580 localaddr => $local->{addr}, 581 peeraddr => $peer->{addr}, 582 }; 583 } 584 } 585 586 if( !@infos ) { 587 # If there was a Family hint then create a plain unbound, unconnected socket 588 if( defined $hints{family} ) { 589 @infos = ( { 590 family => $hints{family}, 591 socktype => $hints{socktype}, 592 protocol => $hints{protocol}, 593 } ); 594 } 595 # If there wasn't, use getaddrinfo()'s AI_ADDRCONFIG side-effect to guess a 596 # suitable family first. 597 else { 598 ( my $err, @infos ) = getaddrinfo( "", "0", \%hints ); 599 if( $err ) { 600 $IO::Socket::errstr = $@ = "$err"; 601 $! = EINVAL; 602 return; 603 } 604 605 # We'll take all the @infos anyway, because some OSes (HPUX) are known to 606 # ignore the AI_ADDRCONFIG hint and return AF_INET6 even if they don't 607 # support them 608 } 609 } 610 611 # In the nonblocking case, caller will be calling ->setup multiple times. 612 # Store configuration in the object for the ->setup method 613 # Yes, these are messy. Sorry, I can't help that... 614 615 ${*$self}{io_socket_ip_infos} = \@infos; 616 617 ${*$self}{io_socket_ip_idx} = -1; 618 619 ${*$self}{io_socket_ip_sockopts} = \@sockopts_enabled; 620 ${*$self}{io_socket_ip_v6only} = $v6only; 621 ${*$self}{io_socket_ip_listenqueue} = $listenqueue; 622 ${*$self}{io_socket_ip_blocking} = $blocking; 623 624 ${*$self}{io_socket_ip_errors} = [ undef, undef, undef ]; 625 626 # ->setup is allowed to return false in nonblocking mode 627 $self->setup or !$blocking or return undef; 628 629 return $self; 630} 631 632sub setup 633{ 634 my $self = shift; 635 636 while(1) { 637 ${*$self}{io_socket_ip_idx}++; 638 last if ${*$self}{io_socket_ip_idx} >= @{ ${*$self}{io_socket_ip_infos} }; 639 640 my $info = ${*$self}{io_socket_ip_infos}->[${*$self}{io_socket_ip_idx}]; 641 642 $self->socket( @{$info}{qw( family socktype protocol )} ) or 643 ( ${*$self}{io_socket_ip_errors}[2] = $!, next ); 644 645 $self->blocking( 0 ) unless ${*$self}{io_socket_ip_blocking}; 646 647 foreach my $sockopt ( @{ ${*$self}{io_socket_ip_sockopts} } ) { 648 my ( $level, $optname, $value ) = @$sockopt; 649 $self->setsockopt( $level, $optname, $value ) or 650 ( $IO::Socket::errstr = $@ = "$!", return undef ); 651 } 652 653 if( defined ${*$self}{io_socket_ip_v6only} and defined $AF_INET6 and $info->{family} == $AF_INET6 ) { 654 my $v6only = ${*$self}{io_socket_ip_v6only}; 655 $self->setsockopt( IPPROTO_IPV6, IPV6_V6ONLY, pack "i", $v6only ) or 656 ( $IO::Socket::errstr = $@ = "$!", return undef ); 657 } 658 659 if( defined( my $addr = $info->{localaddr} ) ) { 660 $self->bind( $addr ) or 661 ( ${*$self}{io_socket_ip_errors}[1] = $!, next ); 662 } 663 664 if( defined( my $listenqueue = ${*$self}{io_socket_ip_listenqueue} ) ) { 665 $self->listen( $listenqueue ) or 666 ( $IO::Socket::errstr = $@ = "$!", return undef ); 667 } 668 669 if( defined( my $addr = $info->{peeraddr} ) ) { 670 if( $self->connect( $addr ) ) { 671 $! = 0; 672 return 1; 673 } 674 675 if( $! == EINPROGRESS or $! == EWOULDBLOCK ) { 676 ${*$self}{io_socket_ip_connect_in_progress} = 1; 677 return 0; 678 } 679 680 # If connect failed but we have no system error there must be an error 681 # at the application layer, like a bad certificate with 682 # IO::Socket::SSL. 683 # In this case don't continue IP based multi-homing because the problem 684 # cannot be solved at the IP layer. 685 return 0 if ! $!; 686 687 ${*$self}{io_socket_ip_errors}[0] = $!; 688 next; 689 } 690 691 return 1; 692 } 693 694 # Pick the most appropriate error, stringified 695 $! = ( grep defined, @{ ${*$self}{io_socket_ip_errors}} )[0]; 696 $IO::Socket::errstr = $@ = "$!"; 697 return undef; 698} 699 700sub connect :method 701{ 702 my $self = shift; 703 704 # It seems that IO::Socket hides EINPROGRESS errors, making them look like 705 # a success. This is annoying here. 706 # Instead of putting up with its frankly-irritating intentional breakage of 707 # useful APIs I'm just going to end-run around it and call core's connect() 708 # directly 709 710 if( @_ ) { 711 my ( $addr ) = @_; 712 713 # Annoyingly IO::Socket's connect() is where the timeout logic is 714 # implemented, so we'll have to reinvent it here 715 my $timeout = ${*$self}{'io_socket_timeout'}; 716 717 return connect( $self, $addr ) unless defined $timeout; 718 719 my $was_blocking = $self->blocking( 0 ); 720 721 my $err = defined connect( $self, $addr ) ? 0 : $!+0; 722 723 if( !$err ) { 724 # All happy 725 $self->blocking( $was_blocking ); 726 return 1; 727 } 728 elsif( not( $err == EINPROGRESS or $err == EWOULDBLOCK ) ) { 729 # Failed for some other reason 730 $self->blocking( $was_blocking ); 731 return undef; 732 } 733 elsif( !$was_blocking ) { 734 # We shouldn't block anyway 735 return undef; 736 } 737 738 my $vec = ''; vec( $vec, $self->fileno, 1 ) = 1; 739 if( !select( undef, $vec, $vec, $timeout ) ) { 740 $self->blocking( $was_blocking ); 741 $! = ETIMEDOUT; 742 return undef; 743 } 744 745 # Hoist the error by connect()ing a second time 746 $err = $self->getsockopt( SOL_SOCKET, SO_ERROR ); 747 $err = 0 if $err == EISCONN; # Some OSes give EISCONN 748 749 $self->blocking( $was_blocking ); 750 751 $! = $err, return undef if $err; 752 return 1; 753 } 754 755 return 1 if !${*$self}{io_socket_ip_connect_in_progress}; 756 757 # See if a connect attempt has just failed with an error 758 if( my $errno = $self->getsockopt( SOL_SOCKET, SO_ERROR ) ) { 759 delete ${*$self}{io_socket_ip_connect_in_progress}; 760 ${*$self}{io_socket_ip_errors}[0] = $! = $errno; 761 return $self->setup; 762 } 763 764 # No error, so either connect is still in progress, or has completed 765 # successfully. We can tell by trying to connect() again; either it will 766 # succeed or we'll get EISCONN (connected successfully), or EALREADY 767 # (still in progress). This even works on MSWin32. 768 my $addr = ${*$self}{io_socket_ip_infos}[${*$self}{io_socket_ip_idx}]{peeraddr}; 769 770 if( connect( $self, $addr ) or $! == EISCONN ) { 771 delete ${*$self}{io_socket_ip_connect_in_progress}; 772 $! = 0; 773 return 1; 774 } 775 else { 776 $! = EINPROGRESS; 777 return 0; 778 } 779} 780 781sub connected 782{ 783 my $self = shift; 784 return defined $self->fileno && 785 !${*$self}{io_socket_ip_connect_in_progress} && 786 defined getpeername( $self ); # ->peername caches, we need to detect disconnection 787} 788 789=head1 METHODS 790 791As well as the following methods, this class inherits all the methods in 792L<IO::Socket> and L<IO::Handle>. 793 794=cut 795 796sub _get_host_service 797{ 798 my $self = shift; 799 my ( $addr, $flags, $xflags ) = @_; 800 801 defined $addr or 802 $! = ENOTCONN, return; 803 804 $flags |= NI_DGRAM if $self->socktype == SOCK_DGRAM; 805 806 my ( $err, $host, $service ) = getnameinfo( $addr, $flags, $xflags || 0 ); 807 croak "getnameinfo - $err" if $err; 808 809 return ( $host, $service ); 810} 811 812sub _unpack_sockaddr 813{ 814 my ( $addr ) = @_; 815 my $family = sockaddr_family $addr; 816 817 if( $family == AF_INET ) { 818 return ( Socket::unpack_sockaddr_in( $addr ) )[1]; 819 } 820 elsif( defined $AF_INET6 and $family == $AF_INET6 ) { 821 return ( Socket::unpack_sockaddr_in6( $addr ) )[1]; 822 } 823 else { 824 croak "Unrecognised address family $family"; 825 } 826} 827 828=head2 sockhost_service 829 830 ( $host, $service ) = $sock->sockhost_service( $numeric ) 831 832Returns the hostname and service name of the local address (that is, the 833socket address given by the C<sockname> method). 834 835If C<$numeric> is true, these will be given in numeric form rather than being 836resolved into names. 837 838The following four convenience wrappers may be used to obtain one of the two 839values returned here. If both host and service names are required, this method 840is preferable to the following wrappers, because it will call 841C<getnameinfo(3)> only once. 842 843=cut 844 845sub sockhost_service 846{ 847 my $self = shift; 848 my ( $numeric ) = @_; 849 850 $self->_get_host_service( $self->sockname, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 ); 851} 852 853=head2 sockhost 854 855 $addr = $sock->sockhost 856 857Return the numeric form of the local address as a textual representation 858 859=head2 sockport 860 861 $port = $sock->sockport 862 863Return the numeric form of the local port number 864 865=head2 sockhostname 866 867 $host = $sock->sockhostname 868 869Return the resolved name of the local address 870 871=head2 sockservice 872 873 $service = $sock->sockservice 874 875Return the resolved name of the local port number 876 877=cut 878 879sub sockhost { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, NI_NUMERICHOST, NIx_NOSERV ) )[0] } 880sub sockport { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, NI_NUMERICSERV, NIx_NOHOST ) )[1] } 881 882sub sockhostname { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, 0, NIx_NOSERV ) )[0] } 883sub sockservice { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, 0, NIx_NOHOST ) )[1] } 884 885=head2 sockaddr 886 887 $addr = $sock->sockaddr 888 889Return the local address as a binary octet string 890 891=cut 892 893sub sockaddr { my $self = shift; _unpack_sockaddr $self->sockname } 894 895=head2 peerhost_service 896 897 ( $host, $service ) = $sock->peerhost_service( $numeric ) 898 899Returns the hostname and service name of the peer address (that is, the 900socket address given by the C<peername> method), similar to the 901C<sockhost_service> method. 902 903The following four convenience wrappers may be used to obtain one of the two 904values returned here. If both host and service names are required, this method 905is preferable to the following wrappers, because it will call 906C<getnameinfo(3)> only once. 907 908=cut 909 910sub peerhost_service 911{ 912 my $self = shift; 913 my ( $numeric ) = @_; 914 915 $self->_get_host_service( $self->peername, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 ); 916} 917 918=head2 peerhost 919 920 $addr = $sock->peerhost 921 922Return the numeric form of the peer address as a textual representation 923 924=head2 peerport 925 926 $port = $sock->peerport 927 928Return the numeric form of the peer port number 929 930=head2 peerhostname 931 932 $host = $sock->peerhostname 933 934Return the resolved name of the peer address 935 936=head2 peerservice 937 938 $service = $sock->peerservice 939 940Return the resolved name of the peer port number 941 942=cut 943 944sub peerhost { my $self = shift; scalar +( $self->_get_host_service( $self->peername, NI_NUMERICHOST, NIx_NOSERV ) )[0] } 945sub peerport { my $self = shift; scalar +( $self->_get_host_service( $self->peername, NI_NUMERICSERV, NIx_NOHOST ) )[1] } 946 947sub peerhostname { my $self = shift; scalar +( $self->_get_host_service( $self->peername, 0, NIx_NOSERV ) )[0] } 948sub peerservice { my $self = shift; scalar +( $self->_get_host_service( $self->peername, 0, NIx_NOHOST ) )[1] } 949 950=head2 peeraddr 951 952 $addr = $peer->peeraddr 953 954Return the peer address as a binary octet string 955 956=cut 957 958sub peeraddr { my $self = shift; _unpack_sockaddr $self->peername } 959 960# This unbelievably dodgy hack works around the bug that IO::Socket doesn't do 961# it 962# https://rt.cpan.org/Ticket/Display.html?id=61577 963sub accept 964{ 965 my $self = shift; 966 my ( $new, $peer ) = $self->SUPER::accept( @_ ) or return; 967 968 ${*$new}{$_} = ${*$self}{$_} for qw( io_socket_domain io_socket_type io_socket_proto ); 969 970 return wantarray ? ( $new, $peer ) 971 : $new; 972} 973 974# This second unbelievably dodgy hack guarantees that $self->fileno doesn't 975# change, which is useful during nonblocking connect 976sub socket :method 977{ 978 my $self = shift; 979 return $self->SUPER::socket(@_) if not defined $self->fileno; 980 981 # I hate core prototypes sometimes... 982 socket( my $tmph, $_[0], $_[1], $_[2] ) or return undef; 983 984 dup2( $tmph->fileno, $self->fileno ) or die "Unable to dup2 $tmph onto $self - $!"; 985} 986 987# Versions of IO::Socket before 1.35 may leave socktype undef if from, say, an 988# ->fdopen call. In this case we'll apply a fix 989BEGIN { 990 if( eval($IO::Socket::VERSION) < 1.35 ) { 991 *socktype = sub { 992 my $self = shift; 993 my $type = $self->SUPER::socktype; 994 if( !defined $type ) { 995 $type = $self->sockopt( Socket::SO_TYPE() ); 996 } 997 return $type; 998 }; 999 } 1000} 1001 1002=head2 as_inet 1003 1004 $inet = $sock->as_inet 1005 1006Returns a new L<IO::Socket::INET> instance wrapping the same filehandle. This 1007may be useful in cases where it is required, for backward-compatibility, to 1008have a real object of C<IO::Socket::INET> type instead of C<IO::Socket::IP>. 1009The new object will wrap the same underlying socket filehandle as the 1010original, so care should be taken not to continue to use both objects 1011concurrently. Ideally the original C<$sock> should be discarded after this 1012method is called. 1013 1014This method checks that the socket domain is C<PF_INET> and will throw an 1015exception if it isn't. 1016 1017=cut 1018 1019sub as_inet 1020{ 1021 my $self = shift; 1022 croak "Cannot downgrade a non-PF_INET socket to IO::Socket::INET" unless $self->sockdomain == AF_INET; 1023 return IO::Socket::INET->new_from_fd( $self->fileno, "r+" ); 1024} 1025 1026=head1 NON-BLOCKING 1027 1028If the constructor is passed a defined but false value for the C<Blocking> 1029argument then the socket is put into non-blocking mode. When in non-blocking 1030mode, the socket will not be set up by the time the constructor returns, 1031because the underlying C<connect(2)> syscall would otherwise have to block. 1032 1033The non-blocking behaviour is an extension of the C<IO::Socket::INET> API, 1034unique to C<IO::Socket::IP>, because the former does not support multi-homed 1035non-blocking connect. 1036 1037When using non-blocking mode, the caller must repeatedly check for 1038writeability on the filehandle (for instance using C<select> or C<IO::Poll>). 1039Each time the filehandle is ready to write, the C<connect> method must be 1040called, with no arguments. Note that some operating systems, most notably 1041C<MSWin32> do not report a C<connect()> failure using write-ready; so you must 1042also C<select()> for exceptional status. 1043 1044While C<connect> returns false, the value of C<$!> indicates whether it should 1045be tried again (by being set to the value C<EINPROGRESS>, or C<EWOULDBLOCK> on 1046MSWin32), or whether a permanent error has occurred (e.g. C<ECONNREFUSED>). 1047 1048Once the socket has been connected to the peer, C<connect> will return true 1049and the socket will now be ready to use. 1050 1051Note that calls to the platform's underlying C<getaddrinfo(3)> function may 1052block. If C<IO::Socket::IP> has to perform this lookup, the constructor will 1053block even when in non-blocking mode. 1054 1055To avoid this blocking behaviour, the caller should pass in the result of such 1056a lookup using the C<PeerAddrInfo> or C<LocalAddrInfo> arguments. This can be 1057achieved by using L<Net::LibAsyncNS>, or the C<getaddrinfo(3)> function can be 1058called in a child process. 1059 1060 use IO::Socket::IP; 1061 use Errno qw( EINPROGRESS EWOULDBLOCK ); 1062 1063 my @peeraddrinfo = ... # Caller must obtain the getaddinfo result here 1064 1065 my $socket = IO::Socket::IP->new( 1066 PeerAddrInfo => \@peeraddrinfo, 1067 Blocking => 0, 1068 ) or die "Cannot construct socket - $@"; 1069 1070 while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) { 1071 my $wvec = ''; 1072 vec( $wvec, fileno $socket, 1 ) = 1; 1073 my $evec = ''; 1074 vec( $evec, fileno $socket, 1 ) = 1; 1075 1076 select( undef, $wvec, $evec, undef ) or die "Cannot select - $!"; 1077 } 1078 1079 die "Cannot connect - $!" if $!; 1080 1081 ... 1082 1083The example above uses C<select()>, but any similar mechanism should work 1084analogously. C<IO::Socket::IP> takes care when creating new socket filehandles 1085to preserve the actual file descriptor number, so such techniques as C<poll> 1086or C<epoll> should be transparent to its reallocation of a different socket 1087underneath, perhaps in order to switch protocol family between C<PF_INET> and 1088C<PF_INET6>. 1089 1090For another example using C<IO::Poll> and C<Net::LibAsyncNS>, see the 1091F<examples/nonblocking_libasyncns.pl> file in the module distribution. 1092 1093=cut 1094 1095=head1 C<PeerHost> AND C<LocalHost> PARSING 1096 1097To support the C<IO::Socket::INET> API, the host and port information may be 1098passed in a single string rather than as two separate arguments. 1099 1100If either C<LocalHost> or C<PeerHost> (or their C<...Addr> synonyms) have any 1101of the following special forms then special parsing is applied. 1102 1103The value of the C<...Host> argument will be split to give both the hostname 1104and port (or service name): 1105 1106 hostname.example.org:http # Host name 1107 192.0.2.1:80 # IPv4 address 1108 [2001:db8::1]:80 # IPv6 address 1109 1110In each case, the port or service name (e.g. C<80>) is passed as the 1111C<LocalService> or C<PeerService> argument. 1112 1113Either of C<LocalService> or C<PeerService> (or their C<...Port> synonyms) can 1114be either a service name, a decimal number, or a string containing both a 1115service name and number, in a form such as 1116 1117 http(80) 1118 1119In this case, the name (C<http>) will be tried first, but if the resolver does 1120not understand it then the port number (C<80>) will be used instead. 1121 1122If the C<...Host> argument is in this special form and the corresponding 1123C<...Service> or C<...Port> argument is also defined, the one parsed from 1124the C<...Host> argument will take precedence and the other will be ignored. 1125 1126=head2 split_addr 1127 1128 ( $host, $port ) = IO::Socket::IP->split_addr( $addr ) 1129 1130Utility method that provides the parsing functionality described above. 1131Returns a 2-element list, containing either the split hostname and port 1132description if it could be parsed, or the given address and C<undef> if it was 1133not recognised. 1134 1135 IO::Socket::IP->split_addr( "hostname:http" ) 1136 # ( "hostname", "http" ) 1137 1138 IO::Socket::IP->split_addr( "192.0.2.1:80" ) 1139 # ( "192.0.2.1", "80" ) 1140 1141 IO::Socket::IP->split_addr( "[2001:db8::1]:80" ) 1142 # ( "2001:db8::1", "80" ) 1143 1144 IO::Socket::IP->split_addr( "something.else" ) 1145 # ( "something.else", undef ) 1146 1147=cut 1148 1149sub split_addr 1150{ 1151 shift; 1152 my ( $addr ) = @_; 1153 1154 local ( $1, $2 ); # Placate a taint-related bug; [perl #67962] 1155 if( $addr =~ m/\A\[($IPv6_re)\](?::([^\s:]*))?\z/ or 1156 $addr =~ m/\A([^\s:]*):([^\s:]*)\z/ ) { 1157 return ( $1, $2 ) if defined $2 and length $2; 1158 return ( $1, undef ); 1159 } 1160 1161 return ( $addr, undef ); 1162} 1163 1164=head2 join_addr 1165 1166 $addr = IO::Socket::IP->join_addr( $host, $port ) 1167 1168Utility method that performs the reverse of C<split_addr>, returning a string 1169formed by joining the specified host address and port number. The host address 1170will be wrapped in C<[]> brackets if required (because it is a raw IPv6 1171numeric address). 1172 1173This can be especially useful when combined with the C<sockhost_service> or 1174C<peerhost_service> methods. 1175 1176 say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service ); 1177 1178=cut 1179 1180sub join_addr 1181{ 1182 shift; 1183 my ( $host, $port ) = @_; 1184 1185 $host = "[$host]" if $host =~ m/:/; 1186 1187 return join ":", $host, $port if defined $port; 1188 return $host; 1189} 1190 1191# Since IO::Socket->new( Domain => ... ) will delete the Domain parameter 1192# before calling ->configure, we need to keep track of which it was 1193 1194package # hide from indexer 1195 IO::Socket::IP::_ForINET; 1196use base qw( IO::Socket::IP ); 1197 1198sub configure 1199{ 1200 # This is evil 1201 my $self = shift; 1202 my ( $arg ) = @_; 1203 1204 bless $self, "IO::Socket::IP"; 1205 $self->configure( { %$arg, Family => Socket::AF_INET() } ); 1206} 1207 1208package # hide from indexer 1209 IO::Socket::IP::_ForINET6; 1210use base qw( IO::Socket::IP ); 1211 1212sub configure 1213{ 1214 # This is evil 1215 my $self = shift; 1216 my ( $arg ) = @_; 1217 1218 bless $self, "IO::Socket::IP"; 1219 $self->configure( { %$arg, Family => Socket::AF_INET6() } ); 1220} 1221 1222=head1 C<IO::Socket::INET> INCOMPATIBILITES 1223 1224=over 4 1225 1226=item * 1227 1228The behaviour enabled by C<MultiHomed> is in fact implemented by 1229C<IO::Socket::IP> as it is required to correctly support searching for a 1230useable address from the results of the C<getaddrinfo(3)> call. The 1231constructor will ignore the value of this argument, except if it is defined 1232but false. An exception is thrown in this case, because that would request it 1233disable the C<getaddrinfo(3)> search behaviour in the first place. 1234 1235=item * 1236 1237C<IO::Socket::IP> implements both the C<Blocking> and C<Timeout> parameters, 1238but it implements the interaction of both in a different way. 1239 1240In C<::INET>, supplying a timeout overrides the non-blocking behaviour, 1241meaning that the C<connect()> operation will still block despite that the 1242caller asked for a non-blocking socket. This is not explicitly specified in 1243its documentation, nor does this author believe that is a useful behaviour - 1244it appears to come from a quirk of implementation. 1245 1246In C<::IP> therefore, the C<Blocking> parameter takes precedence - if a 1247non-blocking socket is requested, no operation will block. The C<Timeout> 1248parameter here simply defines the maximum time that a blocking C<connect()> 1249call will wait, if it blocks at all. 1250 1251In order to specifically obtain the "blocking connect then non-blocking send 1252and receive" behaviour of specifying this combination of options to C<::INET> 1253when using C<::IP>, perform first a blocking connect, then afterwards turn the 1254socket into nonblocking mode. 1255 1256 my $sock = IO::Socket::IP->new( 1257 PeerHost => $peer, 1258 Timeout => 20, 1259 ) or die "Cannot connect - $@"; 1260 1261 $sock->blocking( 0 ); 1262 1263This code will behave identically under both C<IO::Socket::INET> and 1264C<IO::Socket::IP>. 1265 1266=back 1267 1268=cut 1269 1270=head1 TODO 1271 1272=over 4 1273 1274=item * 1275 1276Investigate whether C<POSIX::dup2> upsets BSD's C<kqueue> watchers, and if so, 1277consider what possible workarounds might be applied. 1278 1279=back 1280 1281=head1 AUTHOR 1282 1283Paul Evans <leonerd@leonerd.org.uk> 1284 1285=cut 1286 12870x55AA; 1288