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.184 by root, Thu Sep 3 13:14:38 2009 UTC vs.
Revision 1.193 by root, Mon Mar 15 18:51:30 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.
359C<undef>. 375C<undef>.
360 376
361=item tls => "accept" | "connect" | Net::SSLeay::SSL object 377=item tls => "accept" | "connect" | Net::SSLeay::SSL object
362 378
363When this parameter is given, it enables TLS (SSL) mode, that means 379When this parameter is given, it enables TLS (SSL) mode, that means
364AnyEvent 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
365established and will transparently encrypt/decrypt data afterwards. 381established and will transparently encrypt/decrypt data afterwards.
366 382
367All TLS protocol errors will be signalled as C<EPROTO>, with an 383All TLS protocol errors will be signalled as C<EPROTO>, with an
368appropriate error message. 384appropriate error message.
369 385
551 $message ||= "$!"; 567 $message ||= "$!";
552 568
553 if ($self->{on_error}) { 569 if ($self->{on_error}) {
554 $self->{on_error}($self, $fatal, $message); 570 $self->{on_error}($self, $fatal, $message);
555 $self->destroy if $fatal; 571 $self->destroy if $fatal;
556 } elsif ($self->{fh}) { 572 } elsif ($self->{fh} || $self->{connect}) {
557 $self->destroy; 573 $self->destroy;
558 Carp::croak "AnyEvent::Handle uncaught error: $message"; 574 Carp::croak "AnyEvent::Handle uncaught error: $message";
559 } 575 }
560} 576}
561 577
694 710
695Replace 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).
696 712
697=cut 713=cut
698 714
699sub on_starttls { 715sub on_stoptls {
700 $_[0]{on_stoptls} = $_[1]; 716 $_[0]{on_stoptls} = $_[1];
701} 717}
702 718
703=item $handle->rbuf_max ($max_octets) 719=item $handle->rbuf_max ($max_octets)
704 720
816=item $handle->on_drain ($cb) 832=item $handle->on_drain ($cb)
817 833
818Sets the C<on_drain> callback or clears it (see the description of 834Sets the C<on_drain> callback or clears it (see the description of
819C<on_drain> in the constructor). 835C<on_drain> in the constructor).
820 836
837This method may invoke callbacks (and therefore the handle might be
838destroyed after it returns).
839
821=cut 840=cut
822 841
823sub on_drain { 842sub on_drain {
824 my ($self, $cb) = @_; 843 my ($self, $cb) = @_;
825 844
832=item $handle->push_write ($data) 851=item $handle->push_write ($data)
833 852
834Queues the given scalar to be written. You can push as much data as you 853Queues the given scalar to be written. You can push as much data as you
835want (only limited by the available memory), as C<AnyEvent::Handle> 854want (only limited by the available memory), as C<AnyEvent::Handle>
836buffers it independently of the kernel. 855buffers it independently of the kernel.
856
857This method may invoke callbacks (and therefore the handle might be
858destroyed after it returns).
837 859
838=cut 860=cut
839 861
840sub _drain_wbuf { 862sub _drain_wbuf {
841 my ($self) = @_; 863 my ($self) = @_;
871 }; 893 };
872} 894}
873 895
874our %WH; 896our %WH;
875 897
898# deprecated
876sub register_write_type($$) { 899sub register_write_type($$) {
877 $WH{$_[0]} = $_[1]; 900 $WH{$_[0]} = $_[1];
878} 901}
879 902
880sub push_write { 903sub push_write {
881 my $self = shift; 904 my $self = shift;
882 905
883 if (@_ > 1) { 906 if (@_ > 1) {
884 my $type = shift; 907 my $type = shift;
885 908
909 @_ = ($WH{$type} ||= _load_func "$type\::anyevent_write_type"
886 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write") 910 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_write")
887 ->($self, @_); 911 ->($self, @_);
888 } 912 }
889 913
914 # we downgrade here to avoid hard-to-track-down bugs,
915 # and diagnose the problem earlier and better.
916
890 if ($self->{tls}) { 917 if ($self->{tls}) {
891 $self->{_tls_wbuf} .= $_[0]; 918 utf8::downgrade $self->{_tls_wbuf} .= $_[0];
892 &_dotls ($self) if $self->{fh}; 919 &_dotls ($self) if $self->{fh};
893 } else { 920 } else {
894 $self->{wbuf} .= $_[0]; 921 utf8::downgrade $self->{wbuf} .= $_[0];
895 $self->_drain_wbuf if $self->{fh}; 922 $self->_drain_wbuf if $self->{fh};
896 } 923 }
897} 924}
898 925
899=item $handle->push_write (type => @args) 926=item $handle->push_write (type => @args)
900 927
901Instead of formatting your data yourself, you can also let this module do 928Instead of formatting your data yourself, you can also let this module
902the job by specifying a type and type-specific arguments. 929do the job by specifying a type and type-specific arguments. You
930can also specify the (fully qualified) name of a package, in which
931case AnyEvent tries to load the package and then expects to find the
932C<anyevent_read_type> function inside (see "custom write types", below).
903 933
904Predefined types are (if you have ideas for additional types, feel free to 934Predefined types are (if you have ideas for additional types, feel free to
905drop by and tell us): 935drop by and tell us):
906 936
907=over 4 937=over 4
1010the peer. 1040the peer.
1011 1041
1012You can rely on the normal read queue and C<on_eof> handling 1042You can rely on the normal read queue and C<on_eof> handling
1013afterwards. This is the cleanest way to close a connection. 1043afterwards. This is the cleanest way to close a connection.
1014 1044
1045This method may invoke callbacks (and therefore the handle might be
1046destroyed after it returns).
1047
1015=cut 1048=cut
1016 1049
1017sub push_shutdown { 1050sub push_shutdown {
1018 my ($self) = @_; 1051 my ($self) = @_;
1019 1052
1020 delete $self->{low_water_mark}; 1053 delete $self->{low_water_mark};
1021 $self->on_drain (sub { shutdown $_[0]{fh}, 1 }); 1054 $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
1022} 1055}
1023 1056
1024=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 1057=item custom write types - Package::anyevent_write_type $handle, @args
1025 1058
1026This function (not method) lets you add your own types to C<push_write>. 1059Instead of one of the predefined types, you can also specify the name of
1060a package. AnyEvent will try to load the package and then expects to find
1061a function named C<anyevent_write_type> inside. If it isn't found, it
1062progressively tries to load the parent package until it either finds the
1063function (good) or runs out of packages (bad).
1064
1027Whenever the given C<type> is used, C<push_write> will invoke the code 1065Whenever the given C<type> is used, C<push_write> will the function with
1028reference with the handle object and the remaining arguments. 1066the handle object and the remaining arguments.
1029 1067
1030The code reference is supposed to return a single octet string that will 1068The function is supposed to return a single octet string that will be
1031be appended to the write buffer. 1069appended to the write buffer, so you cna mentally treat this function as a
1070"arguments to on-the-wire-format" converter.
1032 1071
1033Note that this is a function, and all types registered this way will be 1072Example: implement a custom write type C<join> that joins the remaining
1034global, so try to use unique names. 1073arguments using the first one.
1074
1075 $handle->push_write (My::Type => " ", 1,2,3);
1076
1077 # uses the following package, which can be defined in the "My::Type" or in
1078 # the "My" modules to be auto-loaded, or just about anywhere when the
1079 # My::Type::anyevent_write_type is defined before invoking it.
1080
1081 package My::Type;
1082
1083 sub anyevent_write_type {
1084 my ($handle, $delim, @args) = @_;
1085
1086 join $delim, @args
1087 }
1035 1088
1036=cut 1089=cut
1037 1090
1038############################################################################# 1091#############################################################################
1039 1092
1195 1248
1196This replaces the currently set C<on_read> callback, or clears it (when 1249This replaces the currently set C<on_read> callback, or clears it (when
1197the new callback is C<undef>). See the description of C<on_read> in the 1250the new callback is C<undef>). See the description of C<on_read> in the
1198constructor. 1251constructor.
1199 1252
1253This method may invoke callbacks (and therefore the handle might be
1254destroyed after it returns).
1255
1200=cut 1256=cut
1201 1257
1202sub on_read { 1258sub on_read {
1203 my ($self, $cb) = @_; 1259 my ($self, $cb) = @_;
1204 1260
1243 1299
1244If enough data was available, then the callback must remove all data it is 1300If enough data was available, then the callback must remove all data it is
1245interested in (which can be none at all) and return a true value. After returning 1301interested in (which can be none at all) and return a true value. After returning
1246true, it will be removed from the queue. 1302true, it will be removed from the queue.
1247 1303
1304These methods may invoke callbacks (and therefore the handle might be
1305destroyed after it returns).
1306
1248=cut 1307=cut
1249 1308
1250our %RH; 1309our %RH;
1251 1310
1252sub register_read_type($$) { 1311sub register_read_type($$) {
1258 my $cb = pop; 1317 my $cb = pop;
1259 1318
1260 if (@_) { 1319 if (@_) {
1261 my $type = shift; 1320 my $type = shift;
1262 1321
1322 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1263 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 1323 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_read")
1264 ->($self, $cb, @_); 1324 ->($self, $cb, @_);
1265 } 1325 }
1266 1326
1267 push @{ $self->{_queue} }, $cb; 1327 push @{ $self->{_queue} }, $cb;
1268 $self->_drain_rbuf; 1328 $self->_drain_rbuf;
1287 1347
1288=item $handle->unshift_read (type => @args, $cb) 1348=item $handle->unshift_read (type => @args, $cb)
1289 1349
1290Instead of providing a callback that parses the data itself you can chose 1350Instead of providing a callback that parses the data itself you can chose
1291between a number of predefined parsing formats, for chunks of data, lines 1351between a number of predefined parsing formats, for chunks of data, lines
1292etc. 1352etc. You can also specify the (fully qualified) name of a package, in
1353which case AnyEvent tries to load the package and then expects to find the
1354C<anyevent_read_type> function inside (see "custom read types", below).
1293 1355
1294Predefined types are (if you have ideas for additional types, feel free to 1356Predefined types are (if you have ideas for additional types, feel free to
1295drop by and tell us): 1357drop by and tell us):
1296 1358
1297=over 4 1359=over 4
1616 } 1678 }
1617}; 1679};
1618 1680
1619=back 1681=back
1620 1682
1621=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1683=item custom read types - Package::anyevent_read_type $handle, $cb, @args
1622 1684
1623This function (not method) lets you add your own types to C<push_read>. 1685Instead of one of the predefined types, you can also specify the name
1686of a package. AnyEvent will try to load the package and then expects to
1687find a function named C<anyevent_read_type> inside. If it isn't found, it
1688progressively tries to load the parent package until it either finds the
1689function (good) or runs out of packages (bad).
1624 1690
1625Whenever the given C<type> is used, C<push_read> will invoke the code 1691Whenever this type is used, C<push_read> will invoke the function with the
1626reference with the handle object, the callback and the remaining 1692handle object, the original callback and the remaining arguments.
1627arguments.
1628 1693
1629The code reference is supposed to return a callback (usually a closure) 1694The function is supposed to return a callback (usually a closure) that
1630that works as a plain read callback (see C<< ->push_read ($cb) >>). 1695works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
1696mentally treat the function as a "configurable read type to read callback"
1697converter.
1631 1698
1632It should invoke the passed callback when it is done reading (remember to 1699It should invoke the original callback when it is done reading (remember
1633pass C<$handle> as first argument as all other callbacks do that). 1700to pass C<$handle> as first argument as all other callbacks do that,
1701although there is no strict requirement on this).
1634 1702
1635Note that this is a function, and all types registered this way will be
1636global, so try to use unique names.
1637
1638For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, 1703For examples, see the source of this module (F<perldoc -m
1639search for C<register_read_type>)). 1704AnyEvent::Handle>, search for C<register_read_type>)).
1640 1705
1641=item $handle->stop_read 1706=item $handle->stop_read
1642 1707
1643=item $handle->start_read 1708=item $handle->start_read
1644 1709
1664} 1729}
1665 1730
1666sub start_read { 1731sub start_read {
1667 my ($self) = @_; 1732 my ($self) = @_;
1668 1733
1669 unless ($self->{_rw} || $self->{_eof}) { 1734 unless ($self->{_rw} || $self->{_eof} || !$self->{fh}) {
1670 Scalar::Util::weaken $self; 1735 Scalar::Util::weaken $self;
1671 1736
1672 $self->{_rw} = AE::io $self->{fh}, 0, sub { 1737 $self->{_rw} = AE::io $self->{fh}, 0, sub {
1673 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf}); 1738 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1674 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1739 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
1767 && ($tmp != $ERROR_SYSCALL || $!); 1832 && ($tmp != $ERROR_SYSCALL || $!);
1768 1833
1769 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) { 1834 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1770 $self->{wbuf} .= $tmp; 1835 $self->{wbuf} .= $tmp;
1771 $self->_drain_wbuf; 1836 $self->_drain_wbuf;
1837 $self->{tls} or return; # tls session might have gone away in callback
1772 } 1838 }
1773 1839
1774 $self->{_on_starttls} 1840 $self->{_on_starttls}
1775 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK () 1841 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
1776 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established"); 1842 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
1800when this function returns. 1866when this function returns.
1801 1867
1802Due to bugs in OpenSSL, it might or might not be possible to do multiple 1868Due to bugs in OpenSSL, it might or might not be possible to do multiple
1803handshakes on the same stream. Best do not attempt to use the stream after 1869handshakes on the same stream. Best do not attempt to use the stream after
1804stopping TLS. 1870stopping TLS.
1871
1872This method may invoke callbacks (and therefore the handle might be
1873destroyed after it returns).
1805 1874
1806=cut 1875=cut
1807 1876
1808our %TLS_CACHE; #TODO not yet documented, should we? 1877our %TLS_CACHE; #TODO not yet documented, should we?
1809 1878
1875 1944
1876=item $handle->stoptls 1945=item $handle->stoptls
1877 1946
1878Shuts down the SSL connection - this makes a proper EOF handshake by 1947Shuts down the SSL connection - this makes a proper EOF handshake by
1879sending a close notify to the other side, but since OpenSSL doesn't 1948sending a close notify to the other side, but since OpenSSL doesn't
1880support non-blocking shut downs, it is not guarenteed that you can re-use 1949support non-blocking shut downs, it is not guaranteed that you can re-use
1881the stream afterwards. 1950the stream afterwards.
1951
1952This method may invoke callbacks (and therefore the handle might be
1953destroyed after it returns).
1882 1954
1883=cut 1955=cut
1884 1956
1885sub stoptls { 1957sub stoptls {
1886 my ($self) = @_; 1958 my ($self) = @_;
1887 1959
1888 if ($self->{tls}) { 1960 if ($self->{tls} && $self->{fh}) {
1889 Net::SSLeay::shutdown ($self->{tls}); 1961 Net::SSLeay::shutdown ($self->{tls});
1890 1962
1891 &_dotls; 1963 &_dotls;
1892 1964
1893# # we don't give a shit. no, we do, but we can't. no...#d# 1965# # we don't give a shit. no, we do, but we can't. no...#d#
1970 2042
1971sub AnyEvent::Handle::destroyed::AUTOLOAD { 2043sub AnyEvent::Handle::destroyed::AUTOLOAD {
1972 #nop 2044 #nop
1973} 2045}
1974 2046
2047=item $handle->destroyed
2048
2049Returns false as long as the handle hasn't been destroyed by a call to C<<
2050->destroy >>, true otherwise.
2051
2052Can be useful to decide whether the handle is still valid after some
2053callback possibly destroyed the handle. For example, C<< ->push_write >>,
2054C<< ->starttls >> and other methods can call user callbacks, which in turn
2055can destroy the handle, so work can be avoided by checking sometimes:
2056
2057 $hdl->starttls ("accept");
2058 return if $hdl->destroyed;
2059 $hdl->push_write (...
2060
2061Note that the call to C<push_write> will silently be ignored if the handle
2062has been destroyed, so often you can just ignore the possibility of the
2063handle being destroyed.
2064
2065=cut
2066
2067sub destroyed { 0 }
2068sub AnyEvent::Handle::destroyed::destroyed { 1 }
2069
1975=item AnyEvent::Handle::TLS_CTX 2070=item AnyEvent::Handle::TLS_CTX
1976 2071
1977This function creates and returns the AnyEvent::TLS object used by default 2072This function creates and returns the AnyEvent::TLS object used by default
1978for TLS mode. 2073for TLS mode.
1979 2074

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines