AnyEvent

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

	- AnyEvent::Strict would not properly ward against io watchers
          on files when the handle passed was a file descriptor.
        - document "internal" variables used by the dns en-/decoder to allow
          enterprising users to extend them in a semi-official way.

7.14 Sat Jun 24 01:44:19 CEST 2017
	- fix a crash bug in AnyEvent::Handle with openssl 1.1.0 (patched
	  by Paul Howarth and apparently tracked down by Mike McCauley).
	- AnyEvent::Handle->keepalive was documented (and defined) twice
          (found by Matt Merhar).
        - AnyEvent::Socket::tcp_bind/tcp_server would immediately unlink a unix
          listening socket unless a guard is used. Change this so that no
          cleanup will be performed unless a guard is used and document this more
          clearly.
        - make tcp_bind/tcp_server error messages more regular.
        - work around latest perl upstream breakage - this time, perl5porters were
          apparently bullied by a bogus CVE (CVE-2016-1238), and since distros
          stupidly apply anything that has "security fix" stamped on it, it's likely
          going to be a problem in practise (and working around it is trivial on
          windows and unix).
        - add TCP_FASTOPEN/MSG_FASTOPEN and MSG_NOSIGNAL/MSG_MORE/MSG_DONTWAIT
          to constants.
        - update warnings to common::sense 3.74 standards.

7.13 Sat Sep 17 04:31:49 CEST 2016

Changes  view on Meta::CPAN

	- use common name as hostname for tls connects, if Net::SSLeay
          supports SNI.
        - fix documentation of tls_autostart read type in AnyEvent::Handle,
          analyzed by Felix Ostmann.

7.11 Thu Jul 16 14:36:00 CEST 2015
	- AnyEvent::Socket::parse_ipv6 could accept malformed ipv6
          addresses (extra "::" at end and similar cases).
	- add a more explicit warning to AnyEvent::Handle that it doesn't
          work on files, people keep getting confused.
        - new function AnyEvent::Socket::tcp_bind.
        - new functions AnyEvent::fh_block and AnyEvent::fh_unblock.
	- aligned ipv6 address formatting with RFC 5952 (by not shortening
          a single :0: to ::).
        - added stability canary support.

7.09 Sat May  2 16:38:53 CEST 2015
	- AnyEvent::Debug called an internal function (AnyEvent::Log::ft)
          that was renamed to AnyEvent::Log:format_time. uinder its old name
          (analyzed by Michael Stovenour).
        - update AnyEvent::DNS fallback resolver addresses:

README  view on Meta::CPAN


           AnyEvent::Impl::Event     based on Event, very stable, few glitches.
           AnyEvent::Impl::Glib      based on Glib, slow but very stable.
           AnyEvent::Impl::Tk        based on Tk, very broken.
           AnyEvent::Impl::UV        based on UV, innovated square wheels.
           AnyEvent::Impl::EventLib  based on Event::Lib, leaks memory and worse.
           AnyEvent::Impl::POE       based on POE, very slow, some limitations.
           AnyEvent::Impl::Irssi     used when running within irssi.
           AnyEvent::Impl::IOAsync   based on IO::Async.
           AnyEvent::Impl::Cocoa     based on Cocoa::EventLoop.
           AnyEvent::Impl::FLTK      based on FLTK (fltk 2 binding).

    Backends with special needs.
        Qt requires the Qt::Application to be instantiated first, but will
        otherwise be picked up automatically. As long as the main program
        instantiates the application before any AnyEvent watchers are
        created, everything should just work.

           AnyEvent::Impl::Qt        based on Qt.

    Event loops that are indirectly supported via other backends.

README  view on Meta::CPAN


    "PERL_ANYEVENT_DEBUG_SHELL"
        If this env variable is nonempty, then its contents will be
        interpreted by "AnyEvent::Socket::parse_hostport" and
        "AnyEvent::Debug::shell" (after replacing every occurance of $$ by
        the process pid). The shell object is saved in
        $AnyEvent::Debug::SHELL.

        This happens when the first watcher is created.

        For example, to bind a debug shell on a unix domain socket in
        /tmp/debug<pid>.sock, you could use this:

           PERL_ANYEVENT_DEBUG_SHELL=/tmp/debug\$\$.sock perlprog
           # connect with e.g.: socat readline /tmp/debug123.sock

        Or to bind to tcp port 4545 on localhost:

           PERL_ANYEVENT_DEBUG_SHELL=127.0.0.1:4545 perlprog
           # connect with e.g.: telnet localhost 4545

        Note that creating sockets in /tmp or on localhost is very unsafe on
        multiuser systems.

    "PERL_ANYEVENT_DEBUG_WRAP"
        Can be set to 0, 1 or 2 and enables wrapping of all watchers for
        debugging purposes. See "AnyEvent::Debug::wrap" for details.

lib/AnyEvent.pm  view on Meta::CPAN


   AnyEvent::Impl::Event     based on Event, very stable, few glitches.
   AnyEvent::Impl::Glib      based on Glib, slow but very stable.
   AnyEvent::Impl::Tk        based on Tk, very broken.
   AnyEvent::Impl::UV        based on UV, innovated square wheels.
   AnyEvent::Impl::EventLib  based on Event::Lib, leaks memory and worse.
   AnyEvent::Impl::POE       based on POE, very slow, some limitations.
   AnyEvent::Impl::Irssi     used when running within irssi.
   AnyEvent::Impl::IOAsync   based on IO::Async.
   AnyEvent::Impl::Cocoa     based on Cocoa::EventLoop.
   AnyEvent::Impl::FLTK      based on FLTK (fltk 2 binding).

=item Backends with special needs.

Qt requires the Qt::Application to be instantiated first, but will
otherwise be picked up automatically. As long as the main program
instantiates the application before any AnyEvent watchers are created,
everything should just work.

   AnyEvent::Impl::Qt        based on Qt.

lib/AnyEvent.pm  view on Meta::CPAN

   *$name = sub {
      detect;
      # we use goto because
      # a) it makes the thunk more transparent
      # b) it allows us to delete the thunk later
      goto &{ UNIVERSAL::can AnyEvent => "SUPER::$name" }
   };
}

# utility function to dup a filehandle. this is used by many backends
# to support binding more than one watcher per filehandle (they usually
# allow only one watcher per fd, so we dup it to get a different one).
sub _dupfh($$;$$) {
   my ($poll, $fh, $r, $w) = @_;

   # cygwin requires the fh mode to be matching, unix doesn't
   my ($rw, $mode) = $poll eq "r" ? ($r, "<&") : ($w, ">&");

   open my $fh2, $mode, $fh
      or die "AnyEvent->io: cannot dup() filehandle in mode '$poll': $!,";

lib/AnyEvent.pm  view on Meta::CPAN


=item C<PERL_ANYEVENT_DEBUG_SHELL>

If this env variable is nonempty, then its contents will be interpreted by
C<AnyEvent::Socket::parse_hostport> and C<AnyEvent::Debug::shell> (after
replacing every occurance of C<$$> by the process pid). The shell object
is saved in C<$AnyEvent::Debug::SHELL>.

This happens when the first watcher is created.

For example, to bind a debug shell on a unix domain socket in
F<< /tmp/debug<pid>.sock >>, you could use this:

   PERL_ANYEVENT_DEBUG_SHELL=/tmp/debug\$\$.sock perlprog
   # connect with e.g.: socat readline /tmp/debug123.sock

Or to bind to tcp port 4545 on localhost:

   PERL_ANYEVENT_DEBUG_SHELL=127.0.0.1:4545 perlprog
   # connect with e.g.: telnet localhost 4545

Note that creating sockets in F</tmp> or on localhost is very unsafe on
multiuser systems.

=item C<PERL_ANYEVENT_DEBUG_WRAP>

Can be set to C<0>, C<1> or C<2> and enables wrapping of all watchers for

lib/AnyEvent/Debug.pm  view on Meta::CPAN


our $TRACE = 1; # trace status

our ($TRACE_LOGGER, $TRACE_ENABLED);

# cache often-used strings, purely to save memory, at the expense of speed
our %STRCACHE;

=item $shell = AnyEvent::Debug::shell $host, $service

This function binds on the given host and service port and returns a
shell object, which determines the lifetime of the shell. Any number
of connections are accepted on the port, and they will give you a very
primitive shell that simply executes every line you enter.

All commands will be executed "blockingly" with the socket C<select>ed for
output. For a less "blocking" interface see L<Coro::Debug>.

The commands will be executed in the C<AnyEvent::Debug::shell> package,
which currently has "help" and a few other commands, and can be freely
modified by all shells. Code is evaluated under C<use strict 'subs'>.

lib/AnyEvent/Log.pm  view on Meta::CPAN

   $debug_log->(sub { $obj->as_string });

The idea behind this function is to decide whether to log before actually
logging - when the C<logger> function is called once, but the returned
logger callback often, then this can be a tremendous speed win.

Despite this speed advantage, changes in logging configuration will
still be reflected by the logger callback, even if configuration changes
I<after> it was created.

To further speed up logging, you can bind a scalar variable to the logger,
which contains true if the logger should be called or not - if it is
false, calling the logger can be safely skipped. This variable will be
updated as long as C<$logger> is alive.

Full example:

   # near the init section
   use AnyEvent::Log;

   my $debug_log = AnyEvent:Log::logger debug => \my $debug;

lib/AnyEvent/Socket.pm  view on Meta::CPAN


=item $sa = AnyEvent::Socket::pack_sockaddr $service, $host

Pack the given port/host combination into a binary sockaddr
structure. Handles both IPv4 and IPv6 host addresses, as well as UNIX
domain sockets (C<$host> == C<unix/> and C<$service> == absolute
pathname).

Example:

   my $bind = AnyEvent::Socket::pack_sockaddr 43, v195.234.53.120;
   bind $socket, $bind
      or die "bind: $!";

=cut

sub pack_sockaddr($$) {
   my $af = address_family $_[1];

   if ($af == AF_INET) {
      Socket::pack_sockaddr_in $_[0], $_[1]
   } elsif ($af == AF_INET6) {
      pack "$pack_family nL a16 L",

lib/AnyEvent/Socket.pm  view on Meta::CPAN

         0      # scope id
   } elsif ($af == AF_UNIX) {
      Socket::pack_sockaddr_un $_[0]
   } else {
      Carp::croak "pack_sockaddr: invalid host";
   }
}

=item ($service, $host) = AnyEvent::Socket::unpack_sockaddr $sa

Unpack the given binary sockaddr structure (as used by bind, getpeername
etc.) into a C<$service, $host> combination.

For IPv4 and IPv6, C<$service> is the port number and C<$host> the host
address in network format (binary).

For UNIX domain sockets, C<$service> is the absolute pathname and C<$host>
is a special token that is understood by the other functions in this
module (C<format_address> converts it to C<unix/>).

=cut

lib/AnyEvent/Socket.pm  view on Meta::CPAN

C<$family> must be either C<0> (meaning any protocol is OK), C<4> (use
only IPv4) or C<6> (use only IPv6). The default is influenced by
C<$ENV{PERL_ANYEVENT_PROTOCOLS}>.

C<$type> must be C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_SEQPACKET> (or
C<undef> in which case it gets automatically chosen to be C<SOCK_STREAM>
unless C<$proto> is C<udp>).

The callback will receive zero or more array references that contain
C<$family, $type, $proto> for use in C<socket> and a binary
C<$sockaddr> for use in C<connect> (or C<bind>).

The application should try these in the order given.

Example:

   resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... };

=cut

our %HOSTS;          # $HOSTS{$nodename}[$ipv6] = [@aliases...]

lib/AnyEvent/Socket.pm  view on Meta::CPAN

The file handle is perfect for being plugged into L<AnyEvent::Handle>, but
can be used as a normal perl file handle as well.

Unless called in void context, C<tcp_connect> returns a guard object that
will automatically cancel the connection attempt when it gets destroyed
- in which case the callback will not be invoked. Destroying it does not
do anything to the socket after the connect was successful - you cannot
"uncall" a callback that has been invoked already.

Sometimes you need to "prepare" the socket before connecting, for example,
to C<bind> it to some port, or you want a specific connect timeout that
is lower than your kernel's default timeout. In this case you can specify
a second callback, C<$prepare_cb>. It will be called with the file handle
in not-yet-connected state as only argument and must return the connection
timeout value (or C<0>, C<undef> or the empty list to indicate the default
timeout is to be used).

Note to the poor Microsoft Windows users: Windows (of course) doesn't
correctly signal connection errors, so unless your event library works
around this, failed connections will simply hang. The only event libraries
that handle this condition correctly are L<EV> and L<Glib>. Additionally,

lib/AnyEvent/Socket.pm  view on Meta::CPAN

            print "HEADER\n$line\n\nBODY\n";

            $handle->on_read (sub {
               # print response body
               print $_[0]->rbuf;
               $_[0]->rbuf = "";
            });
         });
      }, sub {
         my ($fh) = @_;
         # could call $fh->bind etc. here

         15
      };

Example: connect to a UNIX domain socket.

   tcp_connect "unix/", "/tmp/.X11-unix/X0", sub {
      ...
   }

lib/AnyEvent/Socket.pm  view on Meta::CPAN


      $! = Errno::ENXIO;
      $state{next}();
   };

   defined wantarray && guard { %state = () }
}

=item $guard = tcp_server $host, $service, $accept_cb[, $prepare_cb]

Create and bind a stream socket to the given host address and port, set
the SO_REUSEADDR flag (if applicable) and call C<listen>. Unlike the name
implies, this function can also bind on UNIX domain sockets.

For internet sockets, C<$host> must be an IPv4 or IPv6 address (or
C<undef>, in which case it binds either to C<0> or to C<::>, depending
on whether IPv4 or IPv6 is the preferred protocol, and maybe to both in
future versions, as applicable).

To bind to the IPv4 wildcard address, use C<0>, to bind to the IPv6
wildcard address, use C<::>.

The port is specified by C<$service>, which must be either a service name
or a numeric port number (or C<0> or C<undef>, in which case an ephemeral
port will be used).

For UNIX domain sockets, C<$host> must be C<unix/> and C<$service> must be
the absolute pathname of the socket. This function will try to C<unlink>
the socket before it tries to bind to it, and will try to unlink it after
it stops using it. See SECURITY CONSIDERATIONS, below.

For each new connection that could be C<accept>ed, call the C<<
$accept_cb->($fh, $host, $port) >> with the file handle (in non-blocking
mode) as first, and the peer host and port as second and third arguments
(see C<tcp_connect> for details).

Croaks on any errors it can detect before the listen.

In non-void context, this function returns a guard object whose lifetime

lib/AnyEvent/Socket.pm  view on Meta::CPAN


If you need more control over the listening socket, you can provide a
C<< $prepare_cb->($fh, $host, $port) >>, which is called just before the
C<listen ()> call, with the listen file handle as first argument, and IP
address and port number of the local socket endpoint as second and third
arguments.

It should return the length of the listen queue (or C<0> for the default).

Note to IPv6 users: RFC-compliant behaviour for IPv6 sockets listening on
C<::> is to bind to both IPv6 and IPv4 addresses by default on dual-stack
hosts. Unfortunately, only GNU/Linux seems to implement this properly, so
if you want both IPv4 and IPv6 listening sockets you should create the
IPv6 socket first and then attempt to bind on the IPv4 socket, but ignore
any C<EADDRINUSE> errors.

Example: bind on some TCP port on the local machine and tell each client
to go away.

   tcp_server undef, undef, sub {
      my ($fh, $host, $port) = @_;

      syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
   }, sub {
      my ($fh, $thishost, $thisport) = @_;
      AE::log info => "Bound to $thishost, port $thisport.";
   };

Example: bind a server on a unix domain socket.

   tcp_server "unix/", "/tmp/mydir/mysocket", sub {
      my ($fh) = @_;
   };

=item $guard = AnyEvent::Socket::tcp_bind $host, $service, $done_cb[, $prepare_cb]

Same as C<tcp_server>, except it doesn't call C<accept> in a loop for you
but simply passes the listen socket to the C<$done_cb>. This is useful
when you want to have a convenient set up for your listen socket, but want
to do the C<accept>'ing yourself, for example, in another process.

In case of an error, C<tcp_bind> either croaks, or passes C<undef> to the
C<$done_cb>.

In non-void context, a guard will be returned. It will clean up/unlink the
listening socket when destroyed. In void context, no automatic clean up
might be performed.

=cut

