ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Handle.pm
(Generate patch)

Comparing AnyEvent/lib/AnyEvent/Handle.pm (file contents):
Revision 1.182 by root, Thu Sep 3 12:35:01 2009 UTC vs.
Revision 1.192 by root, Fri Mar 12 23:22:14 2010 UTC

14 on_error => sub { 14 on_error => sub {
15 my ($hdl, $fatal, $msg) = @_; 15 my ($hdl, $fatal, $msg) = @_;
16 warn "got error $msg\n"; 16 warn "got error $msg\n";
17 $hdl->destroy; 17 $hdl->destroy;
18 $cv->send; 18 $cv->send;
19 ); 19 };
20 20
21 # send some request line 21 # send some request line
22 $hdl->push_write ("getinfo\015\012"); 22 $hdl->push_write ("getinfo\015\012");
23 23
24 # read the response line 24 # read the response line
60use AnyEvent (); BEGIN { AnyEvent::common_sense } 60use AnyEvent (); BEGIN { AnyEvent::common_sense }
61use AnyEvent::Util qw(WSAEWOULDBLOCK); 61use AnyEvent::Util qw(WSAEWOULDBLOCK);
62 62
63our $VERSION = $AnyEvent::VERSION; 63our $VERSION = $AnyEvent::VERSION;
64 64
65sub _load_func($) {
66 my $func = $_[0];
67
68 unless (defined &$func) {
69 my $pkg = $func;
70 do {
71 $pkg =~ s/::[^:]+$//
72 or return;
73 eval "require $pkg";
74 } until defined &$func;
75 }
76
77 \&$func
78}
79
65=head1 METHODS 80=head1 METHODS
66 81
67=over 4 82=over 4
68 83
69=item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value... 84=item $handle = B<new> AnyEvent::Handle fh => $filehandle, key => value...
70 85
71The constructor supports these arguments (all as C<< key => value >> pairs). 86The constructor supports these arguments (all as C<< key => value >> pairs).
72 87
73=over 4 88=over 4
74 89
114 129
115The actual numeric host and port (the socket peername) are passed as 130The actual numeric host and port (the socket peername) are passed as
116parameters, together with a retry callback. 131parameters, together with a retry callback.
117 132
118When, for some reason, the handle is not acceptable, then calling 133When, for some reason, the handle is not acceptable, then calling
119C<$retry> will continue with the next conenction target (in case of 134C<$retry> will continue with the next connection target (in case of
120multi-homed hosts or SRV records there can be multiple connection 135multi-homed hosts or SRV records there can be multiple connection
121endpoints). When it is called then the read and write queues, eof status, 136endpoints). At the time it is called the read and write queues, eof
122tls status and similar properties of the handle are being reset. 137status, tls status and similar properties of the handle will have been
138reset.
123 139
124In most cases, ignoring the C<$retry> parameter is the way to go. 140In most cases, ignoring the C<$retry> parameter is the way to go.
125 141
126=item on_connect_error => $cb->($handle, $message) 142=item on_connect_error => $cb->($handle, $message)
127 143
128This callback is called when the conenction could not be 144This callback is called when the connection could not be
129established. C<$!> will contain the relevant error code, and C<$message> a 145established. C<$!> will contain the relevant error code, and C<$message> a
130message describing it (usually the same as C<"$!">). 146message describing it (usually the same as C<"$!">).
131 147
132If this callback isn't specified, then C<on_error> will be called with a 148If this callback isn't specified, then C<on_error> will be called with a
133fatal error instead. 149fatal error instead.
289 305
290=item keepalive => <boolean> 306=item keepalive => <boolean>
291 307
292Enables (default disable) the SO_KEEPALIVE option on the stream socket: 308Enables (default disable) the SO_KEEPALIVE option on the stream socket:
293normally, TCP connections have no time-out once established, so TCP 309normally, TCP connections have no time-out once established, so TCP
294conenctions, once established, can stay alive forever even when the other 310connections, once established, can stay alive forever even when the other
295side has long gone. TCP keepalives are a cheap way to take down long-lived 311side has long gone. TCP keepalives are a cheap way to take down long-lived
296TCP connections whent he other side becomes unreachable. While the default 312TCP connections whent he other side becomes unreachable. While the default
297is OS-dependent, TCP keepalives usually kick in after around two hours, 313is OS-dependent, TCP keepalives usually kick in after around two hours,
298and, if the other side doesn't reply, take down the TCP connection some 10 314and, if the other side doesn't reply, take down the TCP connection some 10
299to 15 minutes later. 315to 15 minutes later.
306 322
307BSD majorly fucked up the implementation of TCP urgent data. The result 323BSD majorly fucked up the implementation of TCP urgent data. The result
308is that almost no OS implements TCP according to the specs, and every OS 324is that almost no OS implements TCP according to the specs, and every OS
309implements it slightly differently. 325implements it slightly differently.
310 326
311If you want to handle TCP urgent data, then setting this flag gives you 327If you want to handle TCP urgent data, then setting this flag (the default
312the most portable way of getting urgent data, by putting it into the 328is enabled) gives you the most portable way of getting urgent data, by
313stream. 329putting it into the stream.
330
331Since BSD emulation of OOB data on top of TCP's urgent data can have
332security implications, AnyEvent::Handle sets this flag automatically
333unless explicitly specified. Note that setting this flag after
334establishing a connection I<may> be a bit too late (data loss could
335already have occured on BSD systems), but at least it will protect you
336from most attacks.
314 337
315=item read_size => <bytes> 338=item read_size => <bytes>
316 339
317The default read block size (the amount of bytes this module will 340The default read block size (the amount of bytes this module will
318try to read during each loop iteration, which affects memory 341try to read during each loop iteration, which affects memory
352C<undef>. 375C<undef>.
353 376
354=item tls => "accept" | "connect" | Net::SSLeay::SSL object 377=item tls => "accept" | "connect" | Net::SSLeay::SSL object
355 378
356When this parameter is given, it enables TLS (SSL) mode, that means 379When this parameter is given, it enables TLS (SSL) mode, that means
357AnyEvent will start a TLS handshake as soon as the conenction has been 380AnyEvent will start a TLS handshake as soon as the connection has been
358established and will transparently encrypt/decrypt data afterwards. 381established and will transparently encrypt/decrypt data afterwards.
359 382
360All TLS protocol errors will be signalled as C<EPROTO>, with an 383All TLS protocol errors will be signalled as C<EPROTO>, with an
361appropriate error message. 384appropriate error message.
362 385
519 542
520 $self->timeout (delete $self->{timeout} ) if $self->{timeout}; 543 $self->timeout (delete $self->{timeout} ) if $self->{timeout};
521 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout}; 544 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout};
522 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout}; 545 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout};
523 546
524 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay}; 547 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay} && $self->{no_delay};
525 $self->keepalive (delete $self->{keepalive}) if exists $self->{keepalive}; 548 $self->keepalive (delete $self->{keepalive}) if exists $self->{keepalive} && $self->{keepalive};
549
526 $self->oobinline (delete $self->{oobinline}) if exists $self->{oobinline}; 550 $self->oobinline (exists $self->{oobinline} ? delete $self->{oobinline} : 1);
527 551
528 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 552 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
529 if $self->{tls}; 553 if $self->{tls};
530 554
531 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 555 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
543 $message ||= "$!"; 567 $message ||= "$!";
544 568
545 if ($self->{on_error}) { 569 if ($self->{on_error}) {
546 $self->{on_error}($self, $fatal, $message); 570 $self->{on_error}($self, $fatal, $message);
547 $self->destroy if $fatal; 571 $self->destroy if $fatal;
548 } elsif ($self->{fh}) { 572 } elsif ($self->{fh} || $self->{connect}) {
549 $self->destroy; 573 $self->destroy;
550 Carp::croak "AnyEvent::Handle uncaught error: $message"; 574 Carp::croak "AnyEvent::Handle uncaught error: $message";
551 } 575 }
552} 576}
553 577
686 710
687Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument). 711Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument).
688 712
689=cut 713=cut
690 714
691sub on_starttls { 715sub on_stoptls {
692 $_[0]{on_stoptls} = $_[1]; 716 $_[0]{on_stoptls} = $_[1];
693} 717}
694 718
695=item $handle->rbuf_max ($max_octets) 719=item $handle->rbuf_max ($max_octets)
696 720
863 }; 887 };
864} 888}
865 889
866our %WH; 890our %WH;
867 891
892# deprecated
868sub register_write_type($$) { 893sub register_write_type($$) {
869 $WH{$_[0]} = $_[1]; 894 $WH{$_[0]} = $_[1];
870} 895}
871 896
872sub push_write { 897sub push_write {
873 my $self = shift; 898 my $self = shift;
874 899
875 if (@_ > 1) { 900 if (@_ > 1) {
876 my $type = shift; 901 my $type = shift;
877 902
903 @_ = ($WH{$type} ||= _load_func "$type\::anyevent_write_type"
878 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write") 904 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_write")
879 ->($self, @_); 905 ->($self, @_);
880 } 906 }
881 907
908 # we downgrade here to avoid hard-to-track-down bugs,
909 # and diagnose the problem earlier and better.
910
882 if ($self->{tls}) { 911 if ($self->{tls}) {
883 $self->{_tls_wbuf} .= $_[0]; 912 utf8::downgrade $self->{_tls_wbuf} .= $_[0];
884 &_dotls ($self) if $self->{fh}; 913 &_dotls ($self) if $self->{fh};
885 } else { 914 } else {
886 $self->{wbuf} .= $_[0]; 915 utf8::downgrade $self->{wbuf} .= $_[0];
887 $self->_drain_wbuf if $self->{fh}; 916 $self->_drain_wbuf if $self->{fh};
888 } 917 }
889} 918}
890 919
891=item $handle->push_write (type => @args) 920=item $handle->push_write (type => @args)
892 921
893Instead of formatting your data yourself, you can also let this module do 922Instead of formatting your data yourself, you can also let this module
894the job by specifying a type and type-specific arguments. 923do the job by specifying a type and type-specific arguments. You
924can also specify the (fully qualified) name of a package, in which
925case AnyEvent tries to load the package and then expects to find the
926C<anyevent_read_type> function inside (see "custom write types", below).
895 927
896Predefined types are (if you have ideas for additional types, feel free to 928Predefined types are (if you have ideas for additional types, feel free to
897drop by and tell us): 929drop by and tell us):
898 930
899=over 4 931=over 4
1011 1043
1012 delete $self->{low_water_mark}; 1044 delete $self->{low_water_mark};
1013 $self->on_drain (sub { shutdown $_[0]{fh}, 1 }); 1045 $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
1014} 1046}
1015 1047
1016=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 1048=item custom write types - Package::anyevent_write_type $handle, @args
1017 1049
1018This function (not method) lets you add your own types to C<push_write>. 1050Instead of one of the predefined types, you can also specify the name of
1051a package. AnyEvent will try to load the package and then expects to find
1052a function named C<anyevent_write_type> inside. If it isn't found, it
1053progressively tries to load the parent package until it either finds the
1054function (good) or runs out of packages (bad).
1055
1019Whenever the given C<type> is used, C<push_write> will invoke the code 1056Whenever the given C<type> is used, C<push_write> will the function with
1020reference with the handle object and the remaining arguments. 1057the handle object and the remaining arguments.
1021 1058
1022The code reference is supposed to return a single octet string that will 1059The function is supposed to return a single octet string that will be
1023be appended to the write buffer. 1060appended to the write buffer, so you cna mentally treat this function as a
1061"arguments to on-the-wire-format" converter.
1024 1062
1025Note that this is a function, and all types registered this way will be 1063Example: implement a custom write type C<join> that joins the remaining
1026global, so try to use unique names. 1064arguments using the first one.
1065
1066 $handle->push_write (My::Type => " ", 1,2,3);
1067
1068 # uses the following package, which can be defined in the "My::Type" or in
1069 # the "My" modules to be auto-loaded, or just about anywhere when the
1070 # My::Type::anyevent_write_type is defined before invoking it.
1071
1072 package My::Type;
1073
1074 sub anyevent_write_type {
1075 my ($handle, $delim, @args) = @_;
1076
1077 join $delim, @args
1078 }
1027 1079
1028=cut 1080=cut
1029 1081
1030############################################################################# 1082#############################################################################
1031 1083
1250 my $cb = pop; 1302 my $cb = pop;
1251 1303
1252 if (@_) { 1304 if (@_) {
1253 my $type = shift; 1305 my $type = shift;
1254 1306
1307 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1255 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 1308 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_read")
1256 ->($self, $cb, @_); 1309 ->($self, $cb, @_);
1257 } 1310 }
1258 1311
1259 push @{ $self->{_queue} }, $cb; 1312 push @{ $self->{_queue} }, $cb;
1260 $self->_drain_rbuf; 1313 $self->_drain_rbuf;
1279 1332
1280=item $handle->unshift_read (type => @args, $cb) 1333=item $handle->unshift_read (type => @args, $cb)
1281 1334
1282Instead of providing a callback that parses the data itself you can chose 1335Instead of providing a callback that parses the data itself you can chose
1283between a number of predefined parsing formats, for chunks of data, lines 1336between a number of predefined parsing formats, for chunks of data, lines
1284etc. 1337etc. You can also specify the (fully qualified) name of a package, in
1338which case AnyEvent tries to load the package and then expects to find the
1339C<anyevent_read_type> function inside (see "custom read types", below).
1285 1340
1286Predefined types are (if you have ideas for additional types, feel free to 1341Predefined types are (if you have ideas for additional types, feel free to
1287drop by and tell us): 1342drop by and tell us):
1288 1343
1289=over 4 1344=over 4
1608 } 1663 }
1609}; 1664};
1610 1665
1611=back 1666=back
1612 1667
1613=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1668=item custom read types - Package::anyevent_read_type $handle, $cb, @args
1614 1669
1615This function (not method) lets you add your own types to C<push_read>. 1670Instead of one of the predefined types, you can also specify the name
1671of a package. AnyEvent will try to load the package and then expects to
1672find a function named C<anyevent_read_type> inside. If it isn't found, it
1673progressively tries to load the parent package until it either finds the
1674function (good) or runs out of packages (bad).
1616 1675
1617Whenever the given C<type> is used, C<push_read> will invoke the code 1676Whenever this type is used, C<push_read> will invoke the function with the
1618reference with the handle object, the callback and the remaining 1677handle object, the original callback and the remaining arguments.
1619arguments.
1620 1678
1621The code reference is supposed to return a callback (usually a closure) 1679The function is supposed to return a callback (usually a closure) that
1622that works as a plain read callback (see C<< ->push_read ($cb) >>). 1680works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
1681mentally treat the function as a "configurable read type to read callback"
1682converter.
1623 1683
1624It should invoke the passed callback when it is done reading (remember to 1684It should invoke the original callback when it is done reading (remember
1625pass C<$handle> as first argument as all other callbacks do that). 1685to pass C<$handle> as first argument as all other callbacks do that,
1686although there is no strict requirement on this).
1626 1687
1627Note that this is a function, and all types registered this way will be
1628global, so try to use unique names.
1629
1630For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, 1688For examples, see the source of this module (F<perldoc -m
1631search for C<register_read_type>)). 1689AnyEvent::Handle>, search for C<register_read_type>)).
1632 1690
1633=item $handle->stop_read 1691=item $handle->stop_read
1634 1692
1635=item $handle->start_read 1693=item $handle->start_read
1636 1694
1656} 1714}
1657 1715
1658sub start_read { 1716sub start_read {
1659 my ($self) = @_; 1717 my ($self) = @_;
1660 1718
1661 unless ($self->{_rw} || $self->{_eof}) { 1719 unless ($self->{_rw} || $self->{_eof} || !$self->{fh}) {
1662 Scalar::Util::weaken $self; 1720 Scalar::Util::weaken $self;
1663 1721
1664 $self->{_rw} = AE::io $self->{fh}, 0, sub { 1722 $self->{_rw} = AE::io $self->{fh}, 0, sub {
1665 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf}); 1723 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1666 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1724 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
1759 && ($tmp != $ERROR_SYSCALL || $!); 1817 && ($tmp != $ERROR_SYSCALL || $!);
1760 1818
1761 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) { 1819 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1762 $self->{wbuf} .= $tmp; 1820 $self->{wbuf} .= $tmp;
1763 $self->_drain_wbuf; 1821 $self->_drain_wbuf;
1822 $self->{tls} or return; # tls session might have gone away in callback
1764 } 1823 }
1765 1824
1766 $self->{_on_starttls} 1825 $self->{_on_starttls}
1767 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK () 1826 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
1768 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established"); 1827 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
1867 1926
1868=item $handle->stoptls 1927=item $handle->stoptls
1869 1928
1870Shuts down the SSL connection - this makes a proper EOF handshake by 1929Shuts down the SSL connection - this makes a proper EOF handshake by
1871sending a close notify to the other side, but since OpenSSL doesn't 1930sending a close notify to the other side, but since OpenSSL doesn't
1872support non-blocking shut downs, it is not guarenteed that you can re-use 1931support non-blocking shut downs, it is not guaranteed that you can re-use
1873the stream afterwards. 1932the stream afterwards.
1874 1933
1875=cut 1934=cut
1876 1935
1877sub stoptls { 1936sub stoptls {
1878 my ($self) = @_; 1937 my ($self) = @_;
1879 1938
1880 if ($self->{tls}) { 1939 if ($self->{tls} && $self->{fh}) {
1881 Net::SSLeay::shutdown ($self->{tls}); 1940 Net::SSLeay::shutdown ($self->{tls});
1882 1941
1883 &_dotls; 1942 &_dotls;
1884 1943
1885# # we don't give a shit. no, we do, but we can't. no...#d# 1944# # we don't give a shit. no, we do, but we can't. no...#d#
1962 2021
1963sub AnyEvent::Handle::destroyed::AUTOLOAD { 2022sub AnyEvent::Handle::destroyed::AUTOLOAD {
1964 #nop 2023 #nop
1965} 2024}
1966 2025
2026=item $handle->destroyed
2027
2028Returns false as long as the handle hasn't been destroyed by a call to C<<
2029->destroy >>, true otherwise.
2030
2031Can be useful to decide whether the handle is still valid after some
2032callback possibly destroyed the handle. For example, C<< ->push_write >>,
2033C<< ->starttls >> and other methods can call user callbacks, which in turn
2034can destroy the handle, so work can be avoided by checking sometimes:
2035
2036 $hdl->starttls ("accept");
2037 return if $hdl->destroyed;
2038 $hdl->push_write (...
2039
2040Note that the call to C<push_write> will silently be ignored if the handle
2041has been destroyed, so often you can just ignore the possibility of the
2042handle being destroyed.
2043
2044=cut
2045
2046sub destroyed { 0 }
2047sub AnyEvent::Handle::destroyed::destroyed { 1 }
2048
1967=item AnyEvent::Handle::TLS_CTX 2049=item AnyEvent::Handle::TLS_CTX
1968 2050
1969This function creates and returns the AnyEvent::TLS object used by default 2051This function creates and returns the AnyEvent::TLS object used by default
1970for TLS mode. 2052for TLS mode.
1971 2053

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines