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.4 by elmex, Sun Apr 27 20:20:20 2008 UTC vs.
Revision 1.80 by root, Sun Jul 27 08:43:32 2008 UTC

1package AnyEvent::Handle; 1package AnyEvent::Handle;
2 2
3use warnings; 3no warnings;
4use strict; 4use strict qw(subs vars);
5 5
6use AnyEvent; 6use AnyEvent ();
7use IO::Handle; 7use AnyEvent::Util qw(WSAEWOULDBLOCK);
8use Scalar::Util ();
9use Carp ();
10use Fcntl ();
8use Errno qw/EAGAIN EINTR/; 11use Errno qw(EAGAIN EINTR);
9 12
10=head1 NAME 13=head1 NAME
11 14
12AnyEvent::Handle - non-blocking I/O on filehandles via AnyEvent 15AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
13 16
14=head1 VERSION
15
16Version 0.01
17
18=cut 17=cut
19 18
20our $VERSION = '0.01'; 19our $VERSION = 4.22;
21 20
22=head1 SYNOPSIS 21=head1 SYNOPSIS
23 22
24 use AnyEvent; 23 use AnyEvent;
25 use AnyEvent::Handle; 24 use AnyEvent::Handle;
26 25
27 my $cv = AnyEvent->condvar; 26 my $cv = AnyEvent->condvar;
28 27
29 my $ae_fh = AnyEvent::Handle->new (fh => \*STDIN); 28 my $handle =
30
31 $ae_fh->on_eof (sub { $cv->broadcast });
32
33 $ae_fh->readlines (sub {
34 my ($ae_fh, @lines) = @_;
35 for (@lines) {
36 chomp;
37 print "Line: $_";
38 }
39 });
40
41 # or use the constructor to pass the callback:
42
43 my $ae_fh2 =
44 AnyEvent::Handle->new ( 29 AnyEvent::Handle->new (
45 fh => \*STDIN, 30 fh => \*STDIN,
46 on_eof => sub { 31 on_eof => sub {
47 $cv->broadcast; 32 $cv->broadcast;
48 }, 33 },
34 );
35
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;
47
48=head1 DESCRIPTION
49
50This module is a helper module to make it easier to do event-based I/O on
51filehandles. For utility functions for doing non-blocking connects and accepts
52on sockets see L<AnyEvent::Util>.
53
54In the following, when the documentation refers to of "bytes" then this
55means characters. As sysread and syswrite are used for all I/O, their
56treatment of characters applies to this module as well.
57
58All callbacks will be invoked with the handle object as their first
59argument.
60
61=head1 METHODS
62
63=over 4
64
65=item B<new (%args)>
66
67The constructor supports these arguments (all as key => value pairs).
68
69=over 4
70
71=item fh => $filehandle [MANDATORY]
72
73The filehandle this L<AnyEvent::Handle> object will operate on.
74
75NOTE: The filehandle will be set to non-blocking (using
76AnyEvent::Util::fh_nonblocking).
77
78=item on_eof => $cb->($handle)
79
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.
83
84While not mandatory, it is I<highly> recommended to set an eof callback,
85otherwise you might end up with a closed socket while you are still
86waiting for data.
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
91=item on_error => $cb->($handle, $fatal)
92
93This is the error callback, which is called when, well, some error
94occured, such as not being able to resolve the hostname, failure to
95connect or a read error.
96
97Some errors are fatal (which is indicated by C<$fatal> being true). On
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.
102
103On callback entrance, the value of C<$!> contains the operating system
104error (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT> or C<EBADMSG>).
105
106While not mandatory, it is I<highly> recommended to set this callback, as
107you will not be notified of errors otherwise. The default simply calls
108C<croak>.
109
110=item on_read => $cb->($handle)
111
112This sets the default read callback, which is called when data arrives
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).
116
117To access (and remove data from) the read buffer, use the C<< ->rbuf >>
118method or access the C<$handle->{rbuf}> member directly.
119
120When an EOF condition is detected then AnyEvent::Handle will first try to
121feed all the remaining data to the queued callbacks and C<on_read> before
122calling the C<on_eof> callback. If no progress can be made, then a fatal
123error will be raised (with C<$!> set to C<EPIPE>).
124
125=item on_drain => $cb->($handle)
126
127This sets the callback that is called when the write buffer becomes empty
128(or when the callback is set and the buffer is empty already).
129
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.
157
158=item rbuf_max => <bytes>
159
160If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
161when the read buffer ever (strictly) exceeds this size. This is useful to
162avoid denial-of-service attacks.
163
164For example, a server accepting connections from untrusted sources should
165be configured to accept only so-and-so much data that it cannot act on
166(for example, when expecting a line, an attacker could send an unlimited
167amount of data without a callback ever being called as long as the line
168isn't finished).
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
194=item read_size => <bytes>
195
196The default read block size (the amount of bytes this module will try to read
197during each (loop iteration). Default: C<8192>.
198
199=item low_water_mark => <bytes>
200
201Sets the amount of bytes (default: C<0>) that make up an "empty" write
202buffer: If the write reaches this size or gets even samller it is
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.
215
216=item tls => "accept" | "connect" | Net::SSLeay::SSL object
217
218When this parameter is given, it enables TLS (SSL) mode, that means it
219will start making tls handshake and will transparently encrypt/decrypt
220data.
221
222TLS mode requires Net::SSLeay to be installed (it will be loaded
223automatically when you try to create a TLS handle).
224
225For the TLS server side, use C<accept>, and for the TLS client side of a
226connection, use C<connect> mode.
227
228You can also provide your own TLS connection object, but you have
229to make sure that you call either C<Net::SSLeay::set_connect_state>
230or C<Net::SSLeay::set_accept_state> on it before you pass it to
231AnyEvent::Handle.
232
233See the C<starttls> method if you need to start TLS negotiation later.
234
235=item tls_ctx => $ssl_ctx
236
237Use the given Net::SSLeay::CTX object to create the new TLS connection
238(unless a connection object was specified directly). If this parameter is
239missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>.
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
257=back
258
259=cut
260
261sub new {
262 my $class = shift;
263
264 my $self = bless { @_ }, $class;
265
266 $self->{fh} or Carp::croak "mandatory argument fh is missing";
267
268 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
269
270 if ($self->{tls}) {
271 require Net::SSLeay;
272 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
273 }
274
275 $self->{_activity} = AnyEvent->now;
276 $self->_timeout;
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
281 $self->start_read
282 if $self->{on_read};
283
284 $self
285}
286
287sub _shutdown {
288 my ($self) = @_;
289
290 delete $self->{_tw};
291 delete $self->{_rw};
292 delete $self->{_ww};
293 delete $self->{fh};
294
295 $self->stoptls;
296}
297
298sub _error {
299 my ($self, $errno, $fatal) = @_;
300
301 $self->_shutdown
302 if $fatal;
303
304 $! = $errno;
305
306 if ($self->{on_error}) {
307 $self->{on_error}($self, $fatal);
308 } else {
309 Carp::croak "AnyEvent::Handle uncaught error: $!";
310 }
311}
312
313=item $fh = $handle->fh
314
315This method returns the file handle of the L<AnyEvent::Handle> object.
316
317=cut
318
319sub fh { $_[0]{fh} }
320
321=item $handle->on_error ($cb)
322
323Replace the current C<on_error> callback (see the C<on_error> constructor argument).
324
325=cut
326
327sub on_error {
328 $_[0]{on_error} = $_[1];
329}
330
331=item $handle->on_eof ($cb)
332
333Replace the current C<on_eof> callback (see the C<on_eof> constructor argument).
334
335=cut
336
337sub on_eof {
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 }
429}
430
431#############################################################################
432
433=back
434
435=head2 WRITE QUEUE
436
437AnyEvent::Handle manages two queues per handle, one for writing and one
438for reading.
439
440The write queue is very simple: you can add data to its end, and
441AnyEvent::Handle will automatically try to get rid of it for you.
442
443When data could be written and the write buffer is shorter then the low
444water mark, the C<on_drain> callback will be invoked.
445
446=over 4
447
448=item $handle->on_drain ($cb)
449
450Sets the C<on_drain> callback or clears it (see the description of
451C<on_drain> in the constructor).
452
453=cut
454
455sub on_drain {
456 my ($self, $cb) = @_;
457
458 $self->{on_drain} = $cb;
459
460 $cb->($self)
461 if $cb && $self->{low_water_mark} >= length $self->{wbuf};
462}
463
464=item $handle->push_write ($data)
465
466Queues the given scalar to be written. You can push as much data as you
467want (only limited by the available memory), as C<AnyEvent::Handle>
468buffers it independently of the kernel.
469
470=cut
471
472sub _drain_wbuf {
473 my ($self) = @_;
474
475 if (!$self->{_ww} && length $self->{wbuf}) {
476
477 Scalar::Util::weaken $self;
478
479 my $cb = sub {
480 my $len = syswrite $self->{fh}, $self->{wbuf};
481
482 if ($len >= 0) {
483 substr $self->{wbuf}, 0, $len, "";
484
485 $self->{_activity} = AnyEvent->now;
486
487 $self->{on_drain}($self)
488 if $self->{low_water_mark} >= length $self->{wbuf}
489 && $self->{on_drain};
490
491 delete $self->{_ww} unless length $self->{wbuf};
492 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
493 $self->_error ($!, 1);
494 }
495 };
496
497 # try to write data immediately
498 $cb->() unless $self->{autocork};
499
500 # if still data left in wbuf, we need to poll
501 $self->{_ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb)
502 if length $self->{wbuf};
503 };
504}
505
506our %WH;
507
508sub register_write_type($$) {
509 $WH{$_[0]} = $_[1];
510}
511
512sub push_write {
513 my $self = shift;
514
515 if (@_ > 1) {
516 my $type = shift;
517
518 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write")
519 ->($self, @_);
520 }
521
522 if ($self->{filter_w}) {
523 $self->{filter_w}($self, \$_[0]);
524 } else {
525 $self->{wbuf} .= $_[0];
526 $self->_drain_wbuf;
527 }
528}
529
530=item $handle->push_write (type => @args)
531
532Instead of formatting your data yourself, you can also let this module do
533the job by specifying a type and type-specific arguments.
534
535Predefined types are (if you have ideas for additional types, feel free to
536drop by and tell us):
537
538=over 4
539
540=item netstring => $string
541
542Formats the given value as netstring
543(http://cr.yp.to/proto/netstrings.txt, this is not a recommendation to use them).
544
545=cut
546
547register_write_type netstring => sub {
548 my ($self, $string) = @_;
549
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
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
626=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args)
627
628This function (not method) lets you add your own types to C<push_write>.
629Whenever the given C<type> is used, C<push_write> will invoke the code
630reference with the handle object and the remaining arguments.
631
632The code reference is supposed to return a single octet string that will
633be appended to the write buffer.
634
635Note that this is a function, and all types registered this way will be
636global, so try to use unique names.
637
638=cut
639
640#############################################################################
641
642=back
643
644=head2 READ QUEUE
645
646AnyEvent::Handle manages two queues per handle, one for writing and one
647for reading.
648
649The read queue is more complex than the write queue. It can be used in two
650ways, the "simple" way, using only C<on_read> and the "complex" way, using
651a queue.
652
653In the simple case, you just install an C<on_read> callback and whenever
654new data arrives, it will be called. You can then remove some data (if
655enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna
656leave the data there if you want to accumulate more (e.g. when only a
657partial message has been received so far).
658
659In the more complex case, you want to queue multiple callbacks. In this
660case, AnyEvent::Handle will call the first queued callback each time new
661data arrives (also the first time it is queued) and removes it when it has
662done its job (see C<push_read>, below).
663
664This way you can, for example, push three line-reads, followed by reading
665a chunk of data, and AnyEvent::Handle will execute them in order.
666
667Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
668the specified number of bytes which give an XML datagram.
669
670 # in the default state, expect some header bytes
671 $handle->on_read (sub {
672 # some data is here, now queue the length-header-read (4 octets)
673 shift->unshift_read (chunk => 4, sub {
674 # header arrived, decode
675 my $len = unpack "N", $_[1];
676
677 # now read the payload
678 shift->unshift_read (chunk => $len, sub {
679 my $xml = $_[1];
680 # handle xml
681 });
682 });
683 });
684
685Example 2: Implement a client for a protocol that replies either with "OK"
686and another line or "ERROR" for the first request that is sent, and 64
687bytes for the second request. Due to the availability of a queue, we can
688just pipeline sending both requests and manipulate the queue as necessary
689in the callbacks.
690
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"
696 $handle->push_write ("request 1\015\012");
697
698 # we expect "ERROR" or "OK" as response, so push a line read
699 $handle->push_read (line => sub {
700 # if we got an "OK", we have to _prepend_ another line,
701 # so it will be read before the second request reads its 64 bytes
702 # which are already in the queue when this callback is called
703 # we don't do this in case we got an error
704 if ($_[1] eq "OK") {
49 on_readline => sub { 705 $_[0]->unshift_read (line => sub {
50 my ($ae_fh, @lines) = @_; 706 my $response = $_[1];
51 for (@lines) { 707 ...
52 chomp; 708 });
53 print "Line: $_"; 709 }
710 });
711
712 # request two, simply returns 64 octets
713 $handle->push_write ("request 2\015\012");
714
715 # simply read 64 bytes, always
716 $handle->push_read (chunk => 64, sub {
717 my $response = $_[1];
718 ...
719 });
720
721=over 4
722
723=cut
724
725sub _drain_rbuf {
726 my ($self) = @_;
727
728 local $self->{_in_drain} = 1;
729
730 if (
731 defined $self->{rbuf_max}
732 && $self->{rbuf_max} < length $self->{rbuf}
733 ) {
734 return $self->_error (&Errno::ENOSPC, 1);
735 }
736
737 while () {
738 my $len = length $self->{rbuf};
739
740 if (my $cb = shift @{ $self->{_queue} }) {
741 unless ($cb->($self)) {
742 if ($self->{_eof}) {
743 # no progress can be made (not enough data and no data forthcoming)
744 $self->_error (&Errno::EPIPE, 1), last;
54 } 745 }
746
747 unshift @{ $self->{_queue} }, $cb;
748 last;
55 } 749 }
56 );
57
58 $cv->wait;
59
60=head1 DESCRIPTION
61
62This module is a helper module to make it easier to do non-blocking I/O
63on filehandles (and sockets, see L<AnyEvent::Socket>).
64
65The event loop is provided by L<AnyEvent>.
66
67=head1 METHODS
68
69=over 4
70
71=item B<new (%args)>
72
73The constructor has these arguments:
74
75=over 4
76
77=item fh => $filehandle
78
79The filehandle this L<AnyEvent::Handle> object will operate on.
80
81NOTE: The filehandle will be set to non-blocking.
82
83=item read_block_size => $size
84
85The default read block size use for reads via the C<on_read>
86method.
87
88=item on_read => $cb
89
90=item on_eof => $cb
91
92=item on_error => $cb
93
94These are shortcuts, that will call the corresponding method and set the callback to C<$cb>.
95
96=item on_readline => $cb
97
98The C<readlines> method is called with the default seperator and C<$cb> as callback
99for you.
100
101=back
102
103=cut
104
105sub new {
106 my $this = shift;
107 my $class = ref($this) || $this;
108 my $self = {
109 read_block_size => 4096,
110 rbuf => '',
111 @_
112 };
113 bless $self, $class;
114
115 $self->{fh}->blocking (0) if $self->{fh};
116
117 if ($self->{on_read}) {
118 $self->on_read ($self->{on_read});
119
120 } elsif ($self->{on_readline}) { 750 } elsif ($self->{on_read}) {
121 $self->readlines ($self->{on_readline}); 751 last unless $len;
122 752
753 $self->{on_read}($self);
754
755 if (
756 $len == length $self->{rbuf} # if no data has been consumed
757 && !@{ $self->{_queue} } # and the queue is still empty
758 && $self->{on_read} # but we still have on_read
759 ) {
760 # no further data will arrive
761 # so no progress can be made
762 $self->_error (&Errno::EPIPE, 1), last
763 if $self->{_eof};
764
765 last; # more data might arrive
766 }
767 } else {
768 # read side becomes idle
769 delete $self->{_rw};
770 last;
771 }
772 }
773
123 } elsif ($self->{on_eof}) { 774 if ($self->{_eof}) {
124 $self->on_eof ($self->{on_eof});
125
126 } elsif ($self->{on_error}) { 775 if ($self->{on_eof}) {
127 $self->on_eof ($self->{on_error}); 776 $self->{on_eof}($self)
777 } else {
778 $self->_error (0, 1);
779 }
128 } 780 }
129 781
130 return $self 782 # may need to restart read watcher
783 unless ($self->{_rw}) {
784 $self->start_read
785 if $self->{on_read} || @{ $self->{_queue} };
786 }
131} 787}
132 788
133=item B<fh> 789=item $handle->on_read ($cb)
134 790
135This method returns the filehandle of the L<AnyEvent::Handle> object. 791This replaces the currently set C<on_read> callback, or clears it (when
136 792the new callback is C<undef>). See the description of C<on_read> in the
137=cut 793constructor.
138
139sub fh { $_[0]->{fh} }
140
141=item B<on_read ($callback)>
142
143This method installs a C<$callback> that will be called
144when new data arrived. You can access the read buffer via the C<rbuf>
145method (see below).
146
147The first argument of the C<$callback> will be the L<AnyEvent::Handle> object.
148 794
149=cut 795=cut
150 796
151sub on_read { 797sub on_read {
152 my ($self, $cb) = @_; 798 my ($self, $cb) = @_;
799
153 $self->{on_read} = $cb; 800 $self->{on_read} = $cb;
801 $self->_drain_rbuf if $cb && !$self->{_in_drain};
802}
154 803
155 unless (defined $self->{on_read}) { 804=item $handle->rbuf
156 delete $self->{on_read_w}; 805
806Returns the read buffer (as a modifiable lvalue).
807
808You can access the read buffer directly as the C<< ->{rbuf} >> member, if
809you want.
810
811NOTE: The read buffer should only be used or modified if the C<on_read>,
812C<push_read> or C<unshift_read> methods are used. The other read methods
813automatically manage the read buffer.
814
815=cut
816
817sub rbuf : lvalue {
818 $_[0]{rbuf}
819}
820
821=item $handle->push_read ($cb)
822
823=item $handle->unshift_read ($cb)
824
825Append the given callback to the end of the queue (C<push_read>) or
826prepend it (C<unshift_read>).
827
828The callback is called each time some additional read data arrives.
829
830It must check whether enough data is in the read buffer already.
831
832If not enough data is available, it must return the empty list or a false
833value, in which case it will be called repeatedly until enough data is
834available (or an error condition is detected).
835
836If enough data was available, then the callback must remove all data it is
837interested in (which can be none at all) and return a true value. After returning
838true, it will be removed from the queue.
839
840=cut
841
842our %RH;
843
844sub register_read_type($$) {
845 $RH{$_[0]} = $_[1];
846}
847
848sub push_read {
849 my $self = shift;
850 my $cb = pop;
851
852 if (@_) {
853 my $type = shift;
854
855 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read")
856 ->($self, $cb, @_);
857 }
858
859 push @{ $self->{_queue} }, $cb;
860 $self->_drain_rbuf unless $self->{_in_drain};
861}
862
863sub unshift_read {
864 my $self = shift;
865 my $cb = pop;
866
867 if (@_) {
868 my $type = shift;
869
870 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
871 ->($self, $cb, @_);
872 }
873
874
875 unshift @{ $self->{_queue} }, $cb;
876 $self->_drain_rbuf unless $self->{_in_drain};
877}
878
879=item $handle->push_read (type => @args, $cb)
880
881=item $handle->unshift_read (type => @args, $cb)
882
883Instead of providing a callback that parses the data itself you can chose
884between a number of predefined parsing formats, for chunks of data, lines
885etc.
886
887Predefined types are (if you have ideas for additional types, feel free to
888drop by and tell us):
889
890=over 4
891
892=item chunk => $octets, $cb->($handle, $data)
893
894Invoke the callback only once C<$octets> bytes have been read. Pass the
895data read to the callback. The callback will never be called with less
896data.
897
898Example: read 2 bytes.
899
900 $handle->push_read (chunk => 2, sub {
901 warn "yay ", unpack "H*", $_[1];
902 });
903
904=cut
905
906register_read_type chunk => sub {
907 my ($self, $cb, $len) = @_;
908
909 sub {
910 $len <= length $_[0]{rbuf} or return;
911 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
912 1
913 }
914};
915
916=item line => [$eol, ]$cb->($handle, $line, $eol)
917
918The callback will be called only once a full line (including the end of
919line marker, C<$eol>) has been read. This line (excluding the end of line
920marker) will be passed to the callback as second argument (C<$line>), and
921the end of line marker as the third argument (C<$eol>).
922
923The end of line marker, C<$eol>, can be either a string, in which case it
924will be interpreted as a fixed record end marker, or it can be a regex
925object (e.g. created by C<qr>), in which case it is interpreted as a
926regular expression.
927
928The end of line marker argument C<$eol> is optional, if it is missing (NOT
929undef), then C<qr|\015?\012|> is used (which is good for most internet
930protocols).
931
932Partial lines at the end of the stream will never be returned, as they are
933not marked by the end of line marker.
934
935=cut
936
937register_read_type line => sub {
938 my ($self, $cb, $eol) = @_;
939
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 {
949 $eol = quotemeta $eol unless ref $eol;
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};
1008
1009 sub {
1010 # accept
1011 if ($$rbuf =~ $accept) {
1012 $data .= substr $$rbuf, 0, $+[0], "";
1013 $cb->($self, $data);
157 return; 1014 return 1;
1015 }
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 ()
158 } 1028 }
159 1029};
160 $self->{on_read_w} = 1030
161 AnyEvent->io (poll => 'r', fh => $self->{fh}, cb => sub { 1031=item netstring => $cb->($handle, $string)
162 #d# warn "READ:[$self->{read_size}] $self->{read_block_size} : ".length ($self->{rbuf})."\n"; 1032
163 my $rbuf_len = length $self->{rbuf}; 1033A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
164 my $l; 1034
165 if (defined $self->{read_size}) { 1035Throws an error with C<$!> set to EBADMSG on format violations.
166 $l = sysread $self->{fh}, $self->{rbuf}, 1036
167 ($self->{read_size} - $rbuf_len), $rbuf_len; 1037=cut
168 } else { 1038
169 $l = sysread $self->{fh}, $self->{rbuf}, $self->{read_block_size}, $rbuf_len; 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);
170 } 1046 }
171 #d# warn "READL $l [$self->{rbuf}]\n"; 1047 return;
1048 }
172 1049
173 if (not defined $l) { 1050 my $len = $1;
174 return if $! == EAGAIN || $! == EINTR;
175 $self->{on_error}->($self) if $self->{on_error};
176 delete $self->{on_read_w};
177 1051
178 } elsif ($l == 0) { 1052 $self->unshift_read (chunk => $len, sub {
179 $self->{on_eof}->($self) if $self->{on_eof}; 1053 my $string = $_[1];
180 delete $self->{on_read_w}; 1054 $_[0]->unshift_read (chunk => 1, sub {
181 1055 if ($_[1] eq ",") {
1056 $cb->($_[0], $string);
182 } else { 1057 } else {
183 $self->{on_read}->($self); 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
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
1201=back
1202
1203=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args)
1204
1205This function (not method) lets you add your own types to C<push_read>.
1206
1207Whenever the given C<type> is used, C<push_read> will invoke the code
1208reference with the handle object, the callback and the remaining
1209arguments.
1210
1211The code reference is supposed to return a callback (usually a closure)
1212that works as a plain read callback (see C<< ->push_read ($cb) >>).
1213
1214It should invoke the passed callback when it is done reading (remember to
1215pass C<$handle> as first argument as all other callbacks do that).
1216
1217Note that this is a function, and all types registered this way will be
1218global, so try to use unique names.
1219
1220For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>,
1221search for C<register_read_type>)).
1222
1223=item $handle->stop_read
1224
1225=item $handle->start_read
1226
1227In rare cases you actually do not want to read anything from the
1228socket. In this case you can call C<stop_read>. Neither C<on_read> nor
1229any queued callbacks will be executed then. To start reading again, call
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.
1236
1237=cut
1238
1239sub stop_read {
1240 my ($self) = @_;
1241
1242 delete $self->{_rw};
1243}
1244
1245sub start_read {
1246 my ($self) = @_;
1247
1248 unless ($self->{_rw} || $self->{_eof}) {
1249 Scalar::Util::weaken $self;
1250
1251 $self->{_rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
1252 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf};
1253 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
1254
1255 if ($len > 0) {
1256 $self->{_activity} = AnyEvent->now;
1257
1258 $self->{filter_r}
1259 ? $self->{filter_r}($self, $rbuf)
1260 : $self->{_in_drain} || $self->_drain_rbuf;
1261
1262 } elsif (defined $len) {
1263 delete $self->{_rw};
1264 $self->{_eof} = 1;
1265 $self->_drain_rbuf unless $self->{_in_drain};
1266
1267 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
1268 return $self->_error ($!, 1);
184 } 1269 }
185 }); 1270 });
186}
187
188=item B<on_error ($callback)>
189
190Whenever a read or write operation resulted in an error the C<$callback>
191will be called.
192
193The first argument of C<$callback> will be the L<AnyEvent::Handle> object itself.
194The error is given as errno in C<$!>.
195
196=cut
197
198sub on_error {
199 $_[0]->{on_error} = $_[1];
200}
201
202=item B<on_eof ($callback)>
203
204Installs the C<$callback> that will be called when the end of file is
205encountered in a read operation this C<$callback> will be called. The first
206argument will be the L<AnyEvent::Handle> object itself.
207
208=cut
209
210sub on_eof {
211 $_[0]->{on_eof} = $_[1];
212}
213
214=item B<rbuf>
215
216Returns a reference to the read buffer.
217
218NOTE: The read buffer should only be used or modified if the C<on_read>
219method is used directly. The C<read> and C<readlines> methods will provide
220the read data to their callbacks.
221
222=cut
223
224sub rbuf : lvalue {
225 $_[0]->{rbuf}
226}
227
228=item B<read ($len, $callback)>
229
230Will read exactly C<$len> bytes from the filehandle and call the C<$callback>
231if done so. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
232object itself and the second argument the read data.
233
234NOTE: This method will override any callbacks installed via the C<on_read> method.
235
236=cut
237
238sub read {
239 my ($self, $len, $cb) = @_;
240
241 $self->{read_cb} = $cb;
242 my $old_blk_size = $self->{read_block_size};
243 $self->{read_block_size} = $len;
244
245 $self->on_read (sub {
246 #d# warn "OFOFO $len || ".length($_[0]->{rbuf})."||\n";
247
248 if ($len == length $_[0]->{rbuf}) {
249 $_[0]->{read_block_size} = $old_blk_size;
250 $_[0]->on_read (undef);
251 $_[0]->{read_cb}->($_[0], (substr $self->{rbuf}, 0, $len, ''));
252 }
253 }); 1271 }
254} 1272}
255 1273
256=item B<readlines ($callback)> 1274sub _dotls {
257
258=item B<readlines ($sep, $callback)>
259
260This method will read lines from the filehandle, seperated by C<$sep> or C<"\n">
261if C<$sep> is not provided. C<$sep> will be used as part of a regex, so it can be
262a regex itself and won't be quoted!
263
264The C<$callback> will be called when at least one
265line could be read. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
266object itself and the rest of the arguments will be the read lines.
267
268NOTE: This method will override any callbacks installed via the C<on_read> method.
269
270=cut
271
272sub readlines {
273 my ($self, $NL, $cb) = @_;
274
275 if (ref $NL) {
276 $cb = $NL;
277 $NL = "\n";
278 }
279
280 $self->{on_readline} = $cb;
281
282 $self->on_read (sub {
283 my @lines;
284 push @lines, $1 while $_[0]->{rbuf} =~ s/(.*)$NL//;
285 $self->{on_readline}->($_[0], @lines);
286 });
287}
288
289=item B<write ($data)>
290
291=item B<write ($callback)>
292
293=item B<write ($data, $callback)>
294
295This method will write C<$data> to the filehandle and call the C<$callback>
296afterwards. If only C<$callback> is provided it will be called when the
297write buffer becomes empty the next time (or immediately if it already is empty).
298
299=cut
300
301sub write {
302 my ($self, $data, $cb) = @_;
303 if (ref $data) { $cb = $data; undef $data }
304 push @{$self->{write_bufs}}, [$data, $cb];
305 $self->_check_writer;
306}
307
308sub _check_writer {
309 my ($self) = @_; 1275 my ($self) = @_;
310 1276
311 if ($self->{write_w}) { 1277 my $buf;
312 unless ($self->{write_cb}) { 1278
313 while (@{$self->{write_bufs}} && not defined $self->{write_bufs}->[0]->[1]) { 1279 if (length $self->{_tls_wbuf}) {
314 my $wba = shift @{$self->{write_bufs}}; 1280 while ((my $len = Net::SSLeay::write ($self->{tls}, $self->{_tls_wbuf})) > 0) {
315 $self->{wbuf} .= $wba->[0]; 1281 substr $self->{_tls_wbuf}, 0, $len, "";
316 } 1282 }
317 } 1283 }
1284
1285 if (length ($buf = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1286 $self->{wbuf} .= $buf;
1287 $self->_drain_wbuf;
1288 }
1289
1290 while (defined ($buf = Net::SSLeay::read ($self->{tls}))) {
1291 if (length $buf) {
1292 $self->{rbuf} .= $buf;
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;
318 return; 1298 return;
1299 }
1300 }
1301
1302 my $err = Net::SSLeay::get_error ($self->{tls}, -1);
1303
1304 if ($err!= Net::SSLeay::ERROR_WANT_READ ()) {
1305 if ($err == Net::SSLeay::ERROR_SYSCALL ()) {
1306 return $self->_error ($!, 1);
1307 } elsif ($err == Net::SSLeay::ERROR_SSL ()) {
1308 return $self->_error (&Errno::EIO, 1);
1309 }
1310
1311 # all others are fine for our purposes
1312 }
1313}
1314
1315=item $handle->starttls ($tls[, $tls_ctx])
1316
1317Instead of starting TLS negotiation immediately when the AnyEvent::Handle
1318object is created, you can also do that at a later time by calling
1319C<starttls>.
1320
1321The first argument is the same as the C<tls> constructor argument (either
1322C<"connect">, C<"accept"> or an existing Net::SSLeay object).
1323
1324The second argument is the optional C<Net::SSLeay::CTX> object that is
1325used when AnyEvent::Handle has to create its own TLS connection object.
1326
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.
1330
1331=cut
1332
1333sub starttls {
1334 my ($self, $ssl, $ctx) = @_;
1335
1336 $self->stoptls;
1337
1338 if ($ssl eq "accept") {
1339 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
1340 Net::SSLeay::set_accept_state ($ssl);
1341 } elsif ($ssl eq "connect") {
1342 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
1343 Net::SSLeay::set_connect_state ($ssl);
1344 }
1345
1346 $self->{tls} = $ssl;
1347
1348 # basically, this is deep magic (because SSL_read should have the same issues)
1349 # but the openssl maintainers basically said: "trust us, it just works".
1350 # (unfortunately, we have to hardcode constants because the abysmally misdesigned
1351 # and mismaintained ssleay-module doesn't even offer them).
1352 # http://www.mail-archive.com/openssl-dev@openssl.org/msg22420.html
1353 Net::SSLeay::CTX_set_mode ($self->{tls},
1354 (eval { local $SIG{__DIE__}; Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1)
1355 | (eval { local $SIG{__DIE__}; Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2));
1356
1357 $self->{_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
1358 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
1359
1360 Net::SSLeay::set_bio ($ssl, $self->{_rbio}, $self->{_wbio});
1361
1362 $self->{filter_w} = sub {
1363 $_[0]{_tls_wbuf} .= ${$_[1]};
1364 &_dotls;
319 } 1365 };
320 1366 $self->{filter_r} = sub {
321 my $wba = shift @{$self->{write_bufs}} 1367 Net::SSLeay::BIO_write ($_[0]{_rbio}, ${$_[1]});
322 or return; 1368 &_dotls;
323
324 unless (defined $wba->[0]) {
325 $wba->[1]->($self) if $wba->[1];
326 $self->_check_writer;
327 return;
328 } 1369 };
1370}
329 1371
330 $self->{wbuf} = $wba->[0]; 1372=item $handle->stoptls
331 $self->{write_cb} = $wba->[1];
332 1373
333 $self->{write_w} = 1374Destroys the SSL connection, if any. Partial read or write data will be
334 AnyEvent->io (poll => 'w', fh => $self->{fh}, cb => sub { 1375lost.
1376
1377=cut
1378
1379sub stoptls {
1380 my ($self) = @_;
1381
1382 Net::SSLeay::free (delete $self->{tls}) if $self->{tls};
1383
1384 delete $self->{_rbio};
1385 delete $self->{_wbio};
1386 delete $self->{_tls_wbuf};
1387 delete $self->{filter_r};
1388 delete $self->{filter_w};
1389}
1390
1391sub DESTROY {
1392 my $self = shift;
1393
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 {
335 my $l = syswrite $self->{fh}, $self->{wbuf}, length $self->{wbuf}; 1405 my $len = syswrite $fh, $wbuf, length $wbuf;
336 1406
337 if (not defined $l) { 1407 if ($len > 0) {
338 return if $! == EAGAIN || $! == EINTR; 1408 substr $wbuf, 0, $len, "";
339 delete $self->{write_w};
340 $self->{on_error}->($self) if $self->{on_error};
341
342 } else { 1409 } else {
343 substr $self->{wbuf}, 0, $l, ''; 1410 @linger = (); # end
344
345 if (length ($self->{wbuf}) == 0) {
346 $self->{write_cb}->($self) if $self->{write_cb};
347
348 delete $self->{write_w};
349 delete $self->{wbuf};
350 delete $self->{write_cb};
351
352 $self->_check_writer;
353 }
354 } 1411 }
355 }); 1412 });
1413 push @linger, AnyEvent->timer (after => $linger, cb => sub {
1414 @linger = ();
1415 });
1416 }
1417}
1418
1419=item AnyEvent::Handle::TLS_CTX
1420
1421This function creates and returns the Net::SSLeay::CTX object used by
1422default for TLS mode.
1423
1424The context is created like this:
1425
1426 Net::SSLeay::load_error_strings;
1427 Net::SSLeay::SSLeay_add_ssl_algorithms;
1428 Net::SSLeay::randomize;
1429
1430 my $CTX = Net::SSLeay::CTX_new;
1431
1432 Net::SSLeay::CTX_set_options $CTX, Net::SSLeay::OP_ALL
1433
1434=cut
1435
1436our $TLS_CTX;
1437
1438sub TLS_CTX() {
1439 $TLS_CTX || do {
1440 require Net::SSLeay;
1441
1442 Net::SSLeay::load_error_strings ();
1443 Net::SSLeay::SSLeay_add_ssl_algorithms ();
1444 Net::SSLeay::randomize ();
1445
1446 $TLS_CTX = Net::SSLeay::CTX_new ();
1447
1448 Net::SSLeay::CTX_set_options ($TLS_CTX, Net::SSLeay::OP_ALL ());
1449
1450 $TLS_CTX
1451 }
356} 1452}
357 1453
358=back 1454=back
359 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
360=head1 AUTHOR 1485=head1 AUTHOR
361 1486
362Robin Redeker, C<< <elmex at ta-sa.org> >> 1487Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
363 1488
364=cut 1489=cut
365 1490
3661; # End of AnyEvent::Handle 14911; # End of AnyEvent::Handle

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines