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.56 by root, Wed Jun 4 09:55:16 2008 UTC vs.
Revision 1.69 by root, Sun Jun 15 21:44:56 2008 UTC

14 14
15AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent 15AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
16 16
17=cut 17=cut
18 18
19our $VERSION = 4.12; 19our $VERSION = 4.151;
20 20
21=head1 SYNOPSIS 21=head1 SYNOPSIS
22 22
23 use AnyEvent; 23 use AnyEvent;
24 use AnyEvent::Handle; 24 use AnyEvent::Handle;
105C<croak>. 105C<croak>.
106 106
107=item on_read => $cb->($handle) 107=item on_read => $cb->($handle)
108 108
109This sets the default read callback, which is called when data arrives 109This sets the default read callback, which is called when data arrives
110and no read request is in the queue. 110and no read request is in the queue (unlike read queue callbacks, this
111callback will only be called when at least one octet of data is in the
112read buffer).
111 113
112To access (and remove data from) the read buffer, use the C<< ->rbuf >> 114To access (and remove data from) the read buffer, use the C<< ->rbuf >>
113method or access the C<$handle->{rbuf}> member directly. 115method or access the C<$handle->{rbuf}> member directly.
114 116
115When an EOF condition is detected then AnyEvent::Handle will first try to 117When an EOF condition is detected then AnyEvent::Handle will first try to
121 123
122This sets the callback that is called when the write buffer becomes empty 124This sets the callback that is called when the write buffer becomes empty
123(or when the callback is set and the buffer is empty already). 125(or when the callback is set and the buffer is empty already).
124 126
125To append to the write buffer, use the C<< ->push_write >> method. 127To append to the write buffer, use the C<< ->push_write >> method.
128
129This callback is useful when you don't want to put all of your write data
130into the queue at once, for example, when you want to write the contents
131of some file to the socket you might not want to read the whole file into
132memory and push it into the queue, but instead only read more data from
133the file when the write queue becomes empty.
126 134
127=item timeout => $fractional_seconds 135=item timeout => $fractional_seconds
128 136
129If non-zero, then this enables an "inactivity" timeout: whenever this many 137If non-zero, then this enables an "inactivity" timeout: whenever this many
130seconds pass without a successful read or write on the underlying file 138seconds pass without a successful read or write on the underlying file
165 173
166Sets the amount of bytes (default: C<0>) that make up an "empty" write 174Sets the amount of bytes (default: C<0>) that make up an "empty" write
167buffer: If the write reaches this size or gets even samller it is 175buffer: If the write reaches this size or gets even samller it is
168considered empty. 176considered empty.
169 177
178=item linger => <seconds>
179
180If non-zero (default: C<3600>), then the destructor of the
181AnyEvent::Handle object will check wether there is still outstanding write
182data and will install a watcher that will write out this data. No errors
183will be reported (this mostly matches how the operating system treats
184outstanding data at socket close time).
185
186This will not work for partial TLS data that could not yet been
187encoded. This data will be lost.
188
170=item tls => "accept" | "connect" | Net::SSLeay::SSL object 189=item tls => "accept" | "connect" | Net::SSLeay::SSL object
171 190
172When this parameter is given, it enables TLS (SSL) mode, that means it 191When this parameter is given, it enables TLS (SSL) mode, that means it
173will start making tls handshake and will transparently encrypt/decrypt 192will start making tls handshake and will transparently encrypt/decrypt
174data. 193data.
224 if ($self->{tls}) { 243 if ($self->{tls}) {
225 require Net::SSLeay; 244 require Net::SSLeay;
226 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}); 245 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
227 } 246 }
228 247
229# $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof}; # nop
230# $self->on_error (delete $self->{on_error}) if $self->{on_error}; # nop
231# $self->on_read (delete $self->{on_read} ) if $self->{on_read}; # nop
232 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
233
234 $self->{_activity} = AnyEvent->now; 248 $self->{_activity} = AnyEvent->now;
235 $self->_timeout; 249 $self->_timeout;
236 250
251 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
252
237 $self->start_read; 253 $self->start_read
254 if $self->{on_read};
238 255
239 $self 256 $self
240} 257}
241 258
242sub _shutdown { 259sub _shutdown {
480 my ($self, $string) = @_; 497 my ($self, $string) = @_;
481 498
482 sprintf "%d:%s,", (length $string), $string 499 sprintf "%d:%s,", (length $string), $string
483}; 500};
484 501
502=item packstring => $format, $data
503
504An octet string prefixed with an encoded length. The encoding C<$format>
505uses the same format as a Perl C<pack> format, but must specify a single
506integer only (only one of C<cCsSlLqQiInNvVjJw> is allowed, plus an
507optional C<!>, C<< < >> or C<< > >> modifier).
508
509=cut
510
511register_write_type packstring => sub {
512 my ($self, $format, $string) = @_;
513
514 pack "$format/a*", $string
515};
516
485=item json => $array_or_hashref 517=item json => $array_or_hashref
486 518
487Encodes the given hash or array reference into a JSON object. Unless you 519Encodes the given hash or array reference into a JSON object. Unless you
488provide your own JSON object, this means it will be encoded to JSON text 520provide your own JSON object, this means it will be encoded to JSON text
489in UTF-8. 521in UTF-8.
521 553
522 $self->{json} ? $self->{json}->encode ($ref) 554 $self->{json} ? $self->{json}->encode ($ref)
523 : JSON::encode_json ($ref) 555 : JSON::encode_json ($ref)
524}; 556};
525 557
558=item storable => $reference
559
560Freezes the given reference using L<Storable> and writes it to the
561handle. Uses the C<nfreeze> format.
562
563=cut
564
565register_write_type storable => sub {
566 my ($self, $ref) = @_;
567
568 require Storable;
569
570 pack "w/a*", Storable::nfreeze ($ref)
571};
572
526=back 573=back
527 574
528=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 575=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args)
529 576
530This function (not method) lets you add your own types to C<push_write>. 577This function (not method) lets you add your own types to C<push_write>.
552ways, the "simple" way, using only C<on_read> and the "complex" way, using 599ways, the "simple" way, using only C<on_read> and the "complex" way, using
553a queue. 600a queue.
554 601
555In the simple case, you just install an C<on_read> callback and whenever 602In the simple case, you just install an C<on_read> callback and whenever
556new data arrives, it will be called. You can then remove some data (if 603new data arrives, it will be called. You can then remove some data (if
557enough is there) from the read buffer (C<< $handle->rbuf >>) if you want 604enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna
558or not. 605leave the data there if you want to accumulate more (e.g. when only a
606partial message has been received so far).
559 607
560In the more complex case, you want to queue multiple callbacks. In this 608In the more complex case, you want to queue multiple callbacks. In this
561case, AnyEvent::Handle will call the first queued callback each time new 609case, AnyEvent::Handle will call the first queued callback each time new
562data arrives and removes it when it has done its job (see C<push_read>, 610data arrives (also the first time it is queued) and removes it when it has
563below). 611done its job (see C<push_read>, below).
564 612
565This way you can, for example, push three line-reads, followed by reading 613This way you can, for example, push three line-reads, followed by reading
566a chunk of data, and AnyEvent::Handle will execute them in order. 614a chunk of data, and AnyEvent::Handle will execute them in order.
567 615
568Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by 616Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
581 # handle xml 629 # handle xml
582 }); 630 });
583 }); 631 });
584 }); 632 });
585 633
586Example 2: Implement a client for a protocol that replies either with 634Example 2: Implement a client for a protocol that replies either with "OK"
587"OK" and another line or "ERROR" for one request, and 64 bytes for the 635and another line or "ERROR" for the first request that is sent, and 64
588second request. Due tot he availability of a full queue, we can just 636bytes for the second request. Due to the availability of a queue, we can
589pipeline sending both requests and manipulate the queue as necessary in 637just pipeline sending both requests and manipulate the queue as necessary
590the callbacks: 638in the callbacks.
591 639
592 # request one 640When the first callback is called and sees an "OK" response, it will
641C<unshift> another line-read. This line-read will be queued I<before> the
64264-byte chunk callback.
643
644 # request one, returns either "OK + extra line" or "ERROR"
593 $handle->push_write ("request 1\015\012"); 645 $handle->push_write ("request 1\015\012");
594 646
595 # we expect "ERROR" or "OK" as response, so push a line read 647 # we expect "ERROR" or "OK" as response, so push a line read
596 $handle->push_read (line => sub { 648 $handle->push_read (line => sub {
597 # if we got an "OK", we have to _prepend_ another line, 649 # if we got an "OK", we have to _prepend_ another line,
604 ... 656 ...
605 }); 657 });
606 } 658 }
607 }); 659 });
608 660
609 # request two 661 # request two, simply returns 64 octets
610 $handle->push_write ("request 2\015\012"); 662 $handle->push_write ("request 2\015\012");
611 663
612 # simply read 64 bytes, always 664 # simply read 64 bytes, always
613 $handle->push_read (chunk => 64, sub { 665 $handle->push_read (chunk => 64, sub {
614 my $response = $_[1]; 666 my $response = $_[1];
620=cut 672=cut
621 673
622sub _drain_rbuf { 674sub _drain_rbuf {
623 my ($self) = @_; 675 my ($self) = @_;
624 676
677 local $self->{_in_drain} = 1;
678
625 if ( 679 if (
626 defined $self->{rbuf_max} 680 defined $self->{rbuf_max}
627 && $self->{rbuf_max} < length $self->{rbuf} 681 && $self->{rbuf_max} < length $self->{rbuf}
628 ) { 682 ) {
629 return $self->_error (&Errno::ENOSPC, 1); 683 return $self->_error (&Errno::ENOSPC, 1);
630 } 684 }
631 685
632 return if $self->{in_drain}; 686 while () {
633 local $self->{in_drain} = 1;
634
635 while (my $len = length $self->{rbuf}) {
636 no strict 'refs'; 687 no strict 'refs';
688
689 my $len = length $self->{rbuf};
690
637 if (my $cb = shift @{ $self->{_queue} }) { 691 if (my $cb = shift @{ $self->{_queue} }) {
638 unless ($cb->($self)) { 692 unless ($cb->($self)) {
639 if ($self->{_eof}) { 693 if ($self->{_eof}) {
640 # no progress can be made (not enough data and no data forthcoming) 694 # no progress can be made (not enough data and no data forthcoming)
641 return $self->_error (&Errno::EPIPE, 1); 695 $self->_error (&Errno::EPIPE, 1), last;
642 } 696 }
643 697
644 unshift @{ $self->{_queue} }, $cb; 698 unshift @{ $self->{_queue} }, $cb;
645 last; 699 last;
646 } 700 }
647 } elsif ($self->{on_read}) { 701 } elsif ($self->{on_read}) {
702 last unless $len;
703
648 $self->{on_read}($self); 704 $self->{on_read}($self);
649 705
650 if ( 706 if (
651 $len == length $self->{rbuf} # if no data has been consumed 707 $len == length $self->{rbuf} # if no data has been consumed
652 && !@{ $self->{_queue} } # and the queue is still empty 708 && !@{ $self->{_queue} } # and the queue is still empty
653 && $self->{on_read} # but we still have on_read 709 && $self->{on_read} # but we still have on_read
654 ) { 710 ) {
655 # no further data will arrive 711 # no further data will arrive
656 # so no progress can be made 712 # so no progress can be made
657 return $self->_error (&Errno::EPIPE, 1) 713 $self->_error (&Errno::EPIPE, 1), last
658 if $self->{_eof}; 714 if $self->{_eof};
659 715
660 last; # more data might arrive 716 last; # more data might arrive
661 } 717 }
662 } else { 718 } else {
686 742
687sub on_read { 743sub on_read {
688 my ($self, $cb) = @_; 744 my ($self, $cb) = @_;
689 745
690 $self->{on_read} = $cb; 746 $self->{on_read} = $cb;
747 $self->_drain_rbuf if $cb && !$self->{_in_drain};
691} 748}
692 749
693=item $handle->rbuf 750=item $handle->rbuf
694 751
695Returns the read buffer (as a modifiable lvalue). 752Returns the read buffer (as a modifiable lvalue).
744 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 801 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read")
745 ->($self, $cb, @_); 802 ->($self, $cb, @_);
746 } 803 }
747 804
748 push @{ $self->{_queue} }, $cb; 805 push @{ $self->{_queue} }, $cb;
749 $self->_drain_rbuf; 806 $self->_drain_rbuf unless $self->{_in_drain};
750} 807}
751 808
752sub unshift_read { 809sub unshift_read {
753 my $self = shift; 810 my $self = shift;
754 my $cb = pop; 811 my $cb = pop;
760 ->($self, $cb, @_); 817 ->($self, $cb, @_);
761 } 818 }
762 819
763 820
764 unshift @{ $self->{_queue} }, $cb; 821 unshift @{ $self->{_queue} }, $cb;
765 $self->_drain_rbuf; 822 $self->_drain_rbuf unless $self->{_in_drain};
766} 823}
767 824
768=item $handle->push_read (type => @args, $cb) 825=item $handle->push_read (type => @args, $cb)
769 826
770=item $handle->unshift_read (type => @args, $cb) 827=item $handle->unshift_read (type => @args, $cb)
855 912
856sub unshift_read_line { 913sub unshift_read_line {
857 my $self = shift; 914 my $self = shift;
858 $self->unshift_read (line => @_); 915 $self->unshift_read (line => @_);
859} 916}
860
861=item netstring => $cb->($handle, $string)
862
863A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
864
865Throws an error with C<$!> set to EBADMSG on format violations.
866
867=cut
868
869register_read_type netstring => sub {
870 my ($self, $cb) = @_;
871
872 sub {
873 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
874 if ($_[0]{rbuf} =~ /[^0-9]/) {
875 $self->_error (&Errno::EBADMSG);
876 }
877 return;
878 }
879
880 my $len = $1;
881
882 $self->unshift_read (chunk => $len, sub {
883 my $string = $_[1];
884 $_[0]->unshift_read (chunk => 1, sub {
885 if ($_[1] eq ",") {
886 $cb->($_[0], $string);
887 } else {
888 $self->_error (&Errno::EBADMSG);
889 }
890 });
891 });
892
893 1
894 }
895};
896 917
897=item regex => $accept[, $reject[, $skip], $cb->($handle, $data) 918=item regex => $accept[, $reject[, $skip], $cb->($handle, $data)
898 919
899Makes a regex match against the regex object C<$accept> and returns 920Makes a regex match against the regex object C<$accept> and returns
900everything up to and including the match. 921everything up to and including the match.
962 983
963 () 984 ()
964 } 985 }
965}; 986};
966 987
988=item netstring => $cb->($handle, $string)
989
990A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
991
992Throws an error with C<$!> set to EBADMSG on format violations.
993
994=cut
995
996register_read_type netstring => sub {
997 my ($self, $cb) = @_;
998
999 sub {
1000 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
1001 if ($_[0]{rbuf} =~ /[^0-9]/) {
1002 $self->_error (&Errno::EBADMSG);
1003 }
1004 return;
1005 }
1006
1007 my $len = $1;
1008
1009 $self->unshift_read (chunk => $len, sub {
1010 my $string = $_[1];
1011 $_[0]->unshift_read (chunk => 1, sub {
1012 if ($_[1] eq ",") {
1013 $cb->($_[0], $string);
1014 } else {
1015 $self->_error (&Errno::EBADMSG);
1016 }
1017 });
1018 });
1019
1020 1
1021 }
1022};
1023
1024=item packstring => $format, $cb->($handle, $string)
1025
1026An octet string prefixed with an encoded length. The encoding C<$format>
1027uses the same format as a Perl C<pack> format, but must specify a single
1028integer only (only one of C<cCsSlLqQiInNvVjJw> is allowed, plus an
1029optional C<!>, C<< < >> or C<< > >> modifier).
1030
1031DNS over TCP uses a prefix of C<n>, EPP uses a prefix of C<N>.
1032
1033Example: read a block of data prefixed by its length in BER-encoded
1034format (very efficient).
1035
1036 $handle->push_read (packstring => "w", sub {
1037 my ($handle, $data) = @_;
1038 });
1039
1040=cut
1041
1042register_read_type packstring => sub {
1043 my ($self, $cb, $format) = @_;
1044
1045 sub {
1046 # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method
1047 defined (my $len = eval { unpack $format, $_[0]->{rbuf} })
1048 or return;
1049
1050 # remove prefix
1051 substr $_[0]->{rbuf}, 0, (length pack $format, $len), "";
1052
1053 # read rest
1054 $_[0]->unshift_read (chunk => $len, $cb);
1055
1056 1
1057 }
1058};
1059
967=item json => $cb->($handle, $hash_or_arrayref) 1060=item json => $cb->($handle, $hash_or_arrayref)
968 1061
969Reads a JSON object or array, decodes it and passes it to the callback. 1062Reads a JSON object or array, decodes it and passes it to the callback.
970 1063
971If a C<json> object was passed to the constructor, then that will be used 1064If a C<json> object was passed to the constructor, then that will be used
981the C<json> write type description, above, for an actual example. 1074the C<json> write type description, above, for an actual example.
982 1075
983=cut 1076=cut
984 1077
985register_read_type json => sub { 1078register_read_type json => sub {
986 my ($self, $cb, $accept, $reject, $skip) = @_; 1079 my ($self, $cb) = @_;
987 1080
988 require JSON; 1081 require JSON;
989 1082
990 my $data; 1083 my $data;
991 my $rbuf = \$self->{rbuf}; 1084 my $rbuf = \$self->{rbuf};
1006 () 1099 ()
1007 } 1100 }
1008 } 1101 }
1009}; 1102};
1010 1103
1104=item storable => $cb->($handle, $ref)
1105
1106Deserialises a L<Storable> frozen representation as written by the
1107C<storable> write type (BER-encoded length prefix followed by nfreeze'd
1108data).
1109
1110Raises C<EBADMSG> error if the data could not be decoded.
1111
1112=cut
1113
1114register_read_type storable => sub {
1115 my ($self, $cb) = @_;
1116
1117 require Storable;
1118
1119 sub {
1120 # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method
1121 defined (my $len = eval { unpack "w", $_[0]->{rbuf} })
1122 or return;
1123
1124 # remove prefix
1125 substr $_[0]->{rbuf}, 0, (length pack "w", $len), "";
1126
1127 # read rest
1128 $_[0]->unshift_read (chunk => $len, sub {
1129 if (my $ref = eval { Storable::thaw ($_[1]) }) {
1130 $cb->($_[0], $ref);
1131 } else {
1132 $self->_error (&Errno::EBADMSG);
1133 }
1134 });
1135 }
1136};
1137
1011=back 1138=back
1012 1139
1013=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1140=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args)
1014 1141
1015This function (not method) lets you add your own types to C<push_read>. 1142This function (not method) lets you add your own types to C<push_read>.
1033=item $handle->stop_read 1160=item $handle->stop_read
1034 1161
1035=item $handle->start_read 1162=item $handle->start_read
1036 1163
1037In rare cases you actually do not want to read anything from the 1164In rare cases you actually do not want to read anything from the
1038socket. In this case you can call C<stop_read>. Neither C<on_read> no 1165socket. In this case you can call C<stop_read>. Neither C<on_read> nor
1039any queued callbacks will be executed then. To start reading again, call 1166any queued callbacks will be executed then. To start reading again, call
1040C<start_read>. 1167C<start_read>.
1041 1168
1042Note that AnyEvent::Handle will automatically C<start_read> for you when 1169Note that AnyEvent::Handle will automatically C<start_read> for you when
1043you change the C<on_read> callback or push/unshift a read callback, and it 1170you change the C<on_read> callback or push/unshift a read callback, and it
1065 if ($len > 0) { 1192 if ($len > 0) {
1066 $self->{_activity} = AnyEvent->now; 1193 $self->{_activity} = AnyEvent->now;
1067 1194
1068 $self->{filter_r} 1195 $self->{filter_r}
1069 ? $self->{filter_r}($self, $rbuf) 1196 ? $self->{filter_r}($self, $rbuf)
1070 : $self->_drain_rbuf; 1197 : $self->{_in_drain} || $self->_drain_rbuf;
1071 1198
1072 } elsif (defined $len) { 1199 } elsif (defined $len) {
1073 delete $self->{_rw}; 1200 delete $self->{_rw};
1074 $self->{_eof} = 1; 1201 $self->{_eof} = 1;
1075 $self->_drain_rbuf; 1202 $self->_drain_rbuf unless $self->{_in_drain};
1076 1203
1077 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) { 1204 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
1078 return $self->_error ($!, 1); 1205 return $self->_error ($!, 1);
1079 } 1206 }
1080 }); 1207 });
1098 } 1225 }
1099 1226
1100 while (defined ($buf = Net::SSLeay::read ($self->{tls}))) { 1227 while (defined ($buf = Net::SSLeay::read ($self->{tls}))) {
1101 if (length $buf) { 1228 if (length $buf) {
1102 $self->{rbuf} .= $buf; 1229 $self->{rbuf} .= $buf;
1103 $self->_drain_rbuf; 1230 $self->_drain_rbuf unless $self->{_in_drain};
1104 } else { 1231 } else {
1105 # let's treat SSL-eof as we treat normal EOF 1232 # let's treat SSL-eof as we treat normal EOF
1106 $self->{_eof} = 1; 1233 $self->{_eof} = 1;
1107 $self->_shutdown; 1234 $self->_shutdown;
1108 return; 1235 return;
1200 1327
1201sub DESTROY { 1328sub DESTROY {
1202 my $self = shift; 1329 my $self = shift;
1203 1330
1204 $self->stoptls; 1331 $self->stoptls;
1332
1333 my $linger = exists $self->{linger} ? $self->{linger} : 3600;
1334
1335 if ($linger && length $self->{wbuf}) {
1336 my $fh = delete $self->{fh};
1337 my $wbuf = delete $self->{wbuf};
1338
1339 my @linger;
1340
1341 push @linger, AnyEvent->io (fh => $fh, poll => "w", cb => sub {
1342 my $len = syswrite $fh, $wbuf, length $wbuf;
1343
1344 if ($len > 0) {
1345 substr $wbuf, 0, $len, "";
1346 } else {
1347 @linger = (); # end
1348 }
1349 });
1350 push @linger, AnyEvent->timer (after => $linger, cb => sub {
1351 @linger = ();
1352 });
1353 }
1205} 1354}
1206 1355
1207=item AnyEvent::Handle::TLS_CTX 1356=item AnyEvent::Handle::TLS_CTX
1208 1357
1209This function creates and returns the Net::SSLeay::CTX object used by 1358This function creates and returns the Net::SSLeay::CTX object used by

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines