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.176 by root, Sun Aug 9 00:20:35 2009 UTC vs.
Revision 1.194 by root, Thu May 20 21:22:21 2010 UTC

1=head1 NAME 1=head1 NAME
2 2
3AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent 3AnyEvent::Handle - non-blocking I/O on streaming handles via AnyEvent
4
5=cut
6
7our $VERSION = 4.92;
8 4
9=head1 SYNOPSIS 5=head1 SYNOPSIS
10 6
11 use AnyEvent; 7 use AnyEvent;
12 use AnyEvent::Handle; 8 use AnyEvent::Handle;
18 on_error => sub { 14 on_error => sub {
19 my ($hdl, $fatal, $msg) = @_; 15 my ($hdl, $fatal, $msg) = @_;
20 warn "got error $msg\n"; 16 warn "got error $msg\n";
21 $hdl->destroy; 17 $hdl->destroy;
22 $cv->send; 18 $cv->send;
23 ); 19 };
24 20
25 # send some request line 21 # send some request line
26 $hdl->push_write ("getinfo\015\012"); 22 $hdl->push_write ("getinfo\015\012");
27 23
28 # read the response line 24 # read the response line
35 $cv->recv; 31 $cv->recv;
36 32
37=head1 DESCRIPTION 33=head1 DESCRIPTION
38 34
39This module is a helper module to make it easier to do event-based I/O on 35This module is a helper module to make it easier to do event-based I/O on
40filehandles. 36stream-based filehandles (sockets, pipes or other stream things).
41 37
42The L<AnyEvent::Intro> tutorial contains some well-documented 38The L<AnyEvent::Intro> tutorial contains some well-documented
43AnyEvent::Handle examples. 39AnyEvent::Handle examples.
44 40
45In the following, when the documentation refers to of "bytes" then this 41In the following, when the documentation refers to of "bytes" then this
62use Errno qw(EAGAIN EINTR); 58use Errno qw(EAGAIN EINTR);
63 59
64use AnyEvent (); BEGIN { AnyEvent::common_sense } 60use AnyEvent (); BEGIN { AnyEvent::common_sense }
65use AnyEvent::Util qw(WSAEWOULDBLOCK); 61use AnyEvent::Util qw(WSAEWOULDBLOCK);
66 62
63our $VERSION = $AnyEvent::VERSION;
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
67=head1 METHODS 80=head1 METHODS
68 81
69=over 4 82=over 4
70 83
71=item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value... 84=item $handle = B<new> AnyEvent::Handle fh => $filehandle, key => value...
72 85
73The constructor supports these arguments (all as C<< key => value >> pairs). 86The constructor supports these arguments (all as C<< key => value >> pairs).
74 87
75=over 4 88=over 4
76 89
116 129
117The actual numeric host and port (the socket peername) are passed as 130The actual numeric host and port (the socket peername) are passed as
118parameters, together with a retry callback. 131parameters, together with a retry callback.
119 132
120When, for some reason, the handle is not acceptable, then calling 133When, for some reason, the handle is not acceptable, then calling
121C<$retry> will continue with the next conenction target (in case of 134C<$retry> will continue with the next connection target (in case of
122multi-homed hosts or SRV records there can be multiple connection 135multi-homed hosts or SRV records there can be multiple connection
123endpoints). 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
124tls status and similar properties of the handle are being reset. 137status, tls status and similar properties of the handle will have been
138reset.
125 139
126In 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.
127 141
128=item on_connect_error => $cb->($handle, $message) 142=item on_connect_error => $cb->($handle, $message)
129 143
130This callback is called when the conenction could not be 144This callback is called when the connection could not be
131established. C<$!> will contain the relevant error code, and C<$message> a 145established. C<$!> will contain the relevant error code, and C<$message> a
132message describing it (usually the same as C<"$!">). 146message describing it (usually the same as C<"$!">).
133 147
134If 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
135fatal error instead. 149fatal error instead.
287accomplishd by setting this option to a true value. 301accomplishd by setting this option to a true value.
288 302
289The default is your opertaing system's default behaviour (most likely 303The default is your opertaing system's default behaviour (most likely
290enabled), this option explicitly enables or disables it, if possible. 304enabled), this option explicitly enables or disables it, if possible.
291 305
306=item keepalive => <boolean>
307
308Enables (default disable) the SO_KEEPALIVE option on the stream socket:
309normally, TCP connections have no time-out once established, so TCP
310connections, once established, can stay alive forever even when the other
311side has long gone. TCP keepalives are a cheap way to take down long-lived
312TCP connections whent he other side becomes unreachable. While the default
313is OS-dependent, TCP keepalives usually kick in after around two hours,
314and, if the other side doesn't reply, take down the TCP connection some 10
315to 15 minutes later.
316
317It is harmless to specify this option for file handles that do not support
318keepalives, and enabling it on connections that are potentially long-lived
319is usually a good idea.
320
321=item oobinline => <boolean>
322
323BSD majorly fucked up the implementation of TCP urgent data. The result
324is that almost no OS implements TCP according to the specs, and every OS
325implements it slightly differently.
326
327If you want to handle TCP urgent data, then setting this flag (the default
328is enabled) gives you the most portable way of getting urgent data, by
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.
337
292=item read_size => <bytes> 338=item read_size => <bytes>
293 339
294The default read block size (the amount of bytes this module will 340The default read block size (the amount of bytes this module will
295try to read during each loop iteration, which affects memory 341try to read during each loop iteration, which affects memory
296requirements). Default: C<8192>. 342requirements). Default: C<8192>.
329C<undef>. 375C<undef>.
330 376
331=item tls => "accept" | "connect" | Net::SSLeay::SSL object 377=item tls => "accept" | "connect" | Net::SSLeay::SSL object
332 378
333When this parameter is given, it enables TLS (SSL) mode, that means 379When this parameter is given, it enables TLS (SSL) mode, that means
334AnyEvent 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
335established and will transparently encrypt/decrypt data afterwards. 381established and will transparently encrypt/decrypt data afterwards.
336 382
337All TLS protocol errors will be signalled as C<EPROTO>, with an 383All TLS protocol errors will be signalled as C<EPROTO>, with an
338appropriate error message. 384appropriate error message.
339 385
452 delete $self->{_skip_drain_rbuf}; 498 delete $self->{_skip_drain_rbuf};
453 $self->_start; 499 $self->_start;
454 500
455 $self->{on_connect} 501 $self->{on_connect}
456 and $self->{on_connect}($self, $host, $port, sub { 502 and $self->{on_connect}($self, $host, $port, sub {
457 delete @$self{qw(fh _tw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)}; 503 delete @$self{qw(fh _tw _rtw _wtw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)};
458 $self->{_skip_drain_rbuf} = 1; 504 $self->{_skip_drain_rbuf} = 1;
459 &$retry; 505 &$retry;
460 }); 506 });
461 507
462 } else { 508 } else {
486} 532}
487 533
488sub _start { 534sub _start {
489 my ($self) = @_; 535 my ($self) = @_;
490 536
537 # too many clueless people try to use udp and similar sockets
538 # with AnyEvent::Handle, do them a favour.
539 if (Socket::SOCK_STREAM != unpack "I", getsockopt $self->{fh}, Socket::SOL_SOCKET (), Socket::SO_TYPE ()) {
540 Carp::croak "AnyEvent::Handle: only stream sockets supported, anything else will NOT work!";
541 }
542
491 AnyEvent::Util::fh_nonblocking $self->{fh}, 1; 543 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
492 544
493 $self->{_activity} = 545 $self->{_activity} =
494 $self->{_ractivity} = 546 $self->{_ractivity} =
495 $self->{_wactivity} = AE::now; 547 $self->{_wactivity} = AE::now;
496 548
497 $self->timeout (delete $self->{timeout} ) if $self->{timeout}; 549 $self->timeout (delete $self->{timeout} ) if $self->{timeout};
498 $self->rtimeout (delete $self->{rtimeout}) if $self->{rtimeout}; 550 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout};
499 $self->wtimeout (delete $self->{wtimeout}) if $self->{wtimeout}; 551 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout};
500 552
501 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay}; 553 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay} && $self->{no_delay};
554 $self->keepalive (delete $self->{keepalive}) if exists $self->{keepalive} && $self->{keepalive};
502 555
556 $self->oobinline (exists $self->{oobinline} ? delete $self->{oobinline} : 1);
557
503 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 558 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
504 if $self->{tls}; 559 if $self->{tls};
505 560
506 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 561 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
507 562
508 $self->start_read 563 $self->start_read
509 if $self->{on_read} || @{ $self->{_queue} }; 564 if $self->{on_read} || @{ $self->{_queue} };
510 565
511 $self->_drain_wbuf; 566 $self->_drain_wbuf;
512} 567}
513
514#sub _shutdown {
515# my ($self) = @_;
516#
517# delete @$self{qw(_tw _rw _ww fh wbuf on_read _queue)};
518# $self->{_eof} = 1; # tell starttls et. al to stop trying
519#
520# &_freetls;
521#}
522 568
523sub _error { 569sub _error {
524 my ($self, $errno, $fatal, $message) = @_; 570 my ($self, $errno, $fatal, $message) = @_;
525 571
526 $! = $errno; 572 $! = $errno;
527 $message ||= "$!"; 573 $message ||= "$!";
528 574
529 if ($self->{on_error}) { 575 if ($self->{on_error}) {
530 $self->{on_error}($self, $fatal, $message); 576 $self->{on_error}($self, $fatal, $message);
531 $self->destroy if $fatal; 577 $self->destroy if $fatal;
532 } elsif ($self->{fh}) { 578 } elsif ($self->{fh} || $self->{connect}) {
533 $self->destroy; 579 $self->destroy;
534 Carp::croak "AnyEvent::Handle uncaught error: $message"; 580 Carp::croak "AnyEvent::Handle uncaught error: $message";
535 } 581 }
536} 582}
537 583
598sub no_delay { 644sub no_delay {
599 $_[0]{no_delay} = $_[1]; 645 $_[0]{no_delay} = $_[1];
600 646
601 eval { 647 eval {
602 local $SIG{__DIE__}; 648 local $SIG{__DIE__};
603 setsockopt $_[0]{fh}, &Socket::IPPROTO_TCP, &Socket::TCP_NODELAY, int $_[1] 649 setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
604 if $_[0]{fh}; 650 if $_[0]{fh};
605 }; 651 };
606} 652}
607 653
654=item $handle->keepalive ($boolean)
655
656Enables or disables the C<keepalive> setting (see constructor argument of
657the same name for details).
658
659=cut
660
661sub keepalive {
662 $_[0]{keepalive} = $_[1];
663
664 eval {
665 local $SIG{__DIE__};
666 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
667 if $_[0]{fh};
668 };
669}
670
671=item $handle->oobinline ($boolean)
672
673Enables or disables the C<oobinline> setting (see constructor argument of
674the same name for details).
675
676=cut
677
678sub oobinline {
679 $_[0]{oobinline} = $_[1];
680
681 eval {
682 local $SIG{__DIE__};
683 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_OOBINLINE (), int $_[1]
684 if $_[0]{fh};
685 };
686}
687
688=item $handle->keepalive ($boolean)
689
690Enables or disables the C<keepalive> setting (see constructor argument of
691the same name for details).
692
693=cut
694
695sub keepalive {
696 $_[0]{keepalive} = $_[1];
697
698 eval {
699 local $SIG{__DIE__};
700 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
701 if $_[0]{fh};
702 };
703}
704
608=item $handle->on_starttls ($cb) 705=item $handle->on_starttls ($cb)
609 706
610Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument). 707Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument).
611 708
612=cut 709=cut
619 716
620Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument). 717Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument).
621 718
622=cut 719=cut
623 720
624sub on_starttls { 721sub on_stoptls {
625 $_[0]{on_stoptls} = $_[1]; 722 $_[0]{on_stoptls} = $_[1];
626} 723}
627 724
628=item $handle->rbuf_max ($max_octets) 725=item $handle->rbuf_max ($max_octets)
629 726
741=item $handle->on_drain ($cb) 838=item $handle->on_drain ($cb)
742 839
743Sets the C<on_drain> callback or clears it (see the description of 840Sets the C<on_drain> callback or clears it (see the description of
744C<on_drain> in the constructor). 841C<on_drain> in the constructor).
745 842
843This method may invoke callbacks (and therefore the handle might be
844destroyed after it returns).
845
746=cut 846=cut
747 847
748sub on_drain { 848sub on_drain {
749 my ($self, $cb) = @_; 849 my ($self, $cb) = @_;
750 850
757=item $handle->push_write ($data) 857=item $handle->push_write ($data)
758 858
759Queues the given scalar to be written. You can push as much data as you 859Queues the given scalar to be written. You can push as much data as you
760want (only limited by the available memory), as C<AnyEvent::Handle> 860want (only limited by the available memory), as C<AnyEvent::Handle>
761buffers it independently of the kernel. 861buffers it independently of the kernel.
862
863This method may invoke callbacks (and therefore the handle might be
864destroyed after it returns).
762 865
763=cut 866=cut
764 867
765sub _drain_wbuf { 868sub _drain_wbuf {
766 my ($self) = @_; 869 my ($self) = @_;
796 }; 899 };
797} 900}
798 901
799our %WH; 902our %WH;
800 903
904# deprecated
801sub register_write_type($$) { 905sub register_write_type($$) {
802 $WH{$_[0]} = $_[1]; 906 $WH{$_[0]} = $_[1];
803} 907}
804 908
805sub push_write { 909sub push_write {
806 my $self = shift; 910 my $self = shift;
807 911
808 if (@_ > 1) { 912 if (@_ > 1) {
809 my $type = shift; 913 my $type = shift;
810 914
915 @_ = ($WH{$type} ||= _load_func "$type\::anyevent_write_type"
811 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write") 916 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_write")
812 ->($self, @_); 917 ->($self, @_);
813 } 918 }
814 919
920 # we downgrade here to avoid hard-to-track-down bugs,
921 # and diagnose the problem earlier and better.
922
815 if ($self->{tls}) { 923 if ($self->{tls}) {
816 $self->{_tls_wbuf} .= $_[0]; 924 utf8::downgrade $self->{_tls_wbuf} .= $_[0];
817 &_dotls ($self) if $self->{fh}; 925 &_dotls ($self) if $self->{fh};
818 } else { 926 } else {
819 $self->{wbuf} .= $_[0]; 927 utf8::downgrade $self->{wbuf} .= $_[0];
820 $self->_drain_wbuf if $self->{fh}; 928 $self->_drain_wbuf if $self->{fh};
821 } 929 }
822} 930}
823 931
824=item $handle->push_write (type => @args) 932=item $handle->push_write (type => @args)
825 933
826Instead of formatting your data yourself, you can also let this module do 934Instead of formatting your data yourself, you can also let this module
827the job by specifying a type and type-specific arguments. 935do the job by specifying a type and type-specific arguments. You
936can also specify the (fully qualified) name of a package, in which
937case AnyEvent tries to load the package and then expects to find the
938C<anyevent_read_type> function inside (see "custom write types", below).
828 939
829Predefined types are (if you have ideas for additional types, feel free to 940Predefined types are (if you have ideas for additional types, feel free to
830drop by and tell us): 941drop by and tell us):
831 942
832=over 4 943=over 4
889Other languages could read single lines terminated by a newline and pass 1000Other languages could read single lines terminated by a newline and pass
890this line into their JSON decoder of choice. 1001this line into their JSON decoder of choice.
891 1002
892=cut 1003=cut
893 1004
1005sub json_coder() {
1006 eval { require JSON::XS; JSON::XS->new->utf8 }
1007 || do { require JSON; JSON->new->utf8 }
1008}
1009
894register_write_type json => sub { 1010register_write_type json => sub {
895 my ($self, $ref) = @_; 1011 my ($self, $ref) = @_;
896 1012
897 require JSON; 1013 my $json = $self->{json} ||= json_coder;
898 1014
899 $self->{json} ? $self->{json}->encode ($ref) 1015 $json->encode ($ref)
900 : JSON::encode_json ($ref)
901}; 1016};
902 1017
903=item storable => $reference 1018=item storable => $reference
904 1019
905Freezes the given reference using L<Storable> and writes it to the 1020Freezes the given reference using L<Storable> and writes it to the
931the peer. 1046the peer.
932 1047
933You can rely on the normal read queue and C<on_eof> handling 1048You can rely on the normal read queue and C<on_eof> handling
934afterwards. This is the cleanest way to close a connection. 1049afterwards. This is the cleanest way to close a connection.
935 1050
1051This method may invoke callbacks (and therefore the handle might be
1052destroyed after it returns).
1053
936=cut 1054=cut
937 1055
938sub push_shutdown { 1056sub push_shutdown {
939 my ($self) = @_; 1057 my ($self) = @_;
940 1058
941 delete $self->{low_water_mark}; 1059 delete $self->{low_water_mark};
942 $self->on_drain (sub { shutdown $_[0]{fh}, 1 }); 1060 $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
943} 1061}
944 1062
945=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 1063=item custom write types - Package::anyevent_write_type $handle, @args
946 1064
947This function (not method) lets you add your own types to C<push_write>. 1065Instead of one of the predefined types, you can also specify the name of
1066a package. AnyEvent will try to load the package and then expects to find
1067a function named C<anyevent_write_type> inside. If it isn't found, it
1068progressively tries to load the parent package until it either finds the
1069function (good) or runs out of packages (bad).
1070
948Whenever the given C<type> is used, C<push_write> will invoke the code 1071Whenever the given C<type> is used, C<push_write> will the function with
949reference with the handle object and the remaining arguments. 1072the handle object and the remaining arguments.
950 1073
951The code reference is supposed to return a single octet string that will 1074The function is supposed to return a single octet string that will be
952be appended to the write buffer. 1075appended to the write buffer, so you cna mentally treat this function as a
1076"arguments to on-the-wire-format" converter.
953 1077
954Note that this is a function, and all types registered this way will be 1078Example: implement a custom write type C<join> that joins the remaining
955global, so try to use unique names. 1079arguments using the first one.
1080
1081 $handle->push_write (My::Type => " ", 1,2,3);
1082
1083 # uses the following package, which can be defined in the "My::Type" or in
1084 # the "My" modules to be auto-loaded, or just about anywhere when the
1085 # My::Type::anyevent_write_type is defined before invoking it.
1086
1087 package My::Type;
1088
1089 sub anyevent_write_type {
1090 my ($handle, $delim, @args) = @_;
1091
1092 join $delim, @args
1093 }
956 1094
957=cut 1095=cut
958 1096
959############################################################################# 1097#############################################################################
960 1098
1116 1254
1117This replaces the currently set C<on_read> callback, or clears it (when 1255This replaces the currently set C<on_read> callback, or clears it (when
1118the new callback is C<undef>). See the description of C<on_read> in the 1256the new callback is C<undef>). See the description of C<on_read> in the
1119constructor. 1257constructor.
1120 1258
1259This method may invoke callbacks (and therefore the handle might be
1260destroyed after it returns).
1261
1121=cut 1262=cut
1122 1263
1123sub on_read { 1264sub on_read {
1124 my ($self, $cb) = @_; 1265 my ($self, $cb) = @_;
1125 1266
1164 1305
1165If enough data was available, then the callback must remove all data it is 1306If enough data was available, then the callback must remove all data it is
1166interested in (which can be none at all) and return a true value. After returning 1307interested in (which can be none at all) and return a true value. After returning
1167true, it will be removed from the queue. 1308true, it will be removed from the queue.
1168 1309
1310These methods may invoke callbacks (and therefore the handle might be
1311destroyed after it returns).
1312
1169=cut 1313=cut
1170 1314
1171our %RH; 1315our %RH;
1172 1316
1173sub register_read_type($$) { 1317sub register_read_type($$) {
1179 my $cb = pop; 1323 my $cb = pop;
1180 1324
1181 if (@_) { 1325 if (@_) {
1182 my $type = shift; 1326 my $type = shift;
1183 1327
1328 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1184 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 1329 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_read")
1185 ->($self, $cb, @_); 1330 ->($self, $cb, @_);
1186 } 1331 }
1187 1332
1188 push @{ $self->{_queue} }, $cb; 1333 push @{ $self->{_queue} }, $cb;
1189 $self->_drain_rbuf; 1334 $self->_drain_rbuf;
1198 1343
1199 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read") 1344 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
1200 ->($self, $cb, @_); 1345 ->($self, $cb, @_);
1201 } 1346 }
1202 1347
1203
1204 unshift @{ $self->{_queue} }, $cb; 1348 unshift @{ $self->{_queue} }, $cb;
1205 $self->_drain_rbuf; 1349 $self->_drain_rbuf;
1206} 1350}
1207 1351
1208=item $handle->push_read (type => @args, $cb) 1352=item $handle->push_read (type => @args, $cb)
1209 1353
1210=item $handle->unshift_read (type => @args, $cb) 1354=item $handle->unshift_read (type => @args, $cb)
1211 1355
1212Instead of providing a callback that parses the data itself you can chose 1356Instead of providing a callback that parses the data itself you can chose
1213between a number of predefined parsing formats, for chunks of data, lines 1357between a number of predefined parsing formats, for chunks of data, lines
1214etc. 1358etc. You can also specify the (fully qualified) name of a package, in
1359which case AnyEvent tries to load the package and then expects to find the
1360C<anyevent_read_type> function inside (see "custom read types", below).
1215 1361
1216Predefined types are (if you have ideas for additional types, feel free to 1362Predefined types are (if you have ideas for additional types, feel free to
1217drop by and tell us): 1363drop by and tell us):
1218 1364
1219=over 4 1365=over 4
1459=cut 1605=cut
1460 1606
1461register_read_type json => sub { 1607register_read_type json => sub {
1462 my ($self, $cb) = @_; 1608 my ($self, $cb) = @_;
1463 1609
1464 my $json = $self->{json} ||= 1610 my $json = $self->{json} ||= json_coder;
1465 eval { require JSON::XS; JSON::XS->new->utf8 }
1466 || do { require JSON; JSON->new->utf8 };
1467 1611
1468 my $data; 1612 my $data;
1469 my $rbuf = \$self->{rbuf}; 1613 my $rbuf = \$self->{rbuf};
1470 1614
1471 sub { 1615 sub {
1540 } 1684 }
1541}; 1685};
1542 1686
1543=back 1687=back
1544 1688
1545=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1689=item custom read types - Package::anyevent_read_type $handle, $cb, @args
1546 1690
1547This function (not method) lets you add your own types to C<push_read>. 1691Instead of one of the predefined types, you can also specify the name
1692of a package. AnyEvent will try to load the package and then expects to
1693find a function named C<anyevent_read_type> inside. If it isn't found, it
1694progressively tries to load the parent package until it either finds the
1695function (good) or runs out of packages (bad).
1548 1696
1549Whenever the given C<type> is used, C<push_read> will invoke the code 1697Whenever this type is used, C<push_read> will invoke the function with the
1550reference with the handle object, the callback and the remaining 1698handle object, the original callback and the remaining arguments.
1551arguments.
1552 1699
1553The code reference is supposed to return a callback (usually a closure) 1700The function is supposed to return a callback (usually a closure) that
1554that works as a plain read callback (see C<< ->push_read ($cb) >>). 1701works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
1702mentally treat the function as a "configurable read type to read callback"
1703converter.
1555 1704
1556It should invoke the passed callback when it is done reading (remember to 1705It should invoke the original callback when it is done reading (remember
1557pass C<$handle> as first argument as all other callbacks do that). 1706to pass C<$handle> as first argument as all other callbacks do that,
1707although there is no strict requirement on this).
1558 1708
1559Note that this is a function, and all types registered this way will be
1560global, so try to use unique names.
1561
1562For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, 1709For examples, see the source of this module (F<perldoc -m
1563search for C<register_read_type>)). 1710AnyEvent::Handle>, search for C<register_read_type>)).
1564 1711
1565=item $handle->stop_read 1712=item $handle->stop_read
1566 1713
1567=item $handle->start_read 1714=item $handle->start_read
1568 1715
1588} 1735}
1589 1736
1590sub start_read { 1737sub start_read {
1591 my ($self) = @_; 1738 my ($self) = @_;
1592 1739
1593 unless ($self->{_rw} || $self->{_eof}) { 1740 unless ($self->{_rw} || $self->{_eof} || !$self->{fh}) {
1594 Scalar::Util::weaken $self; 1741 Scalar::Util::weaken $self;
1595 1742
1596 $self->{_rw} = AE::io $self->{fh}, 0, sub { 1743 $self->{_rw} = AE::io $self->{fh}, 0, sub {
1597 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf}); 1744 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1598 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1745 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
1691 && ($tmp != $ERROR_SYSCALL || $!); 1838 && ($tmp != $ERROR_SYSCALL || $!);
1692 1839
1693 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) { 1840 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1694 $self->{wbuf} .= $tmp; 1841 $self->{wbuf} .= $tmp;
1695 $self->_drain_wbuf; 1842 $self->_drain_wbuf;
1843 $self->{tls} or return; # tls session might have gone away in callback
1696 } 1844 }
1697 1845
1698 $self->{_on_starttls} 1846 $self->{_on_starttls}
1699 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK () 1847 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
1700 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established"); 1848 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
1725 1873
1726Due to bugs in OpenSSL, it might or might not be possible to do multiple 1874Due to bugs in OpenSSL, it might or might not be possible to do multiple
1727handshakes on the same stream. Best do not attempt to use the stream after 1875handshakes on the same stream. Best do not attempt to use the stream after
1728stopping TLS. 1876stopping TLS.
1729 1877
1878This method may invoke callbacks (and therefore the handle might be
1879destroyed after it returns).
1880
1730=cut 1881=cut
1731 1882
1732our %TLS_CACHE; #TODO not yet documented, should we? 1883our %TLS_CACHE; #TODO not yet documented, should we?
1733 1884
1734sub starttls { 1885sub starttls {
1745 require Net::SSLeay; 1896 require Net::SSLeay;
1746 1897
1747 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL (); 1898 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL ();
1748 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ (); 1899 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ ();
1749 1900
1750 $tls = $self->{tls}; 1901 $tls = delete $self->{tls};
1751 $ctx = $self->{tls_ctx}; 1902 $ctx = $self->{tls_ctx};
1752 1903
1753 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session 1904 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session
1754 1905
1755 if ("HASH" eq ref $ctx) { 1906 if ("HASH" eq ref $ctx) {
1799 1950
1800=item $handle->stoptls 1951=item $handle->stoptls
1801 1952
1802Shuts down the SSL connection - this makes a proper EOF handshake by 1953Shuts down the SSL connection - this makes a proper EOF handshake by
1803sending a close notify to the other side, but since OpenSSL doesn't 1954sending a close notify to the other side, but since OpenSSL doesn't
1804support non-blocking shut downs, it is not guarenteed that you can re-use 1955support non-blocking shut downs, it is not guaranteed that you can re-use
1805the stream afterwards. 1956the stream afterwards.
1957
1958This method may invoke callbacks (and therefore the handle might be
1959destroyed after it returns).
1806 1960
1807=cut 1961=cut
1808 1962
1809sub stoptls { 1963sub stoptls {
1810 my ($self) = @_; 1964 my ($self) = @_;
1811 1965
1812 if ($self->{tls}) { 1966 if ($self->{tls} && $self->{fh}) {
1813 Net::SSLeay::shutdown ($self->{tls}); 1967 Net::SSLeay::shutdown ($self->{tls});
1814 1968
1815 &_dotls; 1969 &_dotls;
1816 1970
1817# # we don't give a shit. no, we do, but we can't. no...#d# 1971# # we don't give a shit. no, we do, but we can't. no...#d#
1894 2048
1895sub AnyEvent::Handle::destroyed::AUTOLOAD { 2049sub AnyEvent::Handle::destroyed::AUTOLOAD {
1896 #nop 2050 #nop
1897} 2051}
1898 2052
2053=item $handle->destroyed
2054
2055Returns false as long as the handle hasn't been destroyed by a call to C<<
2056->destroy >>, true otherwise.
2057
2058Can be useful to decide whether the handle is still valid after some
2059callback possibly destroyed the handle. For example, C<< ->push_write >>,
2060C<< ->starttls >> and other methods can call user callbacks, which in turn
2061can destroy the handle, so work can be avoided by checking sometimes:
2062
2063 $hdl->starttls ("accept");
2064 return if $hdl->destroyed;
2065 $hdl->push_write (...
2066
2067Note that the call to C<push_write> will silently be ignored if the handle
2068has been destroyed, so often you can just ignore the possibility of the
2069handle being destroyed.
2070
2071=cut
2072
2073sub destroyed { 0 }
2074sub AnyEvent::Handle::destroyed::destroyed { 1 }
2075
1899=item AnyEvent::Handle::TLS_CTX 2076=item AnyEvent::Handle::TLS_CTX
1900 2077
1901This function creates and returns the AnyEvent::TLS object used by default 2078This function creates and returns the AnyEvent::TLS object used by default
1902for TLS mode. 2079for TLS mode.
1903 2080

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines