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.30 by root, Sat May 24 23:56:26 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 (); 7use AnyEvent::Util qw(WSAEWOULDBLOCK);
8use Scalar::Util (); 8use Scalar::Util ();
9use Carp (); 9use Carp ();
10use Fcntl (); 10use Fcntl ();
11use Errno qw/EAGAIN EINTR/; 11use Errno qw(EAGAIN EINTR);
12 12
13=head1 NAME 13=head1 NAME
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
17This module is experimental.
18
19=cut 17=cut
20 18
21our $VERSION = '0.04'; 19our $VERSION = 4.22;
22 20
23=head1 SYNOPSIS 21=head1 SYNOPSIS
24 22
25 use AnyEvent; 23 use AnyEvent;
26 use AnyEvent::Handle; 24 use AnyEvent::Handle;
27 25
28 my $cv = AnyEvent->condvar; 26 my $cv = AnyEvent->condvar;
29 27
30 my $ae_fh = AnyEvent::Handle->new (fh => \*STDIN); 28 my $handle =
31
32 #TODO
33
34 # or use the constructor to pass the callback:
35
36 my $ae_fh2 =
37 AnyEvent::Handle->new ( 29 AnyEvent::Handle->new (
38 fh => \*STDIN, 30 fh => \*STDIN,
39 on_eof => sub { 31 on_eof => sub {
40 $cv->broadcast; 32 $cv->broadcast;
41 }, 33 },
42 #TODO
43 ); 34 );
44 35
45 $cv->wait; 36 # send some request line
37 $handle->push_write ("getinfo\015\012");
38
39 # read the response line
40 $handle->push_read (line => sub {
41 my ($handle, $line) = @_;
42 warn "read line <$line>\n";
43 $cv->send;
44 });
45
46 $cv->recv;
46 47
47=head1 DESCRIPTION 48=head1 DESCRIPTION
48 49
49This module is a helper module to make it easier to do event-based I/O on 50This module is a helper module to make it easier to do event-based I/O on
50filehandles. For utility functions for doing non-blocking connects and accepts 51filehandles. For utility functions for doing non-blocking connects and accepts
72The filehandle this L<AnyEvent::Handle> object will operate on. 73The filehandle this L<AnyEvent::Handle> object will operate on.
73 74
74NOTE: The filehandle will be set to non-blocking (using 75NOTE: The filehandle will be set to non-blocking (using
75AnyEvent::Util::fh_nonblocking). 76AnyEvent::Util::fh_nonblocking).
76 77
77=item on_eof => $cb->($self) 78=item on_eof => $cb->($handle)
78 79
79Set 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.
80 83
81While not mandatory, it is highly recommended to set an eof callback, 84While not mandatory, it is I<highly> recommended to set an eof callback,
82otherwise 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
83waiting for data. 86waiting for data.
84 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
85=item on_error => $cb->($self) 91=item on_error => $cb->($handle, $fatal)
86 92
87This 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
88occurs, such as not being able to resolve the hostname, failure to connect 94occured, such as not being able to resolve the hostname, failure to
89or a read error. 95connect or a read error.
90 96
91The 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
92called. 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.
93 102
94On callback entrance, the value of C<$!> contains the operating system 103On callback entrance, the value of C<$!> contains the operating system
95error (or C<ENOSPC>, C<EPIPE> or C<EBADMSG>). 104error (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT> or C<EBADMSG>).
96 105
97While 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
98you will not be notified of errors otherwise. The default simply calls 107you will not be notified of errors otherwise. The default simply calls
99die. 108C<croak>.
100 109
101=item on_read => $cb->($self) 110=item on_read => $cb->($handle)
102 111
103This sets the default read callback, which is called when data arrives 112This sets the default read callback, which is called when data arrives
104and 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).
105 116
106To 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 >>
107method or access the C<$self->{rbuf}> member directly. 118method or access the C<$handle->{rbuf}> member directly.
108 119
109When 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
110feed all the remaining data to the queued callbacks and C<on_read> before 121feed all the remaining data to the queued callbacks and C<on_read> before
111calling the C<on_eof> callback. If no progress can be made, then a fatal 122calling the C<on_eof> callback. If no progress can be made, then a fatal
112error will be raised (with C<$!> set to C<EPIPE>). 123error will be raised (with C<$!> set to C<EPIPE>).
113 124
114=item on_drain => $cb->() 125=item on_drain => $cb->($handle)
115 126
116This 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
117(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).
118 129
119To 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.
137
138=item timeout => $fractional_seconds
139
140If non-zero, then this enables an "inactivity" timeout: whenever this many
141seconds pass without a successful read or write on the underlying file
142handle, the C<on_timeout> callback will be invoked (and if that one is
143missing, an C<ETIMEDOUT> error will be raised).
144
145Note that timeout processing is also active when you currently do not have
146any outstanding read or write requests: If you plan to keep the connection
147idle then you should disable the timout temporarily or ignore the timeout
148in the C<on_timeout> callback.
149
150Zero (the default) disables this timeout.
151
152=item on_timeout => $cb->($handle)
153
154Called whenever the inactivity timeout passes. If you return from this
155callback, then the timeout will be reset as if some activity had happened,
156so this condition is not fatal in any way.
120 157
121=item rbuf_max => <bytes> 158=item rbuf_max => <bytes>
122 159
123If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>) 160If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
124when the read buffer ever (strictly) exceeds this size. This is useful to 161when the read buffer ever (strictly) exceeds this size. This is useful to
128be 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
129(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
130amount 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
131isn't finished). 168isn't finished).
132 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
133=item read_size => <bytes> 194=item read_size => <bytes>
134 195
135The 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
136on each [loop iteration). Default: C<4096>. 197during each (loop iteration). Default: C<8192>.
137 198
138=item low_water_mark => <bytes> 199=item low_water_mark => <bytes>
139 200
140Sets 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
141buffer: 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
142considered 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.
143 215
144=item tls => "accept" | "connect" | Net::SSLeay::SSL object 216=item tls => "accept" | "connect" | Net::SSLeay::SSL object
145 217
146When 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
147will start making tls handshake and will transparently encrypt/decrypt 219will start making tls handshake and will transparently encrypt/decrypt
156You can also provide your own TLS connection object, but you have 228You can also provide your own TLS connection object, but you have
157to 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>
158or 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
159AnyEvent::Handle. 231AnyEvent::Handle.
160 232
161See 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.
162 234
163=item tls_ctx => $ssl_ctx 235=item tls_ctx => $ssl_ctx
164 236
165Use 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
166(unless a connection object was specified directly). If this parameter is 238(unless a connection object was specified directly). If this parameter is
167missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>. 239missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>.
168 240
241=item json => JSON or JSON::XS object
242
243This is the json coder object used by the C<json> read and write types.
244
245If you don't supply it, then AnyEvent::Handle will create and use a
246suitable one, which will write and expect UTF-8 encoded JSON texts.
247
248Note that you are responsible to depend on the JSON module if you want to
249use this functionality, as AnyEvent does not have a dependency itself.
250
251=item filter_r => $cb
252
253=item filter_w => $cb
254
255These exist, but are undocumented at this time.
256
169=back 257=back
170 258
171=cut 259=cut
172 260
173sub new { 261sub new {
182 if ($self->{tls}) { 270 if ($self->{tls}) {
183 require Net::SSLeay; 271 require Net::SSLeay;
184 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}); 272 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
185 } 273 }
186 274
187 $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof}; 275 $self->{_activity} = AnyEvent->now;
188 $self->on_error (delete $self->{on_error}) if $self->{on_error}; 276 $self->_timeout;
277
189 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 278 $self->on_drain (delete $self->{on_drain}) if exists $self->{on_drain};
190 $self->on_read (delete $self->{on_read} ) if $self->{on_read}; 279 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay};
191 280
192 $self->start_read; 281 $self->start_read
282 if $self->{on_read};
193 283
194 $self 284 $self
195} 285}
196 286
197sub _shutdown { 287sub _shutdown {
198 my ($self) = @_; 288 my ($self) = @_;
199 289
290 delete $self->{_tw};
200 delete $self->{rw}; 291 delete $self->{_rw};
201 delete $self->{ww}; 292 delete $self->{_ww};
202 delete $self->{fh}; 293 delete $self->{fh};
203}
204 294
295 $self->stoptls;
296}
297
205sub error { 298sub _error {
206 my ($self) = @_; 299 my ($self, $errno, $fatal) = @_;
207 300
208 {
209 local $!;
210 $self->_shutdown; 301 $self->_shutdown
211 } 302 if $fatal;
303
304 $! = $errno;
212 305
213 if ($self->{on_error}) { 306 if ($self->{on_error}) {
214 $self->{on_error}($self); 307 $self->{on_error}($self, $fatal);
215 } else { 308 } else {
216 Carp::croak "AnyEvent::Handle uncaught fatal error: $!"; 309 Carp::croak "AnyEvent::Handle uncaught error: $!";
217 } 310 }
218} 311}
219 312
220=item $fh = $handle->fh 313=item $fh = $handle->fh
221 314
222This method returns the file handle of the L<AnyEvent::Handle> object. 315This method returns the file handle of the L<AnyEvent::Handle> object.
223 316
224=cut 317=cut
225 318
226sub fh { $_[0]->{fh} } 319sub fh { $_[0]{fh} }
227 320
228=item $handle->on_error ($cb) 321=item $handle->on_error ($cb)
229 322
230Replace the current C<on_error> callback (see the C<on_error> constructor argument). 323Replace the current C<on_error> callback (see the C<on_error> constructor argument).
231 324
241 334
242=cut 335=cut
243 336
244sub on_eof { 337sub on_eof {
245 $_[0]{on_eof} = $_[1]; 338 $_[0]{on_eof} = $_[1];
339}
340
341=item $handle->on_timeout ($cb)
342
343Replace the current C<on_timeout> callback, or disables the callback
344(but not the timeout) if C<$cb> = C<undef>. See C<timeout> constructor
345argument.
346
347=cut
348
349sub on_timeout {
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 };
374}
375
376#############################################################################
377
378=item $handle->timeout ($seconds)
379
380Configures (or disables) the inactivity timeout.
381
382=cut
383
384sub timeout {
385 my ($self, $timeout) = @_;
386
387 $self->{timeout} = $timeout;
388 $self->_timeout;
389}
390
391# reset the timeout watcher, as neccessary
392# also check for time-outs
393sub _timeout {
394 my ($self) = @_;
395
396 if ($self->{timeout}) {
397 my $NOW = AnyEvent->now;
398
399 # when would the timeout trigger?
400 my $after = $self->{_activity} + $self->{timeout} - $NOW;
401
402 # now or in the past already?
403 if ($after <= 0) {
404 $self->{_activity} = $NOW;
405
406 if ($self->{on_timeout}) {
407 $self->{on_timeout}($self);
408 } else {
409 $self->_error (&Errno::ETIMEDOUT);
410 }
411
412 # callback could have changed timeout value, optimise
413 return unless $self->{timeout};
414
415 # calculate new after
416 $after = $self->{timeout};
417 }
418
419 Scalar::Util::weaken $self;
420 return unless $self; # ->error could have destroyed $self
421
422 $self->{_tw} ||= AnyEvent->timer (after => $after, cb => sub {
423 delete $self->{_tw};
424 $self->_timeout;
425 });
426 } else {
427 delete $self->{_tw};
428 }
246} 429}
247 430
248############################################################################# 431#############################################################################
249 432
250=back 433=back
287=cut 470=cut
288 471
289sub _drain_wbuf { 472sub _drain_wbuf {
290 my ($self) = @_; 473 my ($self) = @_;
291 474
292 if (!$self->{ww} && length $self->{wbuf}) { 475 if (!$self->{_ww} && length $self->{wbuf}) {
476
293 Scalar::Util::weaken $self; 477 Scalar::Util::weaken $self;
478
294 my $cb = sub { 479 my $cb = sub {
295 my $len = syswrite $self->{fh}, $self->{wbuf}; 480 my $len = syswrite $self->{fh}, $self->{wbuf};
296 481
297 if ($len >= 0) { 482 if ($len >= 0) {
298 substr $self->{wbuf}, 0, $len, ""; 483 substr $self->{wbuf}, 0, $len, "";
484
485 $self->{_activity} = AnyEvent->now;
299 486
300 $self->{on_drain}($self) 487 $self->{on_drain}($self)
301 if $self->{low_water_mark} >= length $self->{wbuf} 488 if $self->{low_water_mark} >= length $self->{wbuf}
302 && $self->{on_drain}; 489 && $self->{on_drain};
303 490
304 delete $self->{ww} unless length $self->{wbuf}; 491 delete $self->{_ww} unless length $self->{wbuf};
305 } elsif ($! != EAGAIN && $! != EINTR) { 492 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
306 $self->error; 493 $self->_error ($!, 1);
307 } 494 }
308 }; 495 };
309 496
497 # try to write data immediately
498 $cb->() unless $self->{autocork};
499
500 # if still data left in wbuf, we need to poll
310 $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb); 501 $self->{_ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb)
311 502 if length $self->{wbuf};
312 $cb->($self);
313 }; 503 };
314} 504}
315 505
316our %WH; 506our %WH;
317 507
328 @_ = ($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")
329 ->($self, @_); 519 ->($self, @_);
330 } 520 }
331 521
332 if ($self->{filter_w}) { 522 if ($self->{filter_w}) {
333 $self->{filter_w}->($self, \$_[0]); 523 $self->{filter_w}($self, \$_[0]);
334 } else { 524 } else {
335 $self->{wbuf} .= $_[0]; 525 $self->{wbuf} .= $_[0];
336 $self->_drain_wbuf; 526 $self->_drain_wbuf;
337 } 527 }
338} 528}
339 529
340=item $handle->push_write (type => @args) 530=item $handle->push_write (type => @args)
341 531
342=item $handle->unshift_write (type => @args)
343
344Instead 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
345the job by specifying a type and type-specific arguments. 533the job by specifying a type and type-specific arguments.
346 534
347Predefined 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
348drop by and tell us): 536drop by and tell us):
352=item netstring => $string 540=item netstring => $string
353 541
354Formats the given value as netstring 542Formats the given value as netstring
355(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).
356 544
357=back
358
359=cut 545=cut
360 546
361register_write_type netstring => sub { 547register_write_type netstring => sub {
362 my ($self, $string) = @_; 548 my ($self, $string) = @_;
363 549
364 sprintf "%d:%s,", (length $string), $string 550 sprintf "%d:%s,", (length $string), $string
365}; 551};
366 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
566};
567
568=item json => $array_or_hashref
569
570Encodes the given hash or array reference into a JSON object. Unless you
571provide your own JSON object, this means it will be encoded to JSON text
572in UTF-8.
573
574JSON objects (and arrays) are self-delimiting, so you can write JSON at
575one end of a handle and read them at the other end without using any
576additional framing.
577
578The generated JSON text is guaranteed not to contain any newlines: While
579this module doesn't need delimiters after or between JSON texts to be
580able to read them, many other languages depend on that.
581
582A simple RPC protocol that interoperates easily with others is to send
583JSON arrays (or objects, although arrays are usually the better choice as
584they mimic how function argument passing works) and a newline after each
585JSON text:
586
587 $handle->push_write (json => ["method", "arg1", "arg2"]); # whatever
588 $handle->push_write ("\012");
589
590An AnyEvent::Handle receiver would simply use the C<json> read type and
591rely on the fact that the newline will be skipped as leading whitespace:
592
593 $handle->push_read (json => sub { my $array = $_[1]; ... });
594
595Other languages could read single lines terminated by a newline and pass
596this line into their JSON decoder of choice.
597
598=cut
599
600register_write_type json => sub {
601 my ($self, $ref) = @_;
602
603 require JSON;
604
605 $self->{json} ? $self->{json}->encode ($ref)
606 : JSON::encode_json ($ref)
607};
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
367=item AnyEvent::Handle::register_write_type type => $coderef->($self, @args) 626=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args)
368 627
369This 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>.
370Whenever 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
371reference with the handle object and the remaining arguments. 630reference with the handle object and the remaining arguments.
372 631
391ways, 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
392a queue. 651a queue.
393 652
394In 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
395new 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
396enough 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
397or not. 656leave the data there if you want to accumulate more (e.g. when only a
657partial message has been received so far).
398 658
399In 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
400case, AnyEvent::Handle will call the first queued callback each time new 660case, AnyEvent::Handle will call the first queued callback each time new
401data 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
402below). 662done its job (see C<push_read>, below).
403 663
404This 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
405a chunk of data, and AnyEvent::Handle will execute them in order. 665a chunk of data, and AnyEvent::Handle will execute them in order.
406 666
407Example 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
408the specified number of bytes which give an XML datagram. 668the specified number of bytes which give an XML datagram.
409 669
410 # in the default state, expect some header bytes 670 # in the default state, expect some header bytes
411 $handle->on_read (sub { 671 $handle->on_read (sub {
412 # 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)
413 shift->unshift_read_chunk (4, sub { 673 shift->unshift_read (chunk => 4, sub {
414 # header arrived, decode 674 # header arrived, decode
415 my $len = unpack "N", $_[1]; 675 my $len = unpack "N", $_[1];
416 676
417 # now read the payload 677 # now read the payload
418 shift->unshift_read_chunk ($len, sub { 678 shift->unshift_read (chunk => $len, sub {
419 my $xml = $_[1]; 679 my $xml = $_[1];
420 # handle xml 680 # handle xml
421 }); 681 });
422 }); 682 });
423 }); 683 });
424 684
425Example 2: Implement a client for a protocol that replies either with 685Example 2: Implement a client for a protocol that replies either with "OK"
426"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
427second 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
428pipeline sending both requests and manipulate the queue as necessary in 688just pipeline sending both requests and manipulate the queue as necessary
429the callbacks: 689in the callbacks.
430 690
431 # 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"
432 $handle->push_write ("request 1\015\012"); 696 $handle->push_write ("request 1\015\012");
433 697
434 # 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
435 $handle->push_read_line (sub { 699 $handle->push_read (line => sub {
436 # if we got an "OK", we have to _prepend_ another line, 700 # if we got an "OK", we have to _prepend_ another line,
437 # 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
438 # which are already in the queue when this callback is called 702 # which are already in the queue when this callback is called
439 # we don't do this in case we got an error 703 # we don't do this in case we got an error
440 if ($_[1] eq "OK") { 704 if ($_[1] eq "OK") {
441 $_[0]->unshift_read_line (sub { 705 $_[0]->unshift_read (line => sub {
442 my $response = $_[1]; 706 my $response = $_[1];
443 ... 707 ...
444 }); 708 });
445 } 709 }
446 }); 710 });
447 711
448 # request two 712 # request two, simply returns 64 octets
449 $handle->push_write ("request 2\015\012"); 713 $handle->push_write ("request 2\015\012");
450 714
451 # simply read 64 bytes, always 715 # simply read 64 bytes, always
452 $handle->push_read_chunk (64, sub { 716 $handle->push_read (chunk => 64, sub {
453 my $response = $_[1]; 717 my $response = $_[1];
454 ... 718 ...
455 }); 719 });
456 720
457=over 4 721=over 4
458 722
459=cut 723=cut
460 724
461sub _drain_rbuf { 725sub _drain_rbuf {
462 my ($self) = @_; 726 my ($self) = @_;
727
728 local $self->{_in_drain} = 1;
463 729
464 if ( 730 if (
465 defined $self->{rbuf_max} 731 defined $self->{rbuf_max}
466 && $self->{rbuf_max} < length $self->{rbuf} 732 && $self->{rbuf_max} < length $self->{rbuf}
467 ) { 733 ) {
468 $! = &Errno::ENOSPC; return $self->error; 734 return $self->_error (&Errno::ENOSPC, 1);
469 } 735 }
470 736
471 return if $self->{in_drain}; 737 while () {
472 local $self->{in_drain} = 1;
473
474 while (my $len = length $self->{rbuf}) { 738 my $len = length $self->{rbuf};
475 no strict 'refs'; 739
476 if (my $cb = shift @{ $self->{queue} }) { 740 if (my $cb = shift @{ $self->{_queue} }) {
477 unless ($cb->($self)) { 741 unless ($cb->($self)) {
478 if ($self->{eof}) { 742 if ($self->{_eof}) {
479 # 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)
480 $! = &Errno::EPIPE; return $self->error; 744 $self->_error (&Errno::EPIPE, 1), last;
481 } 745 }
482 746
483 unshift @{ $self->{queue} }, $cb; 747 unshift @{ $self->{_queue} }, $cb;
484 return; 748 last;
485 } 749 }
486 } elsif ($self->{on_read}) { 750 } elsif ($self->{on_read}) {
751 last unless $len;
752
487 $self->{on_read}($self); 753 $self->{on_read}($self);
488 754
489 if ( 755 if (
490 $self->{eof} # if no further data will arrive
491 && $len == length $self->{rbuf} # and no data has been consumed 756 $len == length $self->{rbuf} # if no data has been consumed
492 && !@{ $self->{queue} } # and the queue is still empty 757 && !@{ $self->{_queue} } # and the queue is still empty
493 && $self->{on_read} # and we still want to read data 758 && $self->{on_read} # but we still have on_read
494 ) { 759 ) {
760 # no further data will arrive
495 # then no progress can be made 761 # so no progress can be made
496 $! = &Errno::EPIPE; return $self->error; 762 $self->_error (&Errno::EPIPE, 1), last
763 if $self->{_eof};
764
765 last; # more data might arrive
497 } 766 }
498 } else { 767 } else {
499 # read side becomes idle 768 # read side becomes idle
500 delete $self->{rw}; 769 delete $self->{_rw};
501 return; 770 last;
502 } 771 }
503 } 772 }
504 773
505 if ($self->{eof}) { 774 if ($self->{_eof}) {
506 $self->_shutdown; 775 if ($self->{on_eof}) {
507 $self->{on_eof}($self) 776 $self->{on_eof}($self)
508 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} };
509 } 786 }
510} 787}
511 788
512=item $handle->on_read ($cb) 789=item $handle->on_read ($cb)
513 790
519 796
520sub on_read { 797sub on_read {
521 my ($self, $cb) = @_; 798 my ($self, $cb) = @_;
522 799
523 $self->{on_read} = $cb; 800 $self->{on_read} = $cb;
801 $self->_drain_rbuf if $cb && !$self->{_in_drain};
524} 802}
525 803
526=item $handle->rbuf 804=item $handle->rbuf
527 805
528Returns the read buffer (as a modifiable lvalue). 806Returns the read buffer (as a modifiable lvalue).
576 854
577 $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")
578 ->($self, $cb, @_); 856 ->($self, $cb, @_);
579 } 857 }
580 858
581 push @{ $self->{queue} }, $cb; 859 push @{ $self->{_queue} }, $cb;
582 $self->_drain_rbuf; 860 $self->_drain_rbuf unless $self->{_in_drain};
583} 861}
584 862
585sub unshift_read { 863sub unshift_read {
586 my $self = shift; 864 my $self = shift;
587 my $cb = pop; 865 my $cb = pop;
592 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read") 870 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
593 ->($self, $cb, @_); 871 ->($self, $cb, @_);
594 } 872 }
595 873
596 874
597 unshift @{ $self->{queue} }, $cb; 875 unshift @{ $self->{_queue} }, $cb;
598 $self->_drain_rbuf; 876 $self->_drain_rbuf unless $self->{_in_drain};
599} 877}
600 878
601=item $handle->push_read (type => @args, $cb) 879=item $handle->push_read (type => @args, $cb)
602 880
603=item $handle->unshift_read (type => @args, $cb) 881=item $handle->unshift_read (type => @args, $cb)
609Predefined types are (if you have ideas for additional types, feel free to 887Predefined types are (if you have ideas for additional types, feel free to
610drop by and tell us): 888drop by and tell us):
611 889
612=over 4 890=over 4
613 891
614=item chunk => $octets, $cb->($self, $data) 892=item chunk => $octets, $cb->($handle, $data)
615 893
616Invoke the callback only once C<$octets> bytes have been read. Pass the 894Invoke the callback only once C<$octets> bytes have been read. Pass the
617data read to the callback. The callback will never be called with less 895data read to the callback. The callback will never be called with less
618data. 896data.
619 897
633 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, ""); 911 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
634 1 912 1
635 } 913 }
636}; 914};
637 915
638# compatibility with older API
639sub push_read_chunk {
640 $_[0]->push_read (chunk => $_[1], $_[2]);
641}
642
643sub unshift_read_chunk {
644 $_[0]->unshift_read (chunk => $_[1], $_[2]);
645}
646
647=item line => [$eol, ]$cb->($self, $line, $eol) 916=item line => [$eol, ]$cb->($handle, $line, $eol)
648 917
649The 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
650line 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
651marker) 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
652the end of line marker as the third argument (C<$eol>). 921the end of line marker as the third argument (C<$eol>).
666=cut 935=cut
667 936
668register_read_type line => sub { 937register_read_type line => sub {
669 my ($self, $cb, $eol) = @_; 938 my ($self, $cb, $eol) = @_;
670 939
671 $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 {
672 $eol = quotemeta $eol unless ref $eol; 949 $eol = quotemeta $eol unless ref $eol;
673 $eol = qr|^(.*?)($eol)|s; 950 $eol = qr|^(.*?)($eol)|s;
951
952 sub {
953 $_[0]{rbuf} =~ s/$eol// or return;
954
955 $cb->($_[0], $1, $2);
956 1
957 }
958 }
959};
960
961=item regex => $accept[, $reject[, $skip], $cb->($handle, $data)
962
963Makes a regex match against the regex object C<$accept> and returns
964everything up to and including the match.
965
966Example: read a single line terminated by '\n'.
967
968 $handle->push_read (regex => qr<\n>, sub { ... });
969
970If C<$reject> is given and not undef, then it determines when the data is
971to be rejected: it is matched against the data when the C<$accept> regex
972does not match and generates an C<EBADMSG> error when it matches. This is
973useful to quickly reject wrong data (to avoid waiting for a timeout or a
974receive buffer overflow).
975
976Example: expect a single decimal number followed by whitespace, reject
977anything else (not the use of an anchor).
978
979 $handle->push_read (regex => qr<^[0-9]+\s>, qr<[^0-9]>, sub { ... });
980
981If C<$skip> is given and not C<undef>, then it will be matched against
982the receive buffer when neither C<$accept> nor C<$reject> match,
983and everything preceding and including the match will be accepted
984unconditionally. This is useful to skip large amounts of data that you
985know cannot be matched, so that the C<$accept> or C<$reject> regex do not
986have to start matching from the beginning. This is purely an optimisation
987and is usually worth only when you expect more than a few kilobytes.
988
989Example: expect a http header, which ends at C<\015\012\015\012>. Since we
990expect the header to be very large (it isn't in practise, but...), we use
991a skip regex to skip initial portions. The skip regex is tricky in that
992it only accepts something not ending in either \015 or \012, as these are
993required for the accept regex.
994
995 $handle->push_read (regex =>
996 qr<\015\012\015\012>,
997 undef, # no reject
998 qr<^.*[^\015\012]>,
999 sub { ... });
1000
1001=cut
1002
1003register_read_type regex => sub {
1004 my ($self, $cb, $accept, $reject, $skip) = @_;
1005
1006 my $data;
1007 my $rbuf = \$self->{rbuf};
674 1008
675 sub { 1009 sub {
676 $_[0]{rbuf} =~ s/$eol// or return; 1010 # accept
677 1011 if ($$rbuf =~ $accept) {
678 $cb->($_[0], $1, $2); 1012 $data .= substr $$rbuf, 0, $+[0], "";
1013 $cb->($self, $data);
1014 return 1;
1015 }
679 1 1016
1017 # reject
1018 if ($reject && $$rbuf =~ $reject) {
1019 $self->_error (&Errno::EBADMSG);
1020 }
1021
1022 # skip
1023 if ($skip && $$rbuf =~ $skip) {
1024 $data .= substr $$rbuf, 0, $+[0], "";
1025 }
1026
1027 ()
680 } 1028 }
681}; 1029};
682 1030
683# compatibility with older API
684sub push_read_line {
685 my $self = shift;
686 $self->push_read (line => @_);
687}
688
689sub unshift_read_line {
690 my $self = shift;
691 $self->unshift_read (line => @_);
692}
693
694=item netstring => $cb->($string) 1031=item netstring => $cb->($handle, $string)
695 1032
696A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement). 1033A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
697 1034
698Throws an error with C<$!> set to EBADMSG on format violations. 1035Throws an error with C<$!> set to EBADMSG on format violations.
699 1036
703 my ($self, $cb) = @_; 1040 my ($self, $cb) = @_;
704 1041
705 sub { 1042 sub {
706 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) { 1043 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
707 if ($_[0]{rbuf} =~ /[^0-9]/) { 1044 if ($_[0]{rbuf} =~ /[^0-9]/) {
708 $! = &Errno::EBADMSG; 1045 $self->_error (&Errno::EBADMSG);
709 $self->error;
710 } 1046 }
711 return; 1047 return;
712 } 1048 }
713 1049
714 my $len = $1; 1050 my $len = $1;
717 my $string = $_[1]; 1053 my $string = $_[1];
718 $_[0]->unshift_read (chunk => 1, sub { 1054 $_[0]->unshift_read (chunk => 1, sub {
719 if ($_[1] eq ",") { 1055 if ($_[1] eq ",") {
720 $cb->($_[0], $string); 1056 $cb->($_[0], $string);
721 } else { 1057 } else {
722 $! = &Errno::EBADMSG; 1058 $self->_error (&Errno::EBADMSG);
723 $self->error;
724 } 1059 }
725 }); 1060 });
726 }); 1061 });
727 1062
728 1 1063 1
729 } 1064 }
730}; 1065};
731 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
1109 }
1110};
1111
1112=item json => $cb->($handle, $hash_or_arrayref)
1113
1114Reads a JSON object or array, decodes it and passes it to the callback.
1115
1116If a C<json> object was passed to the constructor, then that will be used
1117for the final decode, otherwise it will create a JSON coder expecting UTF-8.
1118
1119This read type uses the incremental parser available with JSON version
11202.09 (and JSON::XS version 2.2) and above. You have to provide a
1121dependency on your own: this module will load the JSON module, but
1122AnyEvent does not depend on it itself.
1123
1124Since JSON texts are fully self-delimiting, the C<json> read and write
1125types are an ideal simple RPC protocol: just exchange JSON datagrams. See
1126the C<json> write type description, above, for an actual example.
1127
1128=cut
1129
1130register_read_type json => sub {
1131 my ($self, $cb) = @_;
1132
1133 require JSON;
1134
1135 my $data;
1136 my $rbuf = \$self->{rbuf};
1137
1138 my $json = $self->{json} ||= JSON->new->utf8;
1139
1140 sub {
1141 my $ref = $json->incr_parse ($self->{rbuf});
1142
1143 if ($ref) {
1144 $self->{rbuf} = $json->incr_text;
1145 $json->incr_text = "";
1146 $cb->($self, $ref);
1147
1148 1
1149 } else {
1150 $self->{rbuf} = "";
1151 ()
1152 }
1153 }
1154};
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
732=back 1201=back
733 1202
734=item AnyEvent::Handle::register_read_type type => $coderef->($self, $cb, @args) 1203=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args)
735 1204
736This 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>.
737 1206
738Whenever the given C<type> is used, C<push_read> will invoke the code 1207Whenever the given C<type> is used, C<push_read> will invoke the code
739reference with the handle object, the callback and the remaining 1208reference with the handle object, the callback and the remaining
741 1210
742The code reference is supposed to return a callback (usually a closure) 1211The code reference is supposed to return a callback (usually a closure)
743that works as a plain read callback (see C<< ->push_read ($cb) >>). 1212that works as a plain read callback (see C<< ->push_read ($cb) >>).
744 1213
745It should invoke the passed callback when it is done reading (remember to 1214It should invoke the passed callback when it is done reading (remember to
746pass C<$self> as first argument as all other callbacks do that). 1215pass C<$handle> as first argument as all other callbacks do that).
747 1216
748Note that this is a function, and all types registered this way will be 1217Note that this is a function, and all types registered this way will be
749global, so try to use unique names. 1218global, so try to use unique names.
750 1219
751For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, 1220For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>,
754=item $handle->stop_read 1223=item $handle->stop_read
755 1224
756=item $handle->start_read 1225=item $handle->start_read
757 1226
758In 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
759socket. 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
760any queued callbacks will be executed then. To start reading again, call 1229any queued callbacks will be executed then. To start reading again, call
761C<start_read>. 1230C<start_read>.
762 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.
1236
763=cut 1237=cut
764 1238
765sub stop_read { 1239sub stop_read {
766 my ($self) = @_; 1240 my ($self) = @_;
767 1241
768 delete $self->{rw}; 1242 delete $self->{_rw};
769} 1243}
770 1244
771sub start_read { 1245sub start_read {
772 my ($self) = @_; 1246 my ($self) = @_;
773 1247
774 unless ($self->{rw} || $self->{eof}) { 1248 unless ($self->{_rw} || $self->{_eof}) {
775 Scalar::Util::weaken $self; 1249 Scalar::Util::weaken $self;
776 1250
777 $self->{rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub { 1251 $self->{_rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
778 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf}; 1252 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf};
779 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1253 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
780 1254
781 if ($len > 0) { 1255 if ($len > 0) {
1256 $self->{_activity} = AnyEvent->now;
1257
782 $self->{filter_r} 1258 $self->{filter_r}
783 ? $self->{filter_r}->($self, $rbuf) 1259 ? $self->{filter_r}($self, $rbuf)
784 : $self->_drain_rbuf; 1260 : $self->{_in_drain} || $self->_drain_rbuf;
785 1261
786 } elsif (defined $len) { 1262 } elsif (defined $len) {
787 delete $self->{rw}; 1263 delete $self->{_rw};
788 $self->{eof} = 1; 1264 $self->{_eof} = 1;
789 $self->_drain_rbuf; 1265 $self->_drain_rbuf unless $self->{_in_drain};
790 1266
791 } elsif ($! != EAGAIN && $! != EINTR) { 1267 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
792 return $self->error; 1268 return $self->_error ($!, 1);
793 } 1269 }
794 }); 1270 });
795 } 1271 }
796} 1272}
797 1273
798sub _dotls { 1274sub _dotls {
799 my ($self) = @_; 1275 my ($self) = @_;
800 1276
1277 my $buf;
1278
801 if (length $self->{tls_wbuf}) { 1279 if (length $self->{_tls_wbuf}) {
802 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) {
803 substr $self->{tls_wbuf}, 0, $len, ""; 1281 substr $self->{_tls_wbuf}, 0, $len, "";
804 } 1282 }
805 } 1283 }
806 1284
807 if (defined (my $buf = Net::SSLeay::BIO_read ($self->{tls_wbio}))) { 1285 if (length ($buf = Net::SSLeay::BIO_read ($self->{_wbio}))) {
808 $self->{wbuf} .= $buf; 1286 $self->{wbuf} .= $buf;
809 $self->_drain_wbuf; 1287 $self->_drain_wbuf;
810 } 1288 }
811 1289
812 while (defined (my $buf = Net::SSLeay::read ($self->{tls}))) { 1290 while (defined ($buf = Net::SSLeay::read ($self->{tls}))) {
1291 if (length $buf) {
813 $self->{rbuf} .= $buf; 1292 $self->{rbuf} .= $buf;
814 $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 }
815 } 1300 }
816 1301
817 my $err = Net::SSLeay::get_error ($self->{tls}, -1); 1302 my $err = Net::SSLeay::get_error ($self->{tls}, -1);
818 1303
819 if ($err!= Net::SSLeay::ERROR_WANT_READ ()) { 1304 if ($err!= Net::SSLeay::ERROR_WANT_READ ()) {
820 if ($err == Net::SSLeay::ERROR_SYSCALL ()) { 1305 if ($err == Net::SSLeay::ERROR_SYSCALL ()) {
821 $self->error; 1306 return $self->_error ($!, 1);
822 } elsif ($err == Net::SSLeay::ERROR_SSL ()) { 1307 } elsif ($err == Net::SSLeay::ERROR_SSL ()) {
823 $! = &Errno::EIO; 1308 return $self->_error (&Errno::EIO, 1);
824 $self->error;
825 } 1309 }
826 1310
827 # all others are fine for our purposes 1311 # all others are fine for our purposes
828 } 1312 }
829} 1313}
838C<"connect">, C<"accept"> or an existing Net::SSLeay object). 1322C<"connect">, C<"accept"> or an existing Net::SSLeay object).
839 1323
840The second argument is the optional C<Net::SSLeay::CTX> object that is 1324The second argument is the optional C<Net::SSLeay::CTX> object that is
841used when AnyEvent::Handle has to create its own TLS connection object. 1325used when AnyEvent::Handle has to create its own TLS connection object.
842 1326
843=cut 1327The TLS connection object will end up in C<< $handle->{tls} >> after this
1328call and can be used or changed to your liking. Note that the handshake
1329might have already started when this function returns.
844 1330
845# TODO: maybe document... 1331=cut
1332
846sub starttls { 1333sub starttls {
847 my ($self, $ssl, $ctx) = @_; 1334 my ($self, $ssl, $ctx) = @_;
848 1335
849 $self->stoptls; 1336 $self->stoptls;
850 1337
862 # but the openssl maintainers basically said: "trust us, it just works". 1349 # but the openssl maintainers basically said: "trust us, it just works".
863 # (unfortunately, we have to hardcode constants because the abysmally misdesigned 1350 # (unfortunately, we have to hardcode constants because the abysmally misdesigned
864 # and mismaintained ssleay-module doesn't even offer them). 1351 # and mismaintained ssleay-module doesn't even offer them).
865 # http://www.mail-archive.com/openssl-dev@openssl.org/msg22420.html 1352 # http://www.mail-archive.com/openssl-dev@openssl.org/msg22420.html
866 Net::SSLeay::CTX_set_mode ($self->{tls}, 1353 Net::SSLeay::CTX_set_mode ($self->{tls},
867 (eval { Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1) 1354 (eval { local $SIG{__DIE__}; Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1)
868 | (eval { Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2)); 1355 | (eval { local $SIG{__DIE__}; Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2));
869 1356
870 $self->{tls_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ()); 1357 $self->{_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
871 $self->{tls_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ()); 1358 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
872 1359
873 Net::SSLeay::set_bio ($ssl, $self->{tls_rbio}, $self->{tls_wbio}); 1360 Net::SSLeay::set_bio ($ssl, $self->{_rbio}, $self->{_wbio});
874 1361
875 $self->{filter_w} = sub { 1362 $self->{filter_w} = sub {
876 $_[0]{tls_wbuf} .= ${$_[1]}; 1363 $_[0]{_tls_wbuf} .= ${$_[1]};
877 &_dotls; 1364 &_dotls;
878 }; 1365 };
879 $self->{filter_r} = sub { 1366 $self->{filter_r} = sub {
880 Net::SSLeay::BIO_write ($_[0]{tls_rbio}, ${$_[1]}); 1367 Net::SSLeay::BIO_write ($_[0]{_rbio}, ${$_[1]});
881 &_dotls; 1368 &_dotls;
882 }; 1369 };
883} 1370}
884 1371
885=item $handle->stoptls 1372=item $handle->stoptls
891 1378
892sub stoptls { 1379sub stoptls {
893 my ($self) = @_; 1380 my ($self) = @_;
894 1381
895 Net::SSLeay::free (delete $self->{tls}) if $self->{tls}; 1382 Net::SSLeay::free (delete $self->{tls}) if $self->{tls};
1383
896 delete $self->{tls_rbio}; 1384 delete $self->{_rbio};
897 delete $self->{tls_wbio}; 1385 delete $self->{_wbio};
898 delete $self->{tls_wbuf}; 1386 delete $self->{_tls_wbuf};
899 delete $self->{filter_r}; 1387 delete $self->{filter_r};
900 delete $self->{filter_w}; 1388 delete $self->{filter_w};
901} 1389}
902 1390
903sub DESTROY { 1391sub DESTROY {
904 my $self = shift; 1392 my $self = shift;
905 1393
906 $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 }
907} 1417}
908 1418
909=item AnyEvent::Handle::TLS_CTX 1419=item AnyEvent::Handle::TLS_CTX
910 1420
911This function creates and returns the Net::SSLeay::CTX object used by 1421This function creates and returns the Net::SSLeay::CTX object used by
941 } 1451 }
942} 1452}
943 1453
944=back 1454=back
945 1455
1456=head1 SUBCLASSING AnyEvent::Handle
1457
1458In many cases, you might want to subclass AnyEvent::Handle.
1459
1460To make this easier, a given version of AnyEvent::Handle uses these
1461conventions:
1462
1463=over 4
1464
1465=item * all constructor arguments become object members.
1466
1467At least initially, when you pass a C<tls>-argument to the constructor it
1468will end up in C<< $handle->{tls} >>. Those members might be changed or
1469mutated later on (for example C<tls> will hold the TLS connection object).
1470
1471=item * other object member names are prefixed with an C<_>.
1472
1473All object members not explicitly documented (internal use) are prefixed
1474with an underscore character, so the remaining non-C<_>-namespace is free
1475for use for subclasses.
1476
1477=item * all members not documented here and not prefixed with an underscore
1478are free to use in subclasses.
1479
1480Of course, new versions of AnyEvent::Handle may introduce more "public"
1481member variables, but thats just life, at least it is documented.
1482
1483=back
1484
946=head1 AUTHOR 1485=head1 AUTHOR
947 1486
948Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>. 1487Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
949 1488
950=cut 1489=cut

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines