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.45 by root, Thu May 29 00:20:39 2008 UTC vs.
Revision 1.80 by root, Sun Jul 27 08:43:32 2008 UTC

1package AnyEvent::Handle; 1package AnyEvent::Handle;
2 2
3no warnings; 3no warnings;
4use strict; 4use strict qw(subs vars);
5 5
6use AnyEvent (); 6use AnyEvent ();
7use AnyEvent::Util qw(WSAEWOULDBLOCK); 7use AnyEvent::Util qw(WSAEWOULDBLOCK);
8use Scalar::Util (); 8use Scalar::Util ();
9use Carp (); 9use Carp ();
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 = '0.04'; 19our $VERSION = 4.22;
20 20
21=head1 SYNOPSIS 21=head1 SYNOPSIS
22 22
23 use AnyEvent; 23 use AnyEvent;
24 use AnyEvent::Handle; 24 use AnyEvent::Handle;
75NOTE: The filehandle will be set to non-blocking (using 75NOTE: The filehandle will be set to non-blocking (using
76AnyEvent::Util::fh_nonblocking). 76AnyEvent::Util::fh_nonblocking).
77 77
78=item on_eof => $cb->($handle) 78=item on_eof => $cb->($handle)
79 79
80Set the callback to be called on EOF. 80Set the callback to be called when an end-of-file condition is detected,
81i.e. in the case of a socket, when the other side has closed the
82connection cleanly.
81 83
82While not mandatory, it is highly recommended to set an eof callback, 84While not mandatory, it is I<highly> recommended to set an eof callback,
83otherwise you might end up with a closed socket while you are still 85otherwise you might end up with a closed socket while you are still
84waiting for data. 86waiting for data.
85 87
88If an EOF condition has been detected but no C<on_eof> callback has been
89set, then a fatal error will be raised with C<$!> set to <0>.
90
86=item on_error => $cb->($handle) 91=item on_error => $cb->($handle, $fatal)
87 92
88This is the fatal error callback, that is called when, well, a fatal error 93This is the error callback, which is called when, well, some error
89occurs, such as not being able to resolve the hostname, failure to connect 94occured, such as not being able to resolve the hostname, failure to
90or a read error. 95connect or a read error.
91 96
92The object will not be in a usable state when this callback has been 97Some errors are fatal (which is indicated by C<$fatal> being true). On
93called. 98fatal errors the handle object will be shut down and will not be
99usable. Non-fatal errors can be retried by simply returning, but it is
100recommended to simply ignore this parameter and instead abondon the handle
101object when this callback is invoked.
94 102
95On callback entrance, the value of C<$!> contains the operating system 103On callback entrance, the value of C<$!> contains the operating system
96error (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT> or C<EBADMSG>). 104error (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT> or C<EBADMSG>).
97 105
98The callback should throw an exception. If it returns, then
99AnyEvent::Handle will C<croak> for you.
100
101While not mandatory, it is I<highly> recommended to set this callback, as 106While not mandatory, it is I<highly> recommended to set this callback, as
102you will not be notified of errors otherwise. The default simply calls 107you will not be notified of errors otherwise. The default simply calls
103die. 108C<croak>.
104 109
105=item on_read => $cb->($handle) 110=item on_read => $cb->($handle)
106 111
107This sets the default read callback, which is called when data arrives 112This sets the default read callback, which is called when data arrives
108and no read request is in the queue. 113and no read request is in the queue (unlike read queue callbacks, this
114callback will only be called when at least one octet of data is in the
115read buffer).
109 116
110To access (and remove data from) the read buffer, use the C<< ->rbuf >> 117To access (and remove data from) the read buffer, use the C<< ->rbuf >>
111method or access the C<$handle->{rbuf}> member directly. 118method or access the C<$handle->{rbuf}> member directly.
112 119
113When an EOF condition is detected then AnyEvent::Handle will first try to 120When an EOF condition is detected then AnyEvent::Handle will first try to
119 126
120This sets the callback that is called when the write buffer becomes empty 127This sets the callback that is called when the write buffer becomes empty
121(or when the callback is set and the buffer is empty already). 128(or when the callback is set and the buffer is empty already).
122 129
123To append to the write buffer, use the C<< ->push_write >> method. 130To append to the write buffer, use the C<< ->push_write >> method.
131
132This callback is useful when you don't want to put all of your write data
133into the queue at once, for example, when you want to write the contents
134of some file to the socket you might not want to read the whole file into
135memory and push it into the queue, but instead only read more data from
136the file when the write queue becomes empty.
124 137
125=item timeout => $fractional_seconds 138=item timeout => $fractional_seconds
126 139
127If non-zero, then this enables an "inactivity" timeout: whenever this many 140If non-zero, then this enables an "inactivity" timeout: whenever this many
128seconds pass without a successful read or write on the underlying file 141seconds pass without a successful read or write on the underlying file
152be configured to accept only so-and-so much data that it cannot act on 165be configured to accept only so-and-so much data that it cannot act on
153(for example, when expecting a line, an attacker could send an unlimited 166(for example, when expecting a line, an attacker could send an unlimited
154amount of data without a callback ever being called as long as the line 167amount of data without a callback ever being called as long as the line
155isn't finished). 168isn't finished).
156 169
170=item autocork => <boolean>
171
172When disabled (the default), then C<push_write> will try to immediately
173write the data to the handle if possible. This avoids having to register
174a write watcher and wait for the next event loop iteration, but can be
175inefficient if you write multiple small chunks (this disadvantage is
176usually avoided by your kernel's nagle algorithm, see C<low_delay>).
177
178When enabled, then writes will always be queued till the next event loop
179iteration. This is efficient when you do many small writes per iteration,
180but less efficient when you do a single write only.
181
182=item no_delay => <boolean>
183
184When doing small writes on sockets, your operating system kernel might
185wait a bit for more data before actually sending it out. This is called
186the Nagle algorithm, and usually it is beneficial.
187
188In some situations you want as low a delay as possible, which cna be
189accomplishd by setting this option to true.
190
191The default is your opertaing system's default behaviour, this option
192explicitly enables or disables it, if possible.
193
157=item read_size => <bytes> 194=item read_size => <bytes>
158 195
159The default read block size (the amount of bytes this module will try to read 196The default read block size (the amount of bytes this module will try to read
160on each [loop iteration). Default: C<4096>. 197during each (loop iteration). Default: C<8192>.
161 198
162=item low_water_mark => <bytes> 199=item low_water_mark => <bytes>
163 200
164Sets the amount of bytes (default: C<0>) that make up an "empty" write 201Sets the amount of bytes (default: C<0>) that make up an "empty" write
165buffer: If the write reaches this size or gets even samller it is 202buffer: If the write reaches this size or gets even samller it is
166considered empty. 203considered empty.
204
205=item linger => <seconds>
206
207If non-zero (default: C<3600>), then the destructor of the
208AnyEvent::Handle object will check wether there is still outstanding write
209data and will install a watcher that will write out this data. No errors
210will be reported (this mostly matches how the operating system treats
211outstanding data at socket close time).
212
213This will not work for partial TLS data that could not yet been
214encoded. This data will be lost.
167 215
168=item tls => "accept" | "connect" | Net::SSLeay::SSL object 216=item tls => "accept" | "connect" | Net::SSLeay::SSL object
169 217
170When this parameter is given, it enables TLS (SSL) mode, that means it 218When this parameter is given, it enables TLS (SSL) mode, that means it
171will start making tls handshake and will transparently encrypt/decrypt 219will start making tls handshake and will transparently encrypt/decrypt
180You can also provide your own TLS connection object, but you have 228You can also provide your own TLS connection object, but you have
181to make sure that you call either C<Net::SSLeay::set_connect_state> 229to make sure that you call either C<Net::SSLeay::set_connect_state>
182or C<Net::SSLeay::set_accept_state> on it before you pass it to 230or C<Net::SSLeay::set_accept_state> on it before you pass it to
183AnyEvent::Handle. 231AnyEvent::Handle.
184 232
185See the C<starttls> method if you need to start TLs negotiation later. 233See the C<starttls> method if you need to start TLS negotiation later.
186 234
187=item tls_ctx => $ssl_ctx 235=item tls_ctx => $ssl_ctx
188 236
189Use the given Net::SSLeay::CTX object to create the new TLS connection 237Use the given Net::SSLeay::CTX object to create the new TLS connection
190(unless a connection object was specified directly). If this parameter is 238(unless a connection object was specified directly). If this parameter is
222 if ($self->{tls}) { 270 if ($self->{tls}) {
223 require Net::SSLeay; 271 require Net::SSLeay;
224 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}); 272 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
225 } 273 }
226 274
227# $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof}; # nop
228# $self->on_error (delete $self->{on_error}) if $self->{on_error}; # nop
229# $self->on_read (delete $self->{on_read} ) if $self->{on_read}; # nop
230 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
231
232 $self->{_activity} = AnyEvent->now; 275 $self->{_activity} = AnyEvent->now;
233 $self->_timeout; 276 $self->_timeout;
234 277
278 $self->on_drain (delete $self->{on_drain}) if exists $self->{on_drain};
279 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay};
280
235 $self->start_read; 281 $self->start_read
282 if $self->{on_read};
236 283
237 $self 284 $self
238} 285}
239 286
240sub _shutdown { 287sub _shutdown {
241 my ($self) = @_; 288 my ($self) = @_;
242 289
290 delete $self->{_tw};
243 delete $self->{_rw}; 291 delete $self->{_rw};
244 delete $self->{_ww}; 292 delete $self->{_ww};
245 delete $self->{fh}; 293 delete $self->{fh};
246}
247 294
295 $self->stoptls;
296}
297
248sub error { 298sub _error {
249 my ($self) = @_; 299 my ($self, $errno, $fatal) = @_;
250 300
251 {
252 local $!;
253 $self->_shutdown; 301 $self->_shutdown
254 } 302 if $fatal;
255 303
256 $self->{on_error}($self) 304 $! = $errno;
305
257 if $self->{on_error}; 306 if ($self->{on_error}) {
258 307 $self->{on_error}($self, $fatal);
308 } else {
259 Carp::croak "AnyEvent::Handle uncaught fatal error: $!"; 309 Carp::croak "AnyEvent::Handle uncaught error: $!";
310 }
260} 311}
261 312
262=item $fh = $handle->fh 313=item $fh = $handle->fh
263 314
264This method returns the file handle of the L<AnyEvent::Handle> object. 315This method returns the file handle of the L<AnyEvent::Handle> object.
295 346
296=cut 347=cut
297 348
298sub on_timeout { 349sub on_timeout {
299 $_[0]{on_timeout} = $_[1]; 350 $_[0]{on_timeout} = $_[1];
351}
352
353=item $handle->autocork ($boolean)
354
355Enables or disables the current autocork behaviour (see C<autocork>
356constructor argument).
357
358=cut
359
360=item $handle->no_delay ($boolean)
361
362Enables or disables the C<no_delay> setting (see constructor argument of
363the same name for details).
364
365=cut
366
367sub no_delay {
368 $_[0]{no_delay} = $_[1];
369
370 eval {
371 local $SIG{__DIE__};
372 setsockopt $_[0]{fh}, &Socket::IPPROTO_TCP, &Socket::TCP_NODELAY, int $_[1];
373 };
300} 374}
301 375
302############################################################################# 376#############################################################################
303 377
304=item $handle->timeout ($seconds) 378=item $handle->timeout ($seconds)
328 # now or in the past already? 402 # now or in the past already?
329 if ($after <= 0) { 403 if ($after <= 0) {
330 $self->{_activity} = $NOW; 404 $self->{_activity} = $NOW;
331 405
332 if ($self->{on_timeout}) { 406 if ($self->{on_timeout}) {
333 $self->{on_timeout}->($self); 407 $self->{on_timeout}($self);
334 } else { 408 } else {
335 $! = Errno::ETIMEDOUT; 409 $self->_error (&Errno::ETIMEDOUT);
336 $self->error;
337 } 410 }
338 411
339 # callbakx could have changed timeout value, optimise 412 # callback could have changed timeout value, optimise
340 return unless $self->{timeout}; 413 return unless $self->{timeout};
341 414
342 # calculate new after 415 # calculate new after
343 $after = $self->{timeout}; 416 $after = $self->{timeout};
344 } 417 }
345 418
346 Scalar::Util::weaken $self; 419 Scalar::Util::weaken $self;
420 return unless $self; # ->error could have destroyed $self
347 421
348 $self->{_tw} ||= AnyEvent->timer (after => $after, cb => sub { 422 $self->{_tw} ||= AnyEvent->timer (after => $after, cb => sub {
349 delete $self->{_tw}; 423 delete $self->{_tw};
350 $self->_timeout; 424 $self->_timeout;
351 }); 425 });
414 if $self->{low_water_mark} >= length $self->{wbuf} 488 if $self->{low_water_mark} >= length $self->{wbuf}
415 && $self->{on_drain}; 489 && $self->{on_drain};
416 490
417 delete $self->{_ww} unless length $self->{wbuf}; 491 delete $self->{_ww} unless length $self->{wbuf};
418 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) { 492 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
419 $self->error; 493 $self->_error ($!, 1);
420 } 494 }
421 }; 495 };
422 496
423 # try to write data immediately 497 # try to write data immediately
424 $cb->(); 498 $cb->() unless $self->{autocork};
425 499
426 # if still data left in wbuf, we need to poll 500 # if still data left in wbuf, we need to poll
427 $self->{_ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb) 501 $self->{_ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb)
428 if length $self->{wbuf}; 502 if length $self->{wbuf};
429 }; 503 };
444 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write") 518 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write")
445 ->($self, @_); 519 ->($self, @_);
446 } 520 }
447 521
448 if ($self->{filter_w}) { 522 if ($self->{filter_w}) {
449 $self->{filter_w}->($self, \$_[0]); 523 $self->{filter_w}($self, \$_[0]);
450 } else { 524 } else {
451 $self->{wbuf} .= $_[0]; 525 $self->{wbuf} .= $_[0];
452 $self->_drain_wbuf; 526 $self->_drain_wbuf;
453 } 527 }
454} 528}
455 529
456=item $handle->push_write (type => @args) 530=item $handle->push_write (type => @args)
457 531
458=item $handle->unshift_write (type => @args)
459
460Instead of formatting your data yourself, you can also let this module do 532Instead of formatting your data yourself, you can also let this module do
461the job by specifying a type and type-specific arguments. 533the job by specifying a type and type-specific arguments.
462 534
463Predefined types are (if you have ideas for additional types, feel free to 535Predefined types are (if you have ideas for additional types, feel free to
464drop by and tell us): 536drop by and tell us):
468=item netstring => $string 540=item netstring => $string
469 541
470Formats the given value as netstring 542Formats the given value as netstring
471(http://cr.yp.to/proto/netstrings.txt, this is not a recommendation to use them). 543(http://cr.yp.to/proto/netstrings.txt, this is not a recommendation to use them).
472 544
473=back
474
475=cut 545=cut
476 546
477register_write_type netstring => sub { 547register_write_type netstring => sub {
478 my ($self, $string) = @_; 548 my ($self, $string) = @_;
479 549
480 sprintf "%d:%s,", (length $string), $string 550 sprintf "%d:%s,", (length $string), $string
551};
552
553=item packstring => $format, $data
554
555An octet string prefixed with an encoded length. The encoding C<$format>
556uses the same format as a Perl C<pack> format, but must specify a single
557integer only (only one of C<cCsSlLqQiInNvVjJw> is allowed, plus an
558optional C<!>, C<< < >> or C<< > >> modifier).
559
560=cut
561
562register_write_type packstring => sub {
563 my ($self, $format, $string) = @_;
564
565 pack "$format/a*", $string
481}; 566};
482 567
483=item json => $array_or_hashref 568=item json => $array_or_hashref
484 569
485Encodes the given hash or array reference into a JSON object. Unless you 570Encodes the given hash or array reference into a JSON object. Unless you
519 604
520 $self->{json} ? $self->{json}->encode ($ref) 605 $self->{json} ? $self->{json}->encode ($ref)
521 : JSON::encode_json ($ref) 606 : JSON::encode_json ($ref)
522}; 607};
523 608
609=item storable => $reference
610
611Freezes the given reference using L<Storable> and writes it to the
612handle. Uses the C<nfreeze> format.
613
614=cut
615
616register_write_type storable => sub {
617 my ($self, $ref) = @_;
618
619 require Storable;
620
621 pack "w/a*", Storable::nfreeze ($ref)
622};
623
624=back
625
524=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 626=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args)
525 627
526This function (not method) lets you add your own types to C<push_write>. 628This function (not method) lets you add your own types to C<push_write>.
527Whenever the given C<type> is used, C<push_write> will invoke the code 629Whenever the given C<type> is used, C<push_write> will invoke the code
528reference with the handle object and the remaining arguments. 630reference with the handle object and the remaining arguments.
548ways, the "simple" way, using only C<on_read> and the "complex" way, using 650ways, the "simple" way, using only C<on_read> and the "complex" way, using
549a queue. 651a queue.
550 652
551In the simple case, you just install an C<on_read> callback and whenever 653In the simple case, you just install an C<on_read> callback and whenever
552new data arrives, it will be called. You can then remove some data (if 654new data arrives, it will be called. You can then remove some data (if
553enough is there) from the read buffer (C<< $handle->rbuf >>) if you want 655enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna
554or not. 656leave the data there if you want to accumulate more (e.g. when only a
657partial message has been received so far).
555 658
556In the more complex case, you want to queue multiple callbacks. In this 659In the more complex case, you want to queue multiple callbacks. In this
557case, AnyEvent::Handle will call the first queued callback each time new 660case, AnyEvent::Handle will call the first queued callback each time new
558data arrives and removes it when it has done its job (see C<push_read>, 661data arrives (also the first time it is queued) and removes it when it has
559below). 662done its job (see C<push_read>, below).
560 663
561This way you can, for example, push three line-reads, followed by reading 664This way you can, for example, push three line-reads, followed by reading
562a chunk of data, and AnyEvent::Handle will execute them in order. 665a chunk of data, and AnyEvent::Handle will execute them in order.
563 666
564Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by 667Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
565the specified number of bytes which give an XML datagram. 668the specified number of bytes which give an XML datagram.
566 669
567 # in the default state, expect some header bytes 670 # in the default state, expect some header bytes
568 $handle->on_read (sub { 671 $handle->on_read (sub {
569 # some data is here, now queue the length-header-read (4 octets) 672 # some data is here, now queue the length-header-read (4 octets)
570 shift->unshift_read_chunk (4, sub { 673 shift->unshift_read (chunk => 4, sub {
571 # header arrived, decode 674 # header arrived, decode
572 my $len = unpack "N", $_[1]; 675 my $len = unpack "N", $_[1];
573 676
574 # now read the payload 677 # now read the payload
575 shift->unshift_read_chunk ($len, sub { 678 shift->unshift_read (chunk => $len, sub {
576 my $xml = $_[1]; 679 my $xml = $_[1];
577 # handle xml 680 # handle xml
578 }); 681 });
579 }); 682 });
580 }); 683 });
581 684
582Example 2: Implement a client for a protocol that replies either with 685Example 2: Implement a client for a protocol that replies either with "OK"
583"OK" and another line or "ERROR" for one request, and 64 bytes for the 686and another line or "ERROR" for the first request that is sent, and 64
584second request. Due tot he availability of a full queue, we can just 687bytes for the second request. Due to the availability of a queue, we can
585pipeline sending both requests and manipulate the queue as necessary in 688just pipeline sending both requests and manipulate the queue as necessary
586the callbacks: 689in the callbacks.
587 690
588 # request one 691When the first callback is called and sees an "OK" response, it will
692C<unshift> another line-read. This line-read will be queued I<before> the
69364-byte chunk callback.
694
695 # request one, returns either "OK + extra line" or "ERROR"
589 $handle->push_write ("request 1\015\012"); 696 $handle->push_write ("request 1\015\012");
590 697
591 # we expect "ERROR" or "OK" as response, so push a line read 698 # we expect "ERROR" or "OK" as response, so push a line read
592 $handle->push_read_line (sub { 699 $handle->push_read (line => sub {
593 # if we got an "OK", we have to _prepend_ another line, 700 # if we got an "OK", we have to _prepend_ another line,
594 # so it will be read before the second request reads its 64 bytes 701 # so it will be read before the second request reads its 64 bytes
595 # which are already in the queue when this callback is called 702 # which are already in the queue when this callback is called
596 # we don't do this in case we got an error 703 # we don't do this in case we got an error
597 if ($_[1] eq "OK") { 704 if ($_[1] eq "OK") {
598 $_[0]->unshift_read_line (sub { 705 $_[0]->unshift_read (line => sub {
599 my $response = $_[1]; 706 my $response = $_[1];
600 ... 707 ...
601 }); 708 });
602 } 709 }
603 }); 710 });
604 711
605 # request two 712 # request two, simply returns 64 octets
606 $handle->push_write ("request 2\015\012"); 713 $handle->push_write ("request 2\015\012");
607 714
608 # simply read 64 bytes, always 715 # simply read 64 bytes, always
609 $handle->push_read_chunk (64, sub { 716 $handle->push_read (chunk => 64, sub {
610 my $response = $_[1]; 717 my $response = $_[1];
611 ... 718 ...
612 }); 719 });
613 720
614=over 4 721=over 4
615 722
616=cut 723=cut
617 724
618sub _drain_rbuf { 725sub _drain_rbuf {
619 my ($self) = @_; 726 my ($self) = @_;
727
728 local $self->{_in_drain} = 1;
620 729
621 if ( 730 if (
622 defined $self->{rbuf_max} 731 defined $self->{rbuf_max}
623 && $self->{rbuf_max} < length $self->{rbuf} 732 && $self->{rbuf_max} < length $self->{rbuf}
624 ) { 733 ) {
625 $! = &Errno::ENOSPC; 734 return $self->_error (&Errno::ENOSPC, 1);
626 $self->error;
627 } 735 }
628 736
629 return if $self->{in_drain}; 737 while () {
630 local $self->{in_drain} = 1;
631
632 while (my $len = length $self->{rbuf}) { 738 my $len = length $self->{rbuf};
633 no strict 'refs'; 739
634 if (my $cb = shift @{ $self->{_queue} }) { 740 if (my $cb = shift @{ $self->{_queue} }) {
635 unless ($cb->($self)) { 741 unless ($cb->($self)) {
636 if ($self->{_eof}) { 742 if ($self->{_eof}) {
637 # no progress can be made (not enough data and no data forthcoming) 743 # no progress can be made (not enough data and no data forthcoming)
638 $! = &Errno::EPIPE; 744 $self->_error (&Errno::EPIPE, 1), last;
639 $self->error;
640 } 745 }
641 746
642 unshift @{ $self->{_queue} }, $cb; 747 unshift @{ $self->{_queue} }, $cb;
643 return; 748 last;
644 } 749 }
645 } elsif ($self->{on_read}) { 750 } elsif ($self->{on_read}) {
751 last unless $len;
752
646 $self->{on_read}($self); 753 $self->{on_read}($self);
647 754
648 if ( 755 if (
649 $self->{_eof} # if no further data will arrive
650 && $len == length $self->{rbuf} # and no data has been consumed 756 $len == length $self->{rbuf} # if no data has been consumed
651 && !@{ $self->{_queue} } # and the queue is still empty 757 && !@{ $self->{_queue} } # and the queue is still empty
652 && $self->{on_read} # and we still want to read data 758 && $self->{on_read} # but we still have on_read
653 ) { 759 ) {
760 # no further data will arrive
654 # then no progress can be made 761 # so no progress can be made
655 $! = &Errno::EPIPE; 762 $self->_error (&Errno::EPIPE, 1), last
656 $self->error; 763 if $self->{_eof};
764
765 last; # more data might arrive
657 } 766 }
658 } else { 767 } else {
659 # read side becomes idle 768 # read side becomes idle
660 delete $self->{_rw}; 769 delete $self->{_rw};
661 return; 770 last;
662 } 771 }
663 } 772 }
664 773
665 if ($self->{_eof}) { 774 if ($self->{_eof}) {
666 $self->_shutdown; 775 if ($self->{on_eof}) {
667 $self->{on_eof}($self) 776 $self->{on_eof}($self)
668 if $self->{on_eof}; 777 } else {
778 $self->_error (0, 1);
779 }
780 }
781
782 # may need to restart read watcher
783 unless ($self->{_rw}) {
784 $self->start_read
785 if $self->{on_read} || @{ $self->{_queue} };
669 } 786 }
670} 787}
671 788
672=item $handle->on_read ($cb) 789=item $handle->on_read ($cb)
673 790
679 796
680sub on_read { 797sub on_read {
681 my ($self, $cb) = @_; 798 my ($self, $cb) = @_;
682 799
683 $self->{on_read} = $cb; 800 $self->{on_read} = $cb;
801 $self->_drain_rbuf if $cb && !$self->{_in_drain};
684} 802}
685 803
686=item $handle->rbuf 804=item $handle->rbuf
687 805
688Returns the read buffer (as a modifiable lvalue). 806Returns the read buffer (as a modifiable lvalue).
737 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 855 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read")
738 ->($self, $cb, @_); 856 ->($self, $cb, @_);
739 } 857 }
740 858
741 push @{ $self->{_queue} }, $cb; 859 push @{ $self->{_queue} }, $cb;
742 $self->_drain_rbuf; 860 $self->_drain_rbuf unless $self->{_in_drain};
743} 861}
744 862
745sub unshift_read { 863sub unshift_read {
746 my $self = shift; 864 my $self = shift;
747 my $cb = pop; 865 my $cb = pop;
753 ->($self, $cb, @_); 871 ->($self, $cb, @_);
754 } 872 }
755 873
756 874
757 unshift @{ $self->{_queue} }, $cb; 875 unshift @{ $self->{_queue} }, $cb;
758 $self->_drain_rbuf; 876 $self->_drain_rbuf unless $self->{_in_drain};
759} 877}
760 878
761=item $handle->push_read (type => @args, $cb) 879=item $handle->push_read (type => @args, $cb)
762 880
763=item $handle->unshift_read (type => @args, $cb) 881=item $handle->unshift_read (type => @args, $cb)
793 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, ""); 911 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
794 1 912 1
795 } 913 }
796}; 914};
797 915
798# compatibility with older API
799sub push_read_chunk {
800 $_[0]->push_read (chunk => $_[1], $_[2]);
801}
802
803sub unshift_read_chunk {
804 $_[0]->unshift_read (chunk => $_[1], $_[2]);
805}
806
807=item line => [$eol, ]$cb->($handle, $line, $eol) 916=item line => [$eol, ]$cb->($handle, $line, $eol)
808 917
809The callback will be called only once a full line (including the end of 918The callback will be called only once a full line (including the end of
810line marker, C<$eol>) has been read. This line (excluding the end of line 919line marker, C<$eol>) has been read. This line (excluding the end of line
811marker) will be passed to the callback as second argument (C<$line>), and 920marker) will be passed to the callback as second argument (C<$line>), and
826=cut 935=cut
827 936
828register_read_type line => sub { 937register_read_type line => sub {
829 my ($self, $cb, $eol) = @_; 938 my ($self, $cb, $eol) = @_;
830 939
831 $eol = qr|(\015?\012)| if @_ < 3; 940 if (@_ < 3) {
941 # this is more than twice as fast as the generic code below
942 sub {
943 $_[0]{rbuf} =~ s/^([^\015\012]*)(\015?\012)// or return;
944
945 $cb->($_[0], $1, $2);
946 1
947 }
948 } else {
832 $eol = quotemeta $eol unless ref $eol; 949 $eol = quotemeta $eol unless ref $eol;
833 $eol = qr|^(.*?)($eol)|s; 950 $eol = qr|^(.*?)($eol)|s;
834 951
835 sub { 952 sub {
836 $_[0]{rbuf} =~ s/$eol// or return; 953 $_[0]{rbuf} =~ s/$eol// or return;
837 954
838 $cb->($_[0], $1, $2); 955 $cb->($_[0], $1, $2);
839 1
840 }
841};
842
843# compatibility with older API
844sub push_read_line {
845 my $self = shift;
846 $self->push_read (line => @_);
847}
848
849sub unshift_read_line {
850 my $self = shift;
851 $self->unshift_read (line => @_);
852}
853
854=item netstring => $cb->($handle, $string)
855
856A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
857
858Throws an error with C<$!> set to EBADMSG on format violations.
859
860=cut
861
862register_read_type netstring => sub {
863 my ($self, $cb) = @_;
864
865 sub {
866 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
867 if ($_[0]{rbuf} =~ /[^0-9]/) {
868 $! = &Errno::EBADMSG;
869 $self->error;
870 } 956 1
871 return;
872 }
873
874 my $len = $1;
875
876 $self->unshift_read (chunk => $len, sub {
877 my $string = $_[1];
878 $_[0]->unshift_read (chunk => 1, sub {
879 if ($_[1] eq ",") {
880 $cb->($_[0], $string);
881 } else {
882 $! = &Errno::EBADMSG;
883 $self->error;
884 }
885 });
886 }); 957 }
887
888 1
889 } 958 }
890}; 959};
891 960
892=item regex => $accept[, $reject[, $skip], $cb->($handle, $data) 961=item regex => $accept[, $reject[, $skip], $cb->($handle, $data)
893 962
945 return 1; 1014 return 1;
946 } 1015 }
947 1016
948 # reject 1017 # reject
949 if ($reject && $$rbuf =~ $reject) { 1018 if ($reject && $$rbuf =~ $reject) {
950 $! = &Errno::EBADMSG; 1019 $self->_error (&Errno::EBADMSG);
951 $self->error;
952 } 1020 }
953 1021
954 # skip 1022 # skip
955 if ($skip && $$rbuf =~ $skip) { 1023 if ($skip && $$rbuf =~ $skip) {
956 $data .= substr $$rbuf, 0, $+[0], ""; 1024 $data .= substr $$rbuf, 0, $+[0], "";
957 } 1025 }
958 1026
959 () 1027 ()
1028 }
1029};
1030
1031=item netstring => $cb->($handle, $string)
1032
1033A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
1034
1035Throws an error with C<$!> set to EBADMSG on format violations.
1036
1037=cut
1038
1039register_read_type netstring => sub {
1040 my ($self, $cb) = @_;
1041
1042 sub {
1043 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
1044 if ($_[0]{rbuf} =~ /[^0-9]/) {
1045 $self->_error (&Errno::EBADMSG);
1046 }
1047 return;
1048 }
1049
1050 my $len = $1;
1051
1052 $self->unshift_read (chunk => $len, sub {
1053 my $string = $_[1];
1054 $_[0]->unshift_read (chunk => 1, sub {
1055 if ($_[1] eq ",") {
1056 $cb->($_[0], $string);
1057 } else {
1058 $self->_error (&Errno::EBADMSG);
1059 }
1060 });
1061 });
1062
1063 1
1064 }
1065};
1066
1067=item packstring => $format, $cb->($handle, $string)
1068
1069An octet string prefixed with an encoded length. The encoding C<$format>
1070uses the same format as a Perl C<pack> format, but must specify a single
1071integer only (only one of C<cCsSlLqQiInNvVjJw> is allowed, plus an
1072optional C<!>, C<< < >> or C<< > >> modifier).
1073
1074DNS over TCP uses a prefix of C<n>, EPP uses a prefix of C<N>.
1075
1076Example: read a block of data prefixed by its length in BER-encoded
1077format (very efficient).
1078
1079 $handle->push_read (packstring => "w", sub {
1080 my ($handle, $data) = @_;
1081 });
1082
1083=cut
1084
1085register_read_type packstring => sub {
1086 my ($self, $cb, $format) = @_;
1087
1088 sub {
1089 # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method
1090 defined (my $len = eval { unpack $format, $_[0]{rbuf} })
1091 or return;
1092
1093 $format = length pack $format, $len;
1094
1095 # bypass unshift if we already have the remaining chunk
1096 if ($format + $len <= length $_[0]{rbuf}) {
1097 my $data = substr $_[0]{rbuf}, $format, $len;
1098 substr $_[0]{rbuf}, 0, $format + $len, "";
1099 $cb->($_[0], $data);
1100 } else {
1101 # remove prefix
1102 substr $_[0]{rbuf}, 0, $format, "";
1103
1104 # read remaining chunk
1105 $_[0]->unshift_read (chunk => $len, $cb);
1106 }
1107
1108 1
960 } 1109 }
961}; 1110};
962 1111
963=item json => $cb->($handle, $hash_or_arrayref) 1112=item json => $cb->($handle, $hash_or_arrayref)
964 1113
977the C<json> write type description, above, for an actual example. 1126the C<json> write type description, above, for an actual example.
978 1127
979=cut 1128=cut
980 1129
981register_read_type json => sub { 1130register_read_type json => sub {
982 my ($self, $cb, $accept, $reject, $skip) = @_; 1131 my ($self, $cb) = @_;
983 1132
984 require JSON; 1133 require JSON;
985 1134
986 my $data; 1135 my $data;
987 my $rbuf = \$self->{rbuf}; 1136 my $rbuf = \$self->{rbuf};
1002 () 1151 ()
1003 } 1152 }
1004 } 1153 }
1005}; 1154};
1006 1155
1156=item storable => $cb->($handle, $ref)
1157
1158Deserialises a L<Storable> frozen representation as written by the
1159C<storable> write type (BER-encoded length prefix followed by nfreeze'd
1160data).
1161
1162Raises C<EBADMSG> error if the data could not be decoded.
1163
1164=cut
1165
1166register_read_type storable => sub {
1167 my ($self, $cb) = @_;
1168
1169 require Storable;
1170
1171 sub {
1172 # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method
1173 defined (my $len = eval { unpack "w", $_[0]{rbuf} })
1174 or return;
1175
1176 my $format = length pack "w", $len;
1177
1178 # bypass unshift if we already have the remaining chunk
1179 if ($format + $len <= length $_[0]{rbuf}) {
1180 my $data = substr $_[0]{rbuf}, $format, $len;
1181 substr $_[0]{rbuf}, 0, $format + $len, "";
1182 $cb->($_[0], Storable::thaw ($data));
1183 } else {
1184 # remove prefix
1185 substr $_[0]{rbuf}, 0, $format, "";
1186
1187 # read remaining chunk
1188 $_[0]->unshift_read (chunk => $len, sub {
1189 if (my $ref = eval { Storable::thaw ($_[1]) }) {
1190 $cb->($_[0], $ref);
1191 } else {
1192 $self->_error (&Errno::EBADMSG);
1193 }
1194 });
1195 }
1196
1197 1
1198 }
1199};
1200
1007=back 1201=back
1008 1202
1009=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1203=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args)
1010 1204
1011This function (not method) lets you add your own types to C<push_read>. 1205This function (not method) lets you add your own types to C<push_read>.
1029=item $handle->stop_read 1223=item $handle->stop_read
1030 1224
1031=item $handle->start_read 1225=item $handle->start_read
1032 1226
1033In rare cases you actually do not want to read anything from the 1227In rare cases you actually do not want to read anything from the
1034socket. In this case you can call C<stop_read>. Neither C<on_read> no 1228socket. In this case you can call C<stop_read>. Neither C<on_read> nor
1035any queued callbacks will be executed then. To start reading again, call 1229any queued callbacks will be executed then. To start reading again, call
1036C<start_read>. 1230C<start_read>.
1231
1232Note that AnyEvent::Handle will automatically C<start_read> for you when
1233you change the C<on_read> callback or push/unshift a read callback, and it
1234will automatically C<stop_read> for you when neither C<on_read> is set nor
1235there are any read requests in the queue.
1037 1236
1038=cut 1237=cut
1039 1238
1040sub stop_read { 1239sub stop_read {
1041 my ($self) = @_; 1240 my ($self) = @_;
1055 1254
1056 if ($len > 0) { 1255 if ($len > 0) {
1057 $self->{_activity} = AnyEvent->now; 1256 $self->{_activity} = AnyEvent->now;
1058 1257
1059 $self->{filter_r} 1258 $self->{filter_r}
1060 ? $self->{filter_r}->($self, $rbuf) 1259 ? $self->{filter_r}($self, $rbuf)
1061 : $self->_drain_rbuf; 1260 : $self->{_in_drain} || $self->_drain_rbuf;
1062 1261
1063 } elsif (defined $len) { 1262 } elsif (defined $len) {
1064 delete $self->{_rw}; 1263 delete $self->{_rw};
1065 delete $self->{_ww};
1066 delete $self->{_tw};
1067 $self->{_eof} = 1; 1264 $self->{_eof} = 1;
1068 $self->_drain_rbuf; 1265 $self->_drain_rbuf unless $self->{_in_drain};
1069 1266
1070 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) { 1267 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
1071 return $self->error; 1268 return $self->_error ($!, 1);
1072 } 1269 }
1073 }); 1270 });
1074 } 1271 }
1075} 1272}
1076 1273
1077sub _dotls { 1274sub _dotls {
1078 my ($self) = @_; 1275 my ($self) = @_;
1276
1277 my $buf;
1079 1278
1080 if (length $self->{_tls_wbuf}) { 1279 if (length $self->{_tls_wbuf}) {
1081 while ((my $len = Net::SSLeay::write ($self->{tls}, $self->{_tls_wbuf})) > 0) { 1280 while ((my $len = Net::SSLeay::write ($self->{tls}, $self->{_tls_wbuf})) > 0) {
1082 substr $self->{_tls_wbuf}, 0, $len, ""; 1281 substr $self->{_tls_wbuf}, 0, $len, "";
1083 } 1282 }
1084 } 1283 }
1085 1284
1086 if (defined (my $buf = Net::SSLeay::BIO_read ($self->{_wbio}))) { 1285 if (length ($buf = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1087 $self->{wbuf} .= $buf; 1286 $self->{wbuf} .= $buf;
1088 $self->_drain_wbuf; 1287 $self->_drain_wbuf;
1089 } 1288 }
1090 1289
1091 while (defined (my $buf = Net::SSLeay::read ($self->{tls}))) { 1290 while (defined ($buf = Net::SSLeay::read ($self->{tls}))) {
1291 if (length $buf) {
1092 $self->{rbuf} .= $buf; 1292 $self->{rbuf} .= $buf;
1093 $self->_drain_rbuf; 1293 $self->_drain_rbuf unless $self->{_in_drain};
1294 } else {
1295 # let's treat SSL-eof as we treat normal EOF
1296 $self->{_eof} = 1;
1297 $self->_shutdown;
1298 return;
1299 }
1094 } 1300 }
1095 1301
1096 my $err = Net::SSLeay::get_error ($self->{tls}, -1); 1302 my $err = Net::SSLeay::get_error ($self->{tls}, -1);
1097 1303
1098 if ($err!= Net::SSLeay::ERROR_WANT_READ ()) { 1304 if ($err!= Net::SSLeay::ERROR_WANT_READ ()) {
1099 if ($err == Net::SSLeay::ERROR_SYSCALL ()) { 1305 if ($err == Net::SSLeay::ERROR_SYSCALL ()) {
1100 $self->error; 1306 return $self->_error ($!, 1);
1101 } elsif ($err == Net::SSLeay::ERROR_SSL ()) { 1307 } elsif ($err == Net::SSLeay::ERROR_SSL ()) {
1102 $! = &Errno::EIO; 1308 return $self->_error (&Errno::EIO, 1);
1103 $self->error;
1104 } 1309 }
1105 1310
1106 # all others are fine for our purposes 1311 # all others are fine for our purposes
1107 } 1312 }
1108} 1313}
1123call and can be used or changed to your liking. Note that the handshake 1328call and can be used or changed to your liking. Note that the handshake
1124might have already started when this function returns. 1329might have already started when this function returns.
1125 1330
1126=cut 1331=cut
1127 1332
1128# TODO: maybe document...
1129sub starttls { 1333sub starttls {
1130 my ($self, $ssl, $ctx) = @_; 1334 my ($self, $ssl, $ctx) = @_;
1131 1335
1132 $self->stoptls; 1336 $self->stoptls;
1133 1337
1186 1390
1187sub DESTROY { 1391sub DESTROY {
1188 my $self = shift; 1392 my $self = shift;
1189 1393
1190 $self->stoptls; 1394 $self->stoptls;
1395
1396 my $linger = exists $self->{linger} ? $self->{linger} : 3600;
1397
1398 if ($linger && length $self->{wbuf}) {
1399 my $fh = delete $self->{fh};
1400 my $wbuf = delete $self->{wbuf};
1401
1402 my @linger;
1403
1404 push @linger, AnyEvent->io (fh => $fh, poll => "w", cb => sub {
1405 my $len = syswrite $fh, $wbuf, length $wbuf;
1406
1407 if ($len > 0) {
1408 substr $wbuf, 0, $len, "";
1409 } else {
1410 @linger = (); # end
1411 }
1412 });
1413 push @linger, AnyEvent->timer (after => $linger, cb => sub {
1414 @linger = ();
1415 });
1416 }
1191} 1417}
1192 1418
1193=item AnyEvent::Handle::TLS_CTX 1419=item AnyEvent::Handle::TLS_CTX
1194 1420
1195This function creates and returns the Net::SSLeay::CTX object used by 1421This function creates and returns the Net::SSLeay::CTX object used by
1237=over 4 1463=over 4
1238 1464
1239=item * all constructor arguments become object members. 1465=item * all constructor arguments become object members.
1240 1466
1241At least initially, when you pass a C<tls>-argument to the constructor it 1467At least initially, when you pass a C<tls>-argument to the constructor it
1242will end up in C<< $handle->{tls} >>. Those members might be changes or 1468will end up in C<< $handle->{tls} >>. Those members might be changed or
1243mutated later on (for example C<tls> will hold the TLS connection object). 1469mutated later on (for example C<tls> will hold the TLS connection object).
1244 1470
1245=item * other object member names are prefixed with an C<_>. 1471=item * other object member names are prefixed with an C<_>.
1246 1472
1247All object members not explicitly documented (internal use) are prefixed 1473All object members not explicitly documented (internal use) are prefixed

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines