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