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.178 by root, Tue Aug 11 01:15:17 2009 UTC vs.
Revision 1.197 by root, Tue Aug 31 00:59:55 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 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent; 7 use AnyEvent;
8 use AnyEvent::Handle; 8 use AnyEvent::Handle;
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
31 $cv->recv; 31 $cv->recv;
32 32
33=head1 DESCRIPTION 33=head1 DESCRIPTION
34 34
35This 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
36filehandles. 36stream-based filehandles (sockets, pipes or other stream things).
37 37
38The L<AnyEvent::Intro> tutorial contains some well-documented 38The L<AnyEvent::Intro> tutorial contains some well-documented
39AnyEvent::Handle examples. 39AnyEvent::Handle examples.
40 40
41In the following, when the documentation refers to of "bytes" then this 41In the following, when the documentation refers to of "bytes" then this
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.
176To access (and remove data from) the read buffer, use the C<< ->rbuf >> 192To access (and remove data from) the read buffer, use the C<< ->rbuf >>
177method or access the C<< $handle->{rbuf} >> member directly. Note that you 193method or access the C<< $handle->{rbuf} >> member directly. Note that you
178must not enlarge or modify the read buffer, you can only remove data at 194must not enlarge or modify the read buffer, you can only remove data at
179the beginning from it. 195the beginning from it.
180 196
197You can also call C<< ->push_read (...) >> or any other function that
198modifies the read queue. Or do both. Or ...
199
181When an EOF condition is detected then AnyEvent::Handle will first try to 200When an EOF condition is detected then AnyEvent::Handle will first try to
182feed all the remaining data to the queued callbacks and C<on_read> before 201feed all the remaining data to the queued callbacks and C<on_read> before
183calling the C<on_eof> callback. If no progress can be made, then a fatal 202calling the C<on_eof> callback. If no progress can be made, then a fatal
184error will be raised (with C<$!> set to C<EPIPE>). 203error will be raised (with C<$!> set to C<EPIPE>).
185 204
285accomplishd by setting this option to a true value. 304accomplishd by setting this option to a true value.
286 305
287The default is your opertaing system's default behaviour (most likely 306The default is your opertaing system's default behaviour (most likely
288enabled), this option explicitly enables or disables it, if possible. 307enabled), this option explicitly enables or disables it, if possible.
289 308
309=item keepalive => <boolean>
310
311Enables (default disable) the SO_KEEPALIVE option on the stream socket:
312normally, TCP connections have no time-out once established, so TCP
313connections, once established, can stay alive forever even when the other
314side has long gone. TCP keepalives are a cheap way to take down long-lived
315TCP connections whent he other side becomes unreachable. While the default
316is OS-dependent, TCP keepalives usually kick in after around two hours,
317and, if the other side doesn't reply, take down the TCP connection some 10
318to 15 minutes later.
319
320It is harmless to specify this option for file handles that do not support
321keepalives, and enabling it on connections that are potentially long-lived
322is usually a good idea.
323
324=item oobinline => <boolean>
325
326BSD majorly fucked up the implementation of TCP urgent data. The result
327is that almost no OS implements TCP according to the specs, and every OS
328implements it slightly differently.
329
330If you want to handle TCP urgent data, then setting this flag (the default
331is enabled) gives you the most portable way of getting urgent data, by
332putting it into the stream.
333
334Since BSD emulation of OOB data on top of TCP's urgent data can have
335security implications, AnyEvent::Handle sets this flag automatically
336unless explicitly specified. Note that setting this flag after
337establishing a connection I<may> be a bit too late (data loss could
338already have occured on BSD systems), but at least it will protect you
339from most attacks.
340
290=item read_size => <bytes> 341=item read_size => <bytes>
291 342
292The default read block size (the amount of bytes this module will 343The default read block size (the amount of bytes this module will
293try to read during each loop iteration, which affects memory 344try to read during each loop iteration, which affects memory
294requirements). Default: C<8192>. 345requirements). Default: C<8192>.
327C<undef>. 378C<undef>.
328 379
329=item tls => "accept" | "connect" | Net::SSLeay::SSL object 380=item tls => "accept" | "connect" | Net::SSLeay::SSL object
330 381
331When this parameter is given, it enables TLS (SSL) mode, that means 382When this parameter is given, it enables TLS (SSL) mode, that means
332AnyEvent will start a TLS handshake as soon as the conenction has been 383AnyEvent will start a TLS handshake as soon as the connection has been
333established and will transparently encrypt/decrypt data afterwards. 384established and will transparently encrypt/decrypt data afterwards.
334 385
335All TLS protocol errors will be signalled as C<EPROTO>, with an 386All TLS protocol errors will be signalled as C<EPROTO>, with an
336appropriate error message. 387appropriate error message.
337 388
484} 535}
485 536
486sub _start { 537sub _start {
487 my ($self) = @_; 538 my ($self) = @_;
488 539
540 # too many clueless people try to use udp and similar sockets
541 # with AnyEvent::Handle, do them a favour.
542 my $type = getsockopt $self->{fh}, Socket::SOL_SOCKET (), Socket::SO_TYPE ();
543 Carp::croak "AnyEvent::Handle: only stream sockets supported, anything else will NOT work!"
544 if Socket::SOCK_STREAM () != (unpack "I", $type) && defined $type;
545
489 AnyEvent::Util::fh_nonblocking $self->{fh}, 1; 546 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
490 547
491 $self->{_activity} = 548 $self->{_activity} =
492 $self->{_ractivity} = 549 $self->{_ractivity} =
493 $self->{_wactivity} = AE::now; 550 $self->{_wactivity} = AE::now;
494 551
495 $self->timeout (delete $self->{timeout} ) if $self->{timeout}; 552 $self->timeout (delete $self->{timeout} ) if $self->{timeout};
496 $self->rtimeout (delete $self->{rtimeout}) if $self->{rtimeout}; 553 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout};
497 $self->wtimeout (delete $self->{wtimeout}) if $self->{wtimeout}; 554 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout};
498 555
499 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay}; 556 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay} && $self->{no_delay};
557 $self->keepalive (delete $self->{keepalive}) if exists $self->{keepalive} && $self->{keepalive};
500 558
559 $self->oobinline (exists $self->{oobinline} ? delete $self->{oobinline} : 1);
560
501 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 561 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
502 if $self->{tls}; 562 if $self->{tls};
503 563
504 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 564 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
505 565
506 $self->start_read 566 $self->start_read
507 if $self->{on_read} || @{ $self->{_queue} }; 567 if $self->{on_read} || @{ $self->{_queue} };
508 568
509 $self->_drain_wbuf; 569 $self->_drain_wbuf;
516 $message ||= "$!"; 576 $message ||= "$!";
517 577
518 if ($self->{on_error}) { 578 if ($self->{on_error}) {
519 $self->{on_error}($self, $fatal, $message); 579 $self->{on_error}($self, $fatal, $message);
520 $self->destroy if $fatal; 580 $self->destroy if $fatal;
521 } elsif ($self->{fh}) { 581 } elsif ($self->{fh} || $self->{connect}) {
522 $self->destroy; 582 $self->destroy;
523 Carp::croak "AnyEvent::Handle uncaught error: $message"; 583 Carp::croak "AnyEvent::Handle uncaught error: $message";
524 } 584 }
525} 585}
526 586
587sub no_delay { 647sub no_delay {
588 $_[0]{no_delay} = $_[1]; 648 $_[0]{no_delay} = $_[1];
589 649
590 eval { 650 eval {
591 local $SIG{__DIE__}; 651 local $SIG{__DIE__};
592 setsockopt $_[0]{fh}, &Socket::IPPROTO_TCP, &Socket::TCP_NODELAY, int $_[1] 652 setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
593 if $_[0]{fh}; 653 if $_[0]{fh};
594 }; 654 };
595} 655}
596 656
657=item $handle->keepalive ($boolean)
658
659Enables or disables the C<keepalive> setting (see constructor argument of
660the same name for details).
661
662=cut
663
664sub keepalive {
665 $_[0]{keepalive} = $_[1];
666
667 eval {
668 local $SIG{__DIE__};
669 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
670 if $_[0]{fh};
671 };
672}
673
674=item $handle->oobinline ($boolean)
675
676Enables or disables the C<oobinline> setting (see constructor argument of
677the same name for details).
678
679=cut
680
681sub oobinline {
682 $_[0]{oobinline} = $_[1];
683
684 eval {
685 local $SIG{__DIE__};
686 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_OOBINLINE (), int $_[1]
687 if $_[0]{fh};
688 };
689}
690
691=item $handle->keepalive ($boolean)
692
693Enables or disables the C<keepalive> setting (see constructor argument of
694the same name for details).
695
696=cut
697
698sub keepalive {
699 $_[0]{keepalive} = $_[1];
700
701 eval {
702 local $SIG{__DIE__};
703 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
704 if $_[0]{fh};
705 };
706}
707
597=item $handle->on_starttls ($cb) 708=item $handle->on_starttls ($cb)
598 709
599Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument). 710Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument).
600 711
601=cut 712=cut
608 719
609Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument). 720Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument).
610 721
611=cut 722=cut
612 723
613sub on_starttls { 724sub on_stoptls {
614 $_[0]{on_stoptls} = $_[1]; 725 $_[0]{on_stoptls} = $_[1];
615} 726}
616 727
617=item $handle->rbuf_max ($max_octets) 728=item $handle->rbuf_max ($max_octets)
618 729
730=item $handle->on_drain ($cb) 841=item $handle->on_drain ($cb)
731 842
732Sets the C<on_drain> callback or clears it (see the description of 843Sets the C<on_drain> callback or clears it (see the description of
733C<on_drain> in the constructor). 844C<on_drain> in the constructor).
734 845
846This method may invoke callbacks (and therefore the handle might be
847destroyed after it returns).
848
735=cut 849=cut
736 850
737sub on_drain { 851sub on_drain {
738 my ($self, $cb) = @_; 852 my ($self, $cb) = @_;
739 853
746=item $handle->push_write ($data) 860=item $handle->push_write ($data)
747 861
748Queues the given scalar to be written. You can push as much data as you 862Queues the given scalar to be written. You can push as much data as you
749want (only limited by the available memory), as C<AnyEvent::Handle> 863want (only limited by the available memory), as C<AnyEvent::Handle>
750buffers it independently of the kernel. 864buffers it independently of the kernel.
865
866This method may invoke callbacks (and therefore the handle might be
867destroyed after it returns).
751 868
752=cut 869=cut
753 870
754sub _drain_wbuf { 871sub _drain_wbuf {
755 my ($self) = @_; 872 my ($self) = @_;
785 }; 902 };
786} 903}
787 904
788our %WH; 905our %WH;
789 906
907# deprecated
790sub register_write_type($$) { 908sub register_write_type($$) {
791 $WH{$_[0]} = $_[1]; 909 $WH{$_[0]} = $_[1];
792} 910}
793 911
794sub push_write { 912sub push_write {
795 my $self = shift; 913 my $self = shift;
796 914
797 if (@_ > 1) { 915 if (@_ > 1) {
798 my $type = shift; 916 my $type = shift;
799 917
918 @_ = ($WH{$type} ||= _load_func "$type\::anyevent_write_type"
800 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write") 919 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_write")
801 ->($self, @_); 920 ->($self, @_);
802 } 921 }
803 922
923 # we downgrade here to avoid hard-to-track-down bugs,
924 # and diagnose the problem earlier and better.
925
804 if ($self->{tls}) { 926 if ($self->{tls}) {
805 $self->{_tls_wbuf} .= $_[0]; 927 utf8::downgrade $self->{_tls_wbuf} .= $_[0];
806 &_dotls ($self) if $self->{fh}; 928 &_dotls ($self) if $self->{fh};
807 } else { 929 } else {
808 $self->{wbuf} .= $_[0]; 930 utf8::downgrade $self->{wbuf} .= $_[0];
809 $self->_drain_wbuf if $self->{fh}; 931 $self->_drain_wbuf if $self->{fh};
810 } 932 }
811} 933}
812 934
813=item $handle->push_write (type => @args) 935=item $handle->push_write (type => @args)
814 936
815Instead of formatting your data yourself, you can also let this module do 937Instead of formatting your data yourself, you can also let this module
816the job by specifying a type and type-specific arguments. 938do the job by specifying a type and type-specific arguments. You
939can also specify the (fully qualified) name of a package, in which
940case AnyEvent tries to load the package and then expects to find the
941C<anyevent_write_type> function inside (see "custom write types", below).
817 942
818Predefined types are (if you have ideas for additional types, feel free to 943Predefined types are (if you have ideas for additional types, feel free to
819drop by and tell us): 944drop by and tell us):
820 945
821=over 4 946=over 4
878Other languages could read single lines terminated by a newline and pass 1003Other languages could read single lines terminated by a newline and pass
879this line into their JSON decoder of choice. 1004this line into their JSON decoder of choice.
880 1005
881=cut 1006=cut
882 1007
1008sub json_coder() {
1009 eval { require JSON::XS; JSON::XS->new->utf8 }
1010 || do { require JSON; JSON->new->utf8 }
1011}
1012
883register_write_type json => sub { 1013register_write_type json => sub {
884 my ($self, $ref) = @_; 1014 my ($self, $ref) = @_;
885 1015
886 require JSON; 1016 my $json = $self->{json} ||= json_coder;
887 1017
888 $self->{json} ? $self->{json}->encode ($ref) 1018 $json->encode ($ref)
889 : JSON::encode_json ($ref)
890}; 1019};
891 1020
892=item storable => $reference 1021=item storable => $reference
893 1022
894Freezes the given reference using L<Storable> and writes it to the 1023Freezes the given reference using L<Storable> and writes it to the
920the peer. 1049the peer.
921 1050
922You can rely on the normal read queue and C<on_eof> handling 1051You can rely on the normal read queue and C<on_eof> handling
923afterwards. This is the cleanest way to close a connection. 1052afterwards. This is the cleanest way to close a connection.
924 1053
1054This method may invoke callbacks (and therefore the handle might be
1055destroyed after it returns).
1056
925=cut 1057=cut
926 1058
927sub push_shutdown { 1059sub push_shutdown {
928 my ($self) = @_; 1060 my ($self) = @_;
929 1061
930 delete $self->{low_water_mark}; 1062 delete $self->{low_water_mark};
931 $self->on_drain (sub { shutdown $_[0]{fh}, 1 }); 1063 $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
932} 1064}
933 1065
934=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 1066=item custom write types - Package::anyevent_write_type $handle, @args
935 1067
936This function (not method) lets you add your own types to C<push_write>. 1068Instead of one of the predefined types, you can also specify the name of
1069a package. AnyEvent will try to load the package and then expects to find
1070a function named C<anyevent_write_type> inside. If it isn't found, it
1071progressively tries to load the parent package until it either finds the
1072function (good) or runs out of packages (bad).
1073
937Whenever the given C<type> is used, C<push_write> will invoke the code 1074Whenever the given C<type> is used, C<push_write> will the function with
938reference with the handle object and the remaining arguments. 1075the handle object and the remaining arguments.
939 1076
940The code reference is supposed to return a single octet string that will 1077The function is supposed to return a single octet string that will be
941be appended to the write buffer. 1078appended to the write buffer, so you cna mentally treat this function as a
1079"arguments to on-the-wire-format" converter.
942 1080
943Note that this is a function, and all types registered this way will be 1081Example: implement a custom write type C<join> that joins the remaining
944global, so try to use unique names. 1082arguments using the first one.
1083
1084 $handle->push_write (My::Type => " ", 1,2,3);
1085
1086 # uses the following package, which can be defined in the "My::Type" or in
1087 # the "My" modules to be auto-loaded, or just about anywhere when the
1088 # My::Type::anyevent_write_type is defined before invoking it.
1089
1090 package My::Type;
1091
1092 sub anyevent_write_type {
1093 my ($handle, $delim, @args) = @_;
1094
1095 join $delim, @args
1096 }
945 1097
946=cut 1098=cut
947 1099
948############################################################################# 1100#############################################################################
949 1101
958ways, the "simple" way, using only C<on_read> and the "complex" way, using 1110ways, the "simple" way, using only C<on_read> and the "complex" way, using
959a queue. 1111a queue.
960 1112
961In the simple case, you just install an C<on_read> callback and whenever 1113In the simple case, you just install an C<on_read> callback and whenever
962new data arrives, it will be called. You can then remove some data (if 1114new data arrives, it will be called. You can then remove some data (if
963enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna 1115enough is there) from the read buffer (C<< $handle->rbuf >>). Or you can
964leave the data there if you want to accumulate more (e.g. when only a 1116leave the data there if you want to accumulate more (e.g. when only a
965partial message has been received so far). 1117partial message has been received so far), or change the read queue with
1118e.g. C<push_read>.
966 1119
967In the more complex case, you want to queue multiple callbacks. In this 1120In the more complex case, you want to queue multiple callbacks. In this
968case, AnyEvent::Handle will call the first queued callback each time new 1121case, AnyEvent::Handle will call the first queued callback each time new
969data arrives (also the first time it is queued) and removes it when it has 1122data arrives (also the first time it is queued) and removes it when it has
970done its job (see C<push_read>, below). 1123done its job (see C<push_read>, below).
1105 1258
1106This replaces the currently set C<on_read> callback, or clears it (when 1259This replaces the currently set C<on_read> callback, or clears it (when
1107the new callback is C<undef>). See the description of C<on_read> in the 1260the new callback is C<undef>). See the description of C<on_read> in the
1108constructor. 1261constructor.
1109 1262
1263This method may invoke callbacks (and therefore the handle might be
1264destroyed after it returns).
1265
1110=cut 1266=cut
1111 1267
1112sub on_read { 1268sub on_read {
1113 my ($self, $cb) = @_; 1269 my ($self, $cb) = @_;
1114 1270
1153 1309
1154If enough data was available, then the callback must remove all data it is 1310If enough data was available, then the callback must remove all data it is
1155interested in (which can be none at all) and return a true value. After returning 1311interested in (which can be none at all) and return a true value. After returning
1156true, it will be removed from the queue. 1312true, it will be removed from the queue.
1157 1313
1314These methods may invoke callbacks (and therefore the handle might be
1315destroyed after it returns).
1316
1158=cut 1317=cut
1159 1318
1160our %RH; 1319our %RH;
1161 1320
1162sub register_read_type($$) { 1321sub register_read_type($$) {
1168 my $cb = pop; 1327 my $cb = pop;
1169 1328
1170 if (@_) { 1329 if (@_) {
1171 my $type = shift; 1330 my $type = shift;
1172 1331
1332 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1173 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 1333 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_read")
1174 ->($self, $cb, @_); 1334 ->($self, $cb, @_);
1175 } 1335 }
1176 1336
1177 push @{ $self->{_queue} }, $cb; 1337 push @{ $self->{_queue} }, $cb;
1178 $self->_drain_rbuf; 1338 $self->_drain_rbuf;
1187 1347
1188 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read") 1348 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
1189 ->($self, $cb, @_); 1349 ->($self, $cb, @_);
1190 } 1350 }
1191 1351
1192
1193 unshift @{ $self->{_queue} }, $cb; 1352 unshift @{ $self->{_queue} }, $cb;
1194 $self->_drain_rbuf; 1353 $self->_drain_rbuf;
1195} 1354}
1196 1355
1197=item $handle->push_read (type => @args, $cb) 1356=item $handle->push_read (type => @args, $cb)
1198 1357
1199=item $handle->unshift_read (type => @args, $cb) 1358=item $handle->unshift_read (type => @args, $cb)
1200 1359
1201Instead of providing a callback that parses the data itself you can chose 1360Instead of providing a callback that parses the data itself you can chose
1202between a number of predefined parsing formats, for chunks of data, lines 1361between a number of predefined parsing formats, for chunks of data, lines
1203etc. 1362etc. You can also specify the (fully qualified) name of a package, in
1363which case AnyEvent tries to load the package and then expects to find the
1364C<anyevent_read_type> function inside (see "custom read types", below).
1204 1365
1205Predefined types are (if you have ideas for additional types, feel free to 1366Predefined types are (if you have ideas for additional types, feel free to
1206drop by and tell us): 1367drop by and tell us):
1207 1368
1208=over 4 1369=over 4
1448=cut 1609=cut
1449 1610
1450register_read_type json => sub { 1611register_read_type json => sub {
1451 my ($self, $cb) = @_; 1612 my ($self, $cb) = @_;
1452 1613
1453 my $json = $self->{json} ||= 1614 my $json = $self->{json} ||= json_coder;
1454 eval { require JSON::XS; JSON::XS->new->utf8 }
1455 || do { require JSON; JSON->new->utf8 };
1456 1615
1457 my $data; 1616 my $data;
1458 my $rbuf = \$self->{rbuf}; 1617 my $rbuf = \$self->{rbuf};
1459 1618
1460 sub { 1619 sub {
1529 } 1688 }
1530}; 1689};
1531 1690
1532=back 1691=back
1533 1692
1534=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1693=item custom read types - Package::anyevent_read_type $handle, $cb, @args
1535 1694
1536This function (not method) lets you add your own types to C<push_read>. 1695Instead of one of the predefined types, you can also specify the name
1696of a package. AnyEvent will try to load the package and then expects to
1697find a function named C<anyevent_read_type> inside. If it isn't found, it
1698progressively tries to load the parent package until it either finds the
1699function (good) or runs out of packages (bad).
1537 1700
1538Whenever the given C<type> is used, C<push_read> will invoke the code 1701Whenever this type is used, C<push_read> will invoke the function with the
1539reference with the handle object, the callback and the remaining 1702handle object, the original callback and the remaining arguments.
1540arguments.
1541 1703
1542The code reference is supposed to return a callback (usually a closure) 1704The function is supposed to return a callback (usually a closure) that
1543that works as a plain read callback (see C<< ->push_read ($cb) >>). 1705works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
1706mentally treat the function as a "configurable read type to read callback"
1707converter.
1544 1708
1545It should invoke the passed callback when it is done reading (remember to 1709It should invoke the original callback when it is done reading (remember
1546pass C<$handle> as first argument as all other callbacks do that). 1710to pass C<$handle> as first argument as all other callbacks do that,
1711although there is no strict requirement on this).
1547 1712
1548Note that this is a function, and all types registered this way will be
1549global, so try to use unique names.
1550
1551For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, 1713For examples, see the source of this module (F<perldoc -m
1552search for C<register_read_type>)). 1714AnyEvent::Handle>, search for C<register_read_type>)).
1553 1715
1554=item $handle->stop_read 1716=item $handle->stop_read
1555 1717
1556=item $handle->start_read 1718=item $handle->start_read
1557 1719
1577} 1739}
1578 1740
1579sub start_read { 1741sub start_read {
1580 my ($self) = @_; 1742 my ($self) = @_;
1581 1743
1582 unless ($self->{_rw} || $self->{_eof}) { 1744 unless ($self->{_rw} || $self->{_eof} || !$self->{fh}) {
1583 Scalar::Util::weaken $self; 1745 Scalar::Util::weaken $self;
1584 1746
1585 $self->{_rw} = AE::io $self->{fh}, 0, sub { 1747 $self->{_rw} = AE::io $self->{fh}, 0, sub {
1586 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf}); 1748 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1587 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1749 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
1680 && ($tmp != $ERROR_SYSCALL || $!); 1842 && ($tmp != $ERROR_SYSCALL || $!);
1681 1843
1682 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) { 1844 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1683 $self->{wbuf} .= $tmp; 1845 $self->{wbuf} .= $tmp;
1684 $self->_drain_wbuf; 1846 $self->_drain_wbuf;
1847 $self->{tls} or return; # tls session might have gone away in callback
1685 } 1848 }
1686 1849
1687 $self->{_on_starttls} 1850 $self->{_on_starttls}
1688 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK () 1851 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
1689 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established"); 1852 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
1714 1877
1715Due to bugs in OpenSSL, it might or might not be possible to do multiple 1878Due to bugs in OpenSSL, it might or might not be possible to do multiple
1716handshakes on the same stream. Best do not attempt to use the stream after 1879handshakes on the same stream. Best do not attempt to use the stream after
1717stopping TLS. 1880stopping TLS.
1718 1881
1882This method may invoke callbacks (and therefore the handle might be
1883destroyed after it returns).
1884
1719=cut 1885=cut
1720 1886
1721our %TLS_CACHE; #TODO not yet documented, should we? 1887our %TLS_CACHE; #TODO not yet documented, should we?
1722 1888
1723sub starttls { 1889sub starttls {
1734 require Net::SSLeay; 1900 require Net::SSLeay;
1735 1901
1736 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL (); 1902 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL ();
1737 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ (); 1903 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ ();
1738 1904
1739 $tls = $self->{tls}; 1905 $tls = delete $self->{tls};
1740 $ctx = $self->{tls_ctx}; 1906 $ctx = $self->{tls_ctx};
1741 1907
1742 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session 1908 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session
1743 1909
1744 if ("HASH" eq ref $ctx) { 1910 if ("HASH" eq ref $ctx) {
1788 1954
1789=item $handle->stoptls 1955=item $handle->stoptls
1790 1956
1791Shuts down the SSL connection - this makes a proper EOF handshake by 1957Shuts down the SSL connection - this makes a proper EOF handshake by
1792sending a close notify to the other side, but since OpenSSL doesn't 1958sending a close notify to the other side, but since OpenSSL doesn't
1793support non-blocking shut downs, it is not guarenteed that you can re-use 1959support non-blocking shut downs, it is not guaranteed that you can re-use
1794the stream afterwards. 1960the stream afterwards.
1961
1962This method may invoke callbacks (and therefore the handle might be
1963destroyed after it returns).
1795 1964
1796=cut 1965=cut
1797 1966
1798sub stoptls { 1967sub stoptls {
1799 my ($self) = @_; 1968 my ($self) = @_;
1800 1969
1801 if ($self->{tls}) { 1970 if ($self->{tls} && $self->{fh}) {
1802 Net::SSLeay::shutdown ($self->{tls}); 1971 Net::SSLeay::shutdown ($self->{tls});
1803 1972
1804 &_dotls; 1973 &_dotls;
1805 1974
1806# # we don't give a shit. no, we do, but we can't. no...#d# 1975# # we don't give a shit. no, we do, but we can't. no...#d#
1883 2052
1884sub AnyEvent::Handle::destroyed::AUTOLOAD { 2053sub AnyEvent::Handle::destroyed::AUTOLOAD {
1885 #nop 2054 #nop
1886} 2055}
1887 2056
2057=item $handle->destroyed
2058
2059Returns false as long as the handle hasn't been destroyed by a call to C<<
2060->destroy >>, true otherwise.
2061
2062Can be useful to decide whether the handle is still valid after some
2063callback possibly destroyed the handle. For example, C<< ->push_write >>,
2064C<< ->starttls >> and other methods can call user callbacks, which in turn
2065can destroy the handle, so work can be avoided by checking sometimes:
2066
2067 $hdl->starttls ("accept");
2068 return if $hdl->destroyed;
2069 $hdl->push_write (...
2070
2071Note that the call to C<push_write> will silently be ignored if the handle
2072has been destroyed, so often you can just ignore the possibility of the
2073handle being destroyed.
2074
2075=cut
2076
2077sub destroyed { 0 }
2078sub AnyEvent::Handle::destroyed::destroyed { 1 }
2079
1888=item AnyEvent::Handle::TLS_CTX 2080=item AnyEvent::Handle::TLS_CTX
1889 2081
1890This function creates and returns the AnyEvent::TLS object used by default 2082This function creates and returns the AnyEvent::TLS object used by default
1891for TLS mode. 2083for TLS mode.
1892 2084

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines