AnyEvent

 view release on metacpan or  search on metacpan

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


=head1 METHODS

=over 4

=item $handle = B<new> AnyEvent::Handle fh => $filehandle, key => value...

The constructor supports these arguments (all as C<< key => value >> pairs).

=over 4

=item fh => $filehandle     [C<fh> or C<connect> MANDATORY]

The filehandle this L<AnyEvent::Handle> object will operate on.
NOTE: The filehandle will be set to non-blocking mode (using
C<AnyEvent::fh_unblock>) by the constructor and needs to stay in
that mode.

=item connect => [$host, $service]      [C<fh> or C<connect> MANDATORY]

Try to connect to the specified host and service (port), using
C<AnyEvent::Socket::tcp_connect>. The C<$host> additionally becomes the
default C<peername>.

You have to specify either this parameter, or C<fh>, above.

It is possible to push requests on the read and write queues, and modify
properties of the stream, even while AnyEvent::Handle is connecting.

When this parameter is specified, then the C<on_prepare>,
C<on_connect_error> and C<on_connect> callbacks will be called under the
appropriate circumstances:

=over 4

=item on_prepare => $cb->($handle)

This (rarely used) callback is called before a new connection is
attempted, but after the file handle has been created (you can access that
file handle via C<< $handle->{fh} >>). It could be used to prepare the
file handle with parameters required for the actual connect (as opposed to
settings that can be changed when the connection is already established).

The return value of this callback should be the connect timeout value in
seconds (or C<0>, or C<undef>, or the empty list, to indicate that the
default timeout is to be used).

=item on_connect => $cb->($handle, $host, $port, $retry->())

This callback is called when a connection has been successfully established.

The peer's numeric host and port (the socket peername) are passed as
parameters, together with a retry callback. At the time it is called the
read and write queues, EOF status, TLS status and similar properties of
the handle will have been reset.

If, for some reason, the handle is not acceptable, calling C<$retry> will
continue with the next connection target (in case of multi-homed hosts or
SRV records there can be multiple connection endpoints). The C<$retry>
callback can be invoked after the connect callback returns, i.e. one can
start a handshake and then decide to retry with the next host if the
handshake fails.

In most cases, you should ignore the C<$retry> parameter.

=item on_connect_error => $cb->($handle, $message)

This callback is called when the connection could not be
established. C<$!> will contain the relevant error code, and C<$message> a
message describing it (usually the same as C<"$!">).

If this callback isn't specified, then C<on_error> will be called with a
fatal error instead.

=back

=item on_error => $cb->($handle, $fatal, $message)

This is the error callback, which is called when, well, some error
occured, such as not being able to resolve the hostname, failure to
connect, or a read error.

Some errors are fatal (which is indicated by C<$fatal> being true). On
fatal errors the handle object will be destroyed (by a call to C<< ->
destroy >>) after invoking the error callback (which means you are free to
examine the handle object). Examples of fatal errors are an EOF condition
with active (but unsatisfiable) read watchers (C<EPIPE>) or I/O errors. In
cases where the other side can close the connection at will, it is
often easiest to not report C<EPIPE> errors in this callback.

AnyEvent::Handle tries to find an appropriate error code for you to check
against, but in some cases (TLS errors), this does not work well.

If you report the error to the user, it is recommended to always output
the C<$message> argument in human-readable error messages (you don't need
to report C<"$!"> if you report C<$message>).

If you want to react programmatically to the error, then looking at C<$!>
and comparing it against some of the documented C<Errno> values is usually
better than looking at the C<$message>.

Non-fatal errors can be retried by returning, but it is recommended
to simply ignore this parameter and instead abondon the handle object
when this callback is invoked. Examples of non-fatal errors are timeouts
C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>).

On entry to the callback, the value of C<$!> contains the operating
system error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or
C<EPROTO>).

While not mandatory, it is I<highly> recommended to set this callback, as
you will not be notified of errors otherwise. The default just calls
C<croak>.

=item on_read => $cb->($handle)

This sets the default read callback, which is called when data arrives
and no read request is in the queue (unlike read queue callbacks, this
callback will only be called when at least one octet of data is in the
read buffer).

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

};

=item storable => $cb->($handle, $ref)

Deserialises a L<Storable> frozen representation as written by the
C<storable> write type (BER-encoded length prefix followed by nfreeze'd
data).

Raises C<EBADMSG> error if the data could not be decoded.

=cut

register_read_type storable => sub {
   my ($self, $cb) = @_;

   require Storable unless $Storable::VERSION;

   sub {
      # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method
      defined (my $len = eval { unpack "w", $_[0]{rbuf} })
         or return;

      my $format = length pack "w", $len;

      # bypass unshift if we already have the remaining chunk
      if ($format + $len <= length $_[0]{rbuf}) {
         my $data = substr $_[0]{rbuf}, $format, $len;
         substr $_[0]{rbuf}, 0, $format + $len, "";

         eval { $cb->($_[0], Storable::thaw ($data)); 1 }
            or return $_[0]->_error (Errno::EBADMSG);
      } else {
         # remove prefix
         substr $_[0]{rbuf}, 0, $format, "";

         # read remaining chunk
         $_[0]->unshift_read (chunk => $len, sub {
            eval { $cb->($_[0], Storable::thaw ($_[1])); 1 }
               or $_[0]->_error (Errno::EBADMSG);
         });
      }

      1
   }
};

=item tls_detect => $cb->($handle, $detect, $major, $minor)

Checks the input stream for a valid SSL or TLS handshake TLSPaintext
record without consuming anything. Only SSL version 3 or higher
is handled, up to the fictituous protocol 4.x (but both SSL3+ and
SSL2-compatible framing is supported).

If it detects that the input data is likely TLS, it calls the callback
with a true value for C<$detect> and the (on-wire) TLS version as second
and third argument (C<$major> is C<3>, and C<$minor> is 0..4 for SSL
3.0, TLS 1.0, 1.1, 1.2 and 1.3, respectively).  If it detects the input
to be definitely not TLS, it calls the callback with a false value for
C<$detect>.

The callback could use this information to decide whether or not to start
TLS negotiation.

In all cases the data read so far is passed to the following read
handlers.

Usually you want to use the C<tls_autostart> read type instead.

If you want to design a protocol that works in the presence of TLS
dtection, make sure that any non-TLS data doesn't start with the octet 22
(ASCII SYN, 16 hex) or 128-255 (i.e. highest bit set). The checks this
read type does are a bit more strict, but might losen in the future to
accomodate protocol changes.

This read type does not rely on L<AnyEvent::TLS> (and thus, not on
L<Net::SSLeay>).

=item tls_autostart => [$tls_ctx, ]$tls

Tries to detect a valid SSL or TLS handshake. If one is detected, it tries
to start tls by calling C<starttls> with the given arguments.

In practise, C<$tls> must be C<accept>, or a Net::SSLeay context that has
been configured to accept, as servers do not normally send a handshake on
their own and ths cannot be detected in this way.

See C<tls_detect> above for more details.

Example: give the client a chance to start TLS before accepting a text
line.

   $hdl->push_read (tls_autostart => "accept");
   $hdl->push_read (line => sub {
      print "received ", ($_[0]{tls} ? "encrypted" : "cleartext"), " <$_[1]>\n";
   });

=cut

register_read_type tls_detect => sub {
   my ($self, $cb) = @_;

   sub {
      # this regex matches a full or partial tls record
      if (
         # ssl3+: type(22=handshake) major(=3) minor(any) length_hi
         $self->{rbuf} =~ /^(?:\z| \x16 (\z| [\x03\x04] (?:\z| . (?:\z| [\x00-\x40] ))))/xs
         # ssl2 comapatible: len_hi len_lo type(1) major minor dummy(forlength)
         or $self->{rbuf} =~ /^(?:\z| [\x80-\xff] (?:\z| . (?:\z| \x01 (\z| [\x03\x04] (?:\z| . (?:\z| . ))))))/xs
      ) {
         return if 3 != length $1; # partial match, can't decide yet

         # full match, valid TLS record
         my ($major, $minor) = unpack "CC", $1;
         $cb->($self, "accept", $major, $minor);
      } else {
         # mismatch == guaranteed not TLS
         $cb->($self, undef);
      }

      1
   }
};

register_read_type tls_autostart => sub {
   my ($self, @tls) = @_;

   $RH{tls_detect}($self, sub {
      return unless $_[1];
      $_[0]->starttls (@tls);
   })
};

=back

=item custom read types - Package::anyevent_read_type $handle, $cb, @args

Instead of one of the predefined types, you can also specify the name
of a package. AnyEvent will try to load the package and then expects to
find a function named C<anyevent_read_type> inside. If it isn't found, it
progressively tries to load the parent package until it either finds the
function (good) or runs out of packages (bad).

Whenever this type is used, C<push_read> will invoke the function with the
handle object, the original callback and the remaining arguments.

The function is supposed to return a callback (usually a closure) that
works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
mentally treat the function as a "configurable read type to read callback"
converter.

It should invoke the original callback when it is done reading (remember
to pass C<$handle> as first argument as all other callbacks do that,
although there is no strict requirement on this).

For examples, see the source of this module (F<perldoc -m
AnyEvent::Handle>, search for C<register_read_type>)).

=item $handle->stop_read

=item $handle->start_read

In rare cases you actually do not want to read anything from the
socket. In this case you can call C<stop_read>. Neither C<on_read> nor
any queued callbacks will be executed then. To start reading again, call
C<start_read>.

Note that AnyEvent::Handle will automatically C<start_read> for you when
you change the C<on_read> callback or push/unshift a read callback, and it
will automatically C<stop_read> for you when neither C<on_read> is set nor
there are any read requests in the queue.

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


      my @linger;

      push @linger, AE::io $fh, 1, sub {
         my $len = syswrite $fh, $wbuf, length $wbuf;

         if ($len > 0) {
            substr $wbuf, 0, $len, "";
         } elsif (defined $len || ($! != EAGAIN && $! != EINTR && $! != EWOULDBLOCK && $! != WSAEWOULDBLOCK)) {
            @linger = (); # end
         }
      };
      push @linger, AE::timer $linger, 0, sub {
         @linger = ();
      };
   }
}

=item $handle->destroy

Shuts down the handle object as much as possible - this call ensures that
no further callbacks will be invoked and as many resources as possible
will be freed. Any method you will call on the handle object after
destroying it in this way will be silently ignored (and it will return the
empty list).

Normally, you can just "forget" any references to an AnyEvent::Handle
object and it will simply shut down. This works in fatal error and EOF
callbacks, as well as code outside. It does I<NOT> work in a read or write
callback, so when you want to destroy the AnyEvent::Handle object from
within such an callback. You I<MUST> call C<< ->destroy >> explicitly in
that case.

Destroying the handle object in this way has the advantage that callbacks
will be removed as well, so if those are the only reference holders (as
is common), then one doesn't need to do anything special to break any
reference cycles.

The handle might still linger in the background and write out remaining
data, as specified by the C<linger> option, however.

=cut

sub destroy {
   my ($self) = @_;

   $self->DESTROY;
   %$self = ();
   bless $self, "AnyEvent::Handle::destroyed";
}

sub AnyEvent::Handle::destroyed::AUTOLOAD {
   #nop
}

=item $handle->destroyed

Returns false as long as the handle hasn't been destroyed by a call to C<<
->destroy >>, true otherwise.

Can be useful to decide whether the handle is still valid after some
callback possibly destroyed the handle. For example, C<< ->push_write >>,
C<< ->starttls >> and other methods can call user callbacks, which in turn
can destroy the handle, so work can be avoided by checking sometimes:

   $hdl->starttls ("accept");
   return if $hdl->destroyed;
   $hdl->push_write (...

Note that the call to C<push_write> will silently be ignored if the handle
has been destroyed, so often you can just ignore the possibility of the
handle being destroyed.

=cut

sub destroyed { 0 }
sub AnyEvent::Handle::destroyed::destroyed { 1 }

=item AnyEvent::Handle::TLS_CTX

This function creates and returns the AnyEvent::TLS object used by default
for TLS mode.

The context is created by calling L<AnyEvent::TLS> without any arguments.

=cut

our $TLS_CTX;

sub TLS_CTX() {
   $TLS_CTX ||= do {
      require AnyEvent::TLS;

      new AnyEvent::TLS
   }
}

=back


=head1 NONFREQUENTLY ASKED QUESTIONS

=over 4

=item I C<undef> the AnyEvent::Handle reference inside my callback and
still get further invocations!

That's because AnyEvent::Handle keeps a reference to itself when handling
read or write callbacks.

It is only safe to "forget" the reference inside EOF or error callbacks,
from within all other callbacks, you need to explicitly call the C<<
->destroy >> method.

=item Why is my C<on_eof> callback never called?

Probably because your C<on_error> callback is being called instead: When
you have outstanding requests in your read queue, then an EOF is
considered an error as you clearly expected some data.

To avoid this, make sure you have an empty read queue whenever your handle



( run in 0.752 second using v1.01-cache-2.11-cpan-39bf76dae61 )