sub _tcp_bind($$$;$) {
   my ($host, $service, $done, $prepare) = @_;

   $host = $AnyEvent::PROTOCOL{ipv4} < $AnyEvent::PROTOCOL{ipv6} && AF_INET6
           ? "::" : "0"
      unless defined $host;

   my $ipn = parse_address $host
      or Carp::croak "tcp_bind: cannot parse '$host' as host address";

   my $af = address_family $ipn;

   my %state;

   # win32 perl is too stupid to get this right :/
   Carp::croak "tcp_bind: AF_UNIX address family not supported on win32"
      if AnyEvent::WIN32 && $af == AF_UNIX;

   socket my $fh, $af, SOCK_STREAM, 0
      or Carp::croak "tcp_bind: $!";

   $state{fh} = $fh;

   if ($af == AF_INET || $af == AF_INET6) {
      setsockopt $fh, SOL_SOCKET, SO_REUSEADDR, 1
         or Carp::croak "tcp_bind: so_reuseaddr: $!"
            unless AnyEvent::WIN32; # work around windows bug

      unless ($service =~ /^\d*$/) {
         $service = (getservbyname $service, "tcp")[2]
                    or Carp::croak "tcp_bind: unknown service '$service'"
      }
   } elsif ($af == AF_UNIX) {
      unlink $service;
   }

   bind $fh, pack_sockaddr $service, $ipn
      or Carp::croak "tcp_bind: $!";

   if ($af == AF_UNIX and defined wantarray) {
      # this is racy, but is not designed to be foolproof, just best-effort
      my $ino = (lstat $service)[1];
      $state{unlink} = guard {
         unlink $service
            if (lstat $service)[1] == $ino;
      };
   }

lib/AnyEvent/Socket.pm  view on Meta::CPAN

   my $len;

   if ($prepare) {
      my ($service, $host) = unpack_sockaddr getsockname $fh;
      $len = $prepare && $prepare->($fh, format_address $host, $service);
   }
   
   $len ||= 128;

   listen $fh, $len
      or Carp::croak "tcp_bind: $!";

   $done->(\%state);

   defined wantarray
      ? guard { %state = () } # clear fh, unlink
      : ()
}

sub tcp_bind($$$;$) {
   my ($host, $service, $done, $prepare) = @_;

   _tcp_bind $host, $service, sub {
      $done->(delete shift->{fh});
   }, $prepare
}

sub tcp_server($$$;$) {
   my ($host, $service, $accept, $prepare) = @_;

   _tcp_bind $host, $service, sub {
      my $rstate = shift;

      $rstate->{aw} = AE::io $rstate->{fh}, 0, sub {
         # this closure keeps $state alive
         while ($rstate->{fh} && (my $peer = accept my $fh, $rstate->{fh})) {
            AnyEvent::fh_unblock $fh; # POSIX requires inheritance, the outside world does not

            my ($service, $host) = unpack_sockaddr $peer;
            $accept->($fh, format_address $host, $service);
         }

lib/AnyEvent/Socket.pm  view on Meta::CPAN

}

=back

=head1 SECURITY CONSIDERATIONS

This module is quite powerful, with with power comes the ability to abuse
as well: If you accept "hostnames" and ports from untrusted sources,
then note that this can be abused to delete files (host=C<unix/>). This
is not really a problem with this module, however, as blindly accepting
any address and protocol and trying to bind a server or connect to it is
harmful in general.

=head1 AUTHOR

 Marc Lehmann <schmorp@schmorp.de>
 http://anyevent.schmorp.de

=cut

1

lib/AnyEvent/Util.pm  view on Meta::CPAN

BEGIN {
   if (AnyEvent::WIN32) {
      *_win32_socketpair = sub () {
         # perl's socketpair emulation fails on many vista machines, because
         # vista returns fantasy port numbers.

         for (1..10) {
            socket my $l, Socket::AF_INET(), Socket::SOCK_STREAM(), 0
               or next;

            bind $l, Socket::pack_sockaddr_in 0, "\x7f\x00\x00\x01"
               or next;

            my $sa = getsockname $l
               or next;

            listen $l, 1
               or next;

            socket my $r, Socket::AF_INET(), Socket::SOCK_STREAM(), 0
               or next;

            bind $r, Socket::pack_sockaddr_in 0, "\x7f\x00\x00\x01"
               or next;

            connect $r, $sa
               or next;

            accept my $w, $l
               or next;

            # vista has completely broken peername/sockname that return
            # fantasy ports. this combo seems to work, though.



( run in 1.918 second using v1.01-cache-2.11-cpan-2398b32b56e )