ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Handle.pm
Revision: 1.28
Committed: Sat May 24 22:27:11 2008 UTC (15 years, 11 months ago) by root
Branch: MAIN
Changes since 1.27: +68 -29 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 elmex 1.1 package AnyEvent::Handle;
2    
3 elmex 1.6 no warnings;
4 elmex 1.1 use strict;
5    
6 root 1.8 use AnyEvent ();
7     use AnyEvent::Util ();
8     use Scalar::Util ();
9     use Carp ();
10     use Fcntl ();
11 elmex 1.1 use Errno qw/EAGAIN EINTR/;
12    
13     =head1 NAME
14    
15 root 1.22 AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
16 elmex 1.1
17 root 1.15 This module is experimental.
18    
19 elmex 1.1 =cut
20    
21 root 1.15 our $VERSION = '0.04';
22 elmex 1.1
23     =head1 SYNOPSIS
24    
25     use AnyEvent;
26     use AnyEvent::Handle;
27    
28     my $cv = AnyEvent->condvar;
29    
30     my $ae_fh = AnyEvent::Handle->new (fh => \*STDIN);
31    
32 root 1.8 #TODO
33 elmex 1.1
34 elmex 1.2 # or use the constructor to pass the callback:
35    
36     my $ae_fh2 =
37     AnyEvent::Handle->new (
38     fh => \*STDIN,
39     on_eof => sub {
40     $cv->broadcast;
41     },
42 root 1.8 #TODO
43 elmex 1.2 );
44    
45 elmex 1.1 $cv->wait;
46    
47     =head1 DESCRIPTION
48    
49 root 1.8 This module is a helper module to make it easier to do event-based I/O on
50 elmex 1.13 filehandles. For utility functions for doing non-blocking connects and accepts
51     on sockets see L<AnyEvent::Util>.
52 root 1.8
53     In the following, when the documentation refers to of "bytes" then this
54     means characters. As sysread and syswrite are used for all I/O, their
55     treatment of characters applies to this module as well.
56 elmex 1.1
57 root 1.8 All callbacks will be invoked with the handle object as their first
58     argument.
59 elmex 1.1
60     =head1 METHODS
61    
62     =over 4
63    
64     =item B<new (%args)>
65    
66 root 1.8 The constructor supports these arguments (all as key => value pairs).
67 elmex 1.1
68     =over 4
69    
70 root 1.8 =item fh => $filehandle [MANDATORY]
71 elmex 1.1
72     The filehandle this L<AnyEvent::Handle> object will operate on.
73    
74 root 1.8 NOTE: The filehandle will be set to non-blocking (using
75     AnyEvent::Util::fh_nonblocking).
76    
77 root 1.16 =item on_eof => $cb->($self)
78 root 1.10
79     Set the callback to be called on EOF.
80 root 1.8
81 root 1.16 While not mandatory, it is highly recommended to set an eof callback,
82     otherwise you might end up with a closed socket while you are still
83     waiting for data.
84    
85 root 1.10 =item on_error => $cb->($self)
86    
87     This is the fatal error callback, that is called when, well, a fatal error
88 elmex 1.20 occurs, such as not being able to resolve the hostname, failure to connect
89 root 1.10 or a read error.
90 root 1.8
91     The object will not be in a usable state when this callback has been
92     called.
93    
94 root 1.10 On callback entrance, the value of C<$!> contains the operating system
95 root 1.8 error (or C<ENOSPC> or C<EPIPE>).
96    
97 root 1.10 While not mandatory, it is I<highly> recommended to set this callback, as
98     you will not be notified of errors otherwise. The default simply calls
99     die.
100 root 1.8
101     =item on_read => $cb->($self)
102    
103     This sets the default read callback, which is called when data arrives
104 root 1.10 and no read request is in the queue.
105 root 1.8
106     To access (and remove data from) the read buffer, use the C<< ->rbuf >>
107 elmex 1.20 method or access the C<$self->{rbuf}> member directly.
108 root 1.8
109     When an EOF condition is detected then AnyEvent::Handle will first try to
110     feed all the remaining data to the queued callbacks and C<on_read> before
111     calling the C<on_eof> callback. If no progress can be made, then a fatal
112     error will be raised (with C<$!> set to C<EPIPE>).
113 elmex 1.1
114 root 1.8 =item on_drain => $cb->()
115 elmex 1.1
116 root 1.8 This 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).
118 elmex 1.1
119 root 1.8 To append to the write buffer, use the C<< ->push_write >> method.
120 elmex 1.2
121 root 1.8 =item rbuf_max => <bytes>
122 elmex 1.2
123 root 1.8 If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
124     when the read buffer ever (strictly) exceeds this size. This is useful to
125     avoid denial-of-service attacks.
126 elmex 1.2
127 root 1.8 For example, a server accepting connections from untrusted sources should
128     be 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
130     amount of data without a callback ever being called as long as the line
131     isn't finished).
132 elmex 1.2
133 root 1.8 =item read_size => <bytes>
134 elmex 1.2
135 root 1.8 The default read block size (the amount of bytes this module will try to read
136     on each [loop iteration). Default: C<4096>.
137    
138     =item low_water_mark => <bytes>
139    
140     Sets the amount of bytes (default: C<0>) that make up an "empty" write
141     buffer: If the write reaches this size or gets even samller it is
142     considered empty.
143 elmex 1.2
144 root 1.19 =item tls => "accept" | "connect" | Net::SSLeay::SSL object
145    
146     When this parameter is given, it enables TLS (SSL) mode, that means it
147     will start making tls handshake and will transparently encrypt/decrypt
148     data.
149    
150 root 1.26 TLS mode requires Net::SSLeay to be installed (it will be loaded
151     automatically when you try to create a TLS handle).
152    
153 root 1.19 For the TLS server side, use C<accept>, and for the TLS client side of a
154     connection, use C<connect> mode.
155    
156     You can also provide your own TLS connection object, but you have
157     to make sure that you call either C<Net::SSLeay::set_connect_state>
158     or C<Net::SSLeay::set_accept_state> on it before you pass it to
159     AnyEvent::Handle.
160    
161 root 1.26 See the C<starttls> method if you need to start TLs negotiation later.
162    
163 root 1.19 =item tls_ctx => $ssl_ctx
164    
165     Use the given Net::SSLeay::CTX object to create the new TLS connection
166     (unless a connection object was specified directly). If this parameter is
167     missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>.
168    
169 elmex 1.1 =back
170    
171     =cut
172    
173 root 1.28 our (%RH, %WH);
174    
175     sub register_read_type($$) {
176     $RH{$_[0]} = $_[1];
177     }
178    
179     sub register_write_type($$) {
180     $WH{$_[0]} = $_[1];
181     }
182    
183 elmex 1.1 sub new {
184 root 1.8 my $class = shift;
185    
186     my $self = bless { @_ }, $class;
187    
188     $self->{fh} or Carp::croak "mandatory argument fh is missing";
189    
190     AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
191 elmex 1.1
192 root 1.19 if ($self->{tls}) {
193     require Net::SSLeay;
194     $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
195     }
196    
197 root 1.16 $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof};
198 root 1.10 $self->on_error (delete $self->{on_error}) if $self->{on_error};
199 root 1.8 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
200     $self->on_read (delete $self->{on_read} ) if $self->{on_read};
201 elmex 1.1
202 root 1.10 $self->start_read;
203    
204 root 1.8 $self
205     }
206 elmex 1.2
207 root 1.8 sub _shutdown {
208     my ($self) = @_;
209 elmex 1.2
210 root 1.8 delete $self->{rw};
211     delete $self->{ww};
212     delete $self->{fh};
213     }
214    
215     sub error {
216     my ($self) = @_;
217    
218     {
219     local $!;
220     $self->_shutdown;
221 elmex 1.1 }
222    
223 root 1.10 if ($self->{on_error}) {
224     $self->{on_error}($self);
225     } else {
226     die "AnyEvent::Handle uncaught fatal error: $!";
227     }
228 elmex 1.1 }
229    
230 root 1.8 =item $fh = $handle->fh
231 elmex 1.1
232 root 1.22 This method returns the file handle of the L<AnyEvent::Handle> object.
233 elmex 1.1
234     =cut
235    
236     sub fh { $_[0]->{fh} }
237    
238 root 1.8 =item $handle->on_error ($cb)
239 elmex 1.1
240 root 1.8 Replace the current C<on_error> callback (see the C<on_error> constructor argument).
241 elmex 1.1
242 root 1.8 =cut
243    
244     sub on_error {
245     $_[0]{on_error} = $_[1];
246     }
247    
248     =item $handle->on_eof ($cb)
249    
250     Replace the current C<on_eof> callback (see the C<on_eof> constructor argument).
251 elmex 1.1
252     =cut
253    
254 root 1.8 sub on_eof {
255     $_[0]{on_eof} = $_[1];
256     }
257    
258 root 1.9 #############################################################################
259    
260     =back
261    
262     =head2 WRITE QUEUE
263    
264     AnyEvent::Handle manages two queues per handle, one for writing and one
265     for reading.
266    
267     The write queue is very simple: you can add data to its end, and
268     AnyEvent::Handle will automatically try to get rid of it for you.
269    
270 elmex 1.20 When data could be written and the write buffer is shorter then the low
271 root 1.9 water mark, the C<on_drain> callback will be invoked.
272    
273     =over 4
274    
275 root 1.8 =item $handle->on_drain ($cb)
276    
277     Sets the C<on_drain> callback or clears it (see the description of
278     C<on_drain> in the constructor).
279    
280     =cut
281    
282     sub on_drain {
283 elmex 1.1 my ($self, $cb) = @_;
284    
285 root 1.8 $self->{on_drain} = $cb;
286    
287     $cb->($self)
288     if $cb && $self->{low_water_mark} >= length $self->{wbuf};
289     }
290    
291     =item $handle->push_write ($data)
292    
293     Queues the given scalar to be written. You can push as much data as you
294     want (only limited by the available memory), as C<AnyEvent::Handle>
295     buffers it independently of the kernel.
296    
297     =cut
298    
299 root 1.17 sub _drain_wbuf {
300     my ($self) = @_;
301 root 1.8
302     unless ($self->{ww}) {
303     Scalar::Util::weaken $self;
304     my $cb = sub {
305     my $len = syswrite $self->{fh}, $self->{wbuf};
306    
307     if ($len > 0) {
308     substr $self->{wbuf}, 0, $len, "";
309    
310     $self->{on_drain}($self)
311     if $self->{low_water_mark} >= length $self->{wbuf}
312     && $self->{on_drain};
313    
314     delete $self->{ww} unless length $self->{wbuf};
315     } elsif ($! != EAGAIN && $! != EINTR) {
316     $self->error;
317 elmex 1.1 }
318 root 1.8 };
319    
320     $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb);
321    
322     $cb->($self);
323     };
324     }
325    
326 root 1.17 sub push_write {
327     my $self = shift;
328    
329     if ($self->{filter_w}) {
330 root 1.18 $self->{filter_w}->($self, \$_[0]);
331 root 1.17 } else {
332     $self->{wbuf} .= $_[0];
333     $self->_drain_wbuf;
334     }
335     }
336    
337 root 1.8 #############################################################################
338    
339 root 1.9 =back
340    
341     =head2 READ QUEUE
342    
343     AnyEvent::Handle manages two queues per handle, one for writing and one
344     for reading.
345    
346     The read queue is more complex than the write queue. It can be used in two
347     ways, the "simple" way, using only C<on_read> and the "complex" way, using
348     a queue.
349    
350     In the simple case, you just install an C<on_read> callback and whenever
351     new data arrives, it will be called. You can then remove some data (if
352     enough is there) from the read buffer (C<< $handle->rbuf >>) if you want
353     or not.
354    
355     In the more complex case, you want to queue multiple callbacks. In this
356     case, AnyEvent::Handle will call the first queued callback each time new
357     data arrives and removes it when it has done its job (see C<push_read>,
358     below).
359    
360     This way you can, for example, push three line-reads, followed by reading
361     a chunk of data, and AnyEvent::Handle will execute them in order.
362    
363     Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
364     the specified number of bytes which give an XML datagram.
365    
366     # in the default state, expect some header bytes
367     $handle->on_read (sub {
368     # some data is here, now queue the length-header-read (4 octets)
369     shift->unshift_read_chunk (4, sub {
370     # header arrived, decode
371     my $len = unpack "N", $_[1];
372    
373     # now read the payload
374     shift->unshift_read_chunk ($len, sub {
375     my $xml = $_[1];
376     # handle xml
377     });
378     });
379     });
380    
381     Example 2: Implement a client for a protocol that replies either with
382     "OK" and another line or "ERROR" for one request, and 64 bytes for the
383     second request. Due tot he availability of a full queue, we can just
384     pipeline sending both requests and manipulate the queue as necessary in
385     the callbacks:
386    
387     # request one
388     $handle->push_write ("request 1\015\012");
389    
390     # we expect "ERROR" or "OK" as response, so push a line read
391     $handle->push_read_line (sub {
392     # if we got an "OK", we have to _prepend_ another line,
393     # so it will be read before the second request reads its 64 bytes
394     # which are already in the queue when this callback is called
395     # we don't do this in case we got an error
396     if ($_[1] eq "OK") {
397     $_[0]->unshift_read_line (sub {
398     my $response = $_[1];
399     ...
400     });
401     }
402     });
403    
404     # request two
405     $handle->push_write ("request 2\015\012");
406    
407     # simply read 64 bytes, always
408     $handle->push_read_chunk (64, sub {
409     my $response = $_[1];
410     ...
411     });
412    
413     =over 4
414    
415 root 1.10 =cut
416    
417 root 1.8 sub _drain_rbuf {
418     my ($self) = @_;
419 elmex 1.1
420 root 1.17 if (
421     defined $self->{rbuf_max}
422     && $self->{rbuf_max} < length $self->{rbuf}
423     ) {
424     $! = &Errno::ENOSPC; return $self->error;
425     }
426    
427 root 1.11 return if $self->{in_drain};
428 root 1.8 local $self->{in_drain} = 1;
429 elmex 1.1
430 root 1.8 while (my $len = length $self->{rbuf}) {
431     no strict 'refs';
432 root 1.10 if (my $cb = shift @{ $self->{queue} }) {
433     if (!$cb->($self)) {
434     if ($self->{eof}) {
435     # no progress can be made (not enough data and no data forthcoming)
436     $! = &Errno::EPIPE; return $self->error;
437     }
438    
439     unshift @{ $self->{queue} }, $cb;
440 root 1.8 return;
441     }
442     } elsif ($self->{on_read}) {
443     $self->{on_read}($self);
444    
445     if (
446     $self->{eof} # if no further data will arrive
447     && $len == length $self->{rbuf} # and no data has been consumed
448     && !@{ $self->{queue} } # and the queue is still empty
449     && $self->{on_read} # and we still want to read data
450     ) {
451     # then no progress can be made
452     $! = &Errno::EPIPE; return $self->error;
453 elmex 1.1 }
454 root 1.8 } else {
455     # read side becomes idle
456     delete $self->{rw};
457     return;
458     }
459     }
460    
461     if ($self->{eof}) {
462     $self->_shutdown;
463 root 1.16 $self->{on_eof}($self)
464     if $self->{on_eof};
465 root 1.8 }
466 elmex 1.1 }
467    
468 root 1.8 =item $handle->on_read ($cb)
469 elmex 1.1
470 root 1.8 This replaces the currently set C<on_read> callback, or clears it (when
471     the new callback is C<undef>). See the description of C<on_read> in the
472     constructor.
473 elmex 1.1
474 root 1.8 =cut
475    
476     sub on_read {
477     my ($self, $cb) = @_;
478 elmex 1.1
479 root 1.8 $self->{on_read} = $cb;
480 elmex 1.1 }
481    
482 root 1.8 =item $handle->rbuf
483    
484     Returns the read buffer (as a modifiable lvalue).
485 elmex 1.1
486 root 1.8 You can access the read buffer directly as the C<< ->{rbuf} >> member, if
487     you want.
488 elmex 1.1
489 root 1.8 NOTE: The read buffer should only be used or modified if the C<on_read>,
490     C<push_read> or C<unshift_read> methods are used. The other read methods
491     automatically manage the read buffer.
492 elmex 1.1
493     =cut
494    
495 elmex 1.2 sub rbuf : lvalue {
496 root 1.8 $_[0]{rbuf}
497 elmex 1.2 }
498 elmex 1.1
499 root 1.8 =item $handle->push_read ($cb)
500    
501     =item $handle->unshift_read ($cb)
502    
503     Append the given callback to the end of the queue (C<push_read>) or
504     prepend it (C<unshift_read>).
505    
506     The callback is called each time some additional read data arrives.
507 elmex 1.1
508 elmex 1.20 It must check whether enough data is in the read buffer already.
509 elmex 1.1
510 root 1.8 If not enough data is available, it must return the empty list or a false
511     value, in which case it will be called repeatedly until enough data is
512     available (or an error condition is detected).
513    
514     If enough data was available, then the callback must remove all data it is
515     interested in (which can be none at all) and return a true value. After returning
516     true, it will be removed from the queue.
517 elmex 1.1
518     =cut
519    
520 root 1.8 sub push_read {
521 root 1.28 my $self = shift;
522     my $cb = pop;
523    
524     if (@_) {
525     my $type = shift;
526    
527     $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read")
528     ->($self, $cb, @_);
529     }
530 elmex 1.1
531 root 1.8 push @{ $self->{queue} }, $cb;
532     $self->_drain_rbuf;
533 elmex 1.1 }
534    
535 root 1.8 sub unshift_read {
536 root 1.28 my $self = shift;
537     my $cb = pop;
538    
539     if (@_) {
540     my $type = shift;
541    
542     $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
543     ->($self, $cb, @_);
544     }
545    
546 root 1.8
547 root 1.28 unshift @{ $self->{queue} }, $cb;
548 root 1.8 $self->_drain_rbuf;
549     }
550 elmex 1.1
551 root 1.28 =item $handle->push_read (type => @args, $cb)
552 elmex 1.1
553 root 1.28 =item $handle->unshift_read (type => @args, $cb)
554 elmex 1.1
555 root 1.28 Instead of providing a callback that parses the data itself you can chose
556     between a number of predefined parsing formats, for chunks of data, lines
557     etc.
558 elmex 1.1
559 root 1.28 The types currently supported are:
560    
561     =over 4
562    
563     =item chunk => $octets, $cb->($self, $data)
564    
565     Invoke the callback only once C<$octets> bytes have been read. Pass the
566     data read to the callback. The callback will never be called with less
567     data.
568    
569     Example: read 2 bytes.
570    
571     $handle->push_read (chunk => 2, sub {
572     warn "yay ", unpack "H*", $_[1];
573     });
574 elmex 1.1
575     =cut
576    
577 root 1.28 register_read_type chunk => sub {
578     my ($self, $cb, $len) = @_;
579 elmex 1.1
580 root 1.8 sub {
581     $len <= length $_[0]{rbuf} or return;
582 elmex 1.12 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
583 root 1.8 1
584     }
585 root 1.28 };
586 root 1.8
587 root 1.28 # compatibility with older API
588 root 1.8 sub push_read_chunk {
589 root 1.28 $_[0]->push_read (chunk => $_[1], $_[2]);
590 root 1.8 }
591 elmex 1.1
592 root 1.8 sub unshift_read_chunk {
593 root 1.28 $_[0]->unshift_read (chunk => $_[1], $_[2]);
594 elmex 1.1 }
595    
596 root 1.28 =item line => [$eol, ]$cb->($self, $line, $eol)
597 elmex 1.1
598 root 1.8 The callback will be called only once a full line (including the end of
599     line marker, C<$eol>) has been read. This line (excluding the end of line
600     marker) will be passed to the callback as second argument (C<$line>), and
601     the end of line marker as the third argument (C<$eol>).
602 elmex 1.1
603 root 1.8 The end of line marker, C<$eol>, can be either a string, in which case it
604     will be interpreted as a fixed record end marker, or it can be a regex
605     object (e.g. created by C<qr>), in which case it is interpreted as a
606     regular expression.
607 elmex 1.1
608 root 1.8 The end of line marker argument C<$eol> is optional, if it is missing (NOT
609     undef), then C<qr|\015?\012|> is used (which is good for most internet
610     protocols).
611 elmex 1.1
612 root 1.8 Partial lines at the end of the stream will never be returned, as they are
613     not marked by the end of line marker.
614 elmex 1.1
615 root 1.8 =cut
616 elmex 1.1
617 root 1.28 register_read_type line => sub {
618     my ($self, $cb, $eol) = @_;
619 elmex 1.1
620 root 1.28 $eol = qr|(\015?\012)| if @_ < 3;
621 root 1.14 $eol = quotemeta $eol unless ref $eol;
622     $eol = qr|^(.*?)($eol)|s;
623 elmex 1.1
624 root 1.8 sub {
625     $_[0]{rbuf} =~ s/$eol// or return;
626 elmex 1.1
627 elmex 1.12 $cb->($_[0], $1, $2);
628 root 1.8 1
629     }
630 root 1.28 };
631 elmex 1.1
632 root 1.28 # compatibility with older API
633 root 1.8 sub push_read_line {
634 root 1.28 my $self = shift;
635     $self->push_read (line => @_);
636 root 1.10 }
637    
638     sub unshift_read_line {
639 root 1.28 my $self = shift;
640     $self->unshift_read (line => @_);
641 root 1.10 }
642    
643 root 1.28 =back
644    
645 root 1.10 =item $handle->stop_read
646    
647     =item $handle->start_read
648    
649 root 1.18 In rare cases you actually do not want to read anything from the
650 root 1.10 socket. In this case you can call C<stop_read>. Neither C<on_read> no
651 root 1.22 any queued callbacks will be executed then. To start reading again, call
652 root 1.10 C<start_read>.
653    
654     =cut
655    
656     sub stop_read {
657     my ($self) = @_;
658 elmex 1.1
659 root 1.10 delete $self->{rw};
660 root 1.8 }
661 elmex 1.1
662 root 1.10 sub start_read {
663     my ($self) = @_;
664    
665     unless ($self->{rw} || $self->{eof}) {
666     Scalar::Util::weaken $self;
667    
668     $self->{rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
669 root 1.17 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf};
670     my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
671 root 1.10
672     if ($len > 0) {
673 root 1.17 $self->{filter_r}
674 root 1.18 ? $self->{filter_r}->($self, $rbuf)
675 root 1.17 : $self->_drain_rbuf;
676 root 1.10
677     } elsif (defined $len) {
678 root 1.17 delete $self->{rw};
679 root 1.10 $self->{eof} = 1;
680 root 1.17 $self->_drain_rbuf;
681 root 1.10
682     } elsif ($! != EAGAIN && $! != EINTR) {
683     return $self->error;
684     }
685     });
686     }
687 elmex 1.1 }
688    
689 root 1.19 sub _dotls {
690     my ($self) = @_;
691    
692     if (length $self->{tls_wbuf}) {
693 root 1.22 while ((my $len = Net::SSLeay::write ($self->{tls}, $self->{tls_wbuf})) > 0) {
694     substr $self->{tls_wbuf}, 0, $len, "";
695     }
696 root 1.19 }
697    
698     if (defined (my $buf = Net::SSLeay::BIO_read ($self->{tls_wbio}))) {
699     $self->{wbuf} .= $buf;
700     $self->_drain_wbuf;
701     }
702    
703 root 1.23 while (defined (my $buf = Net::SSLeay::read ($self->{tls}))) {
704     $self->{rbuf} .= $buf;
705     $self->_drain_rbuf;
706     }
707    
708 root 1.24 my $err = Net::SSLeay::get_error ($self->{tls}, -1);
709    
710     if ($err!= Net::SSLeay::ERROR_WANT_READ ()) {
711 root 1.23 if ($err == Net::SSLeay::ERROR_SYSCALL ()) {
712     $self->error;
713     } elsif ($err == Net::SSLeay::ERROR_SSL ()) {
714     $! = &Errno::EIO;
715     $self->error;
716 root 1.19 }
717 root 1.23
718     # all others are fine for our purposes
719 root 1.19 }
720     }
721    
722 root 1.25 =item $handle->starttls ($tls[, $tls_ctx])
723    
724     Instead of starting TLS negotiation immediately when the AnyEvent::Handle
725     object is created, you can also do that at a later time by calling
726     C<starttls>.
727    
728     The first argument is the same as the C<tls> constructor argument (either
729     C<"connect">, C<"accept"> or an existing Net::SSLeay object).
730    
731     The second argument is the optional C<Net::SSLeay::CTX> object that is
732     used when AnyEvent::Handle has to create its own TLS connection object.
733    
734     =cut
735    
736 root 1.19 # TODO: maybe document...
737     sub starttls {
738     my ($self, $ssl, $ctx) = @_;
739    
740 root 1.25 $self->stoptls;
741    
742 root 1.19 if ($ssl eq "accept") {
743     $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
744     Net::SSLeay::set_accept_state ($ssl);
745     } elsif ($ssl eq "connect") {
746     $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
747     Net::SSLeay::set_connect_state ($ssl);
748     }
749    
750     $self->{tls} = $ssl;
751    
752 root 1.21 # basically, this is deep magic (because SSL_read should have the same issues)
753     # but the openssl maintainers basically said: "trust us, it just works".
754     # (unfortunately, we have to hardcode constants because the abysmally misdesigned
755     # and mismaintained ssleay-module doesn't even offer them).
756 root 1.27 # http://www.mail-archive.com/openssl-dev@openssl.org/msg22420.html
757 root 1.21 Net::SSLeay::CTX_set_mode ($self->{tls},
758     (eval { Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1)
759     | (eval { Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2));
760    
761 root 1.19 $self->{tls_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
762     $self->{tls_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
763    
764     Net::SSLeay::set_bio ($ssl, $self->{tls_rbio}, $self->{tls_wbio});
765    
766     $self->{filter_w} = sub {
767     $_[0]{tls_wbuf} .= ${$_[1]};
768     &_dotls;
769     };
770     $self->{filter_r} = sub {
771     Net::SSLeay::BIO_write ($_[0]{tls_rbio}, ${$_[1]});
772     &_dotls;
773     };
774     }
775    
776 root 1.25 =item $handle->stoptls
777    
778     Destroys the SSL connection, if any. Partial read or write data will be
779     lost.
780    
781     =cut
782    
783     sub stoptls {
784     my ($self) = @_;
785    
786     Net::SSLeay::free (delete $self->{tls}) if $self->{tls};
787     delete $self->{tls_rbio};
788     delete $self->{tls_wbio};
789     delete $self->{tls_wbuf};
790     delete $self->{filter_r};
791     delete $self->{filter_w};
792     }
793    
794 root 1.19 sub DESTROY {
795     my $self = shift;
796    
797 root 1.25 $self->stoptls;
798 root 1.19 }
799    
800     =item AnyEvent::Handle::TLS_CTX
801    
802     This function creates and returns the Net::SSLeay::CTX object used by
803     default for TLS mode.
804    
805     The context is created like this:
806    
807     Net::SSLeay::load_error_strings;
808     Net::SSLeay::SSLeay_add_ssl_algorithms;
809     Net::SSLeay::randomize;
810    
811     my $CTX = Net::SSLeay::CTX_new;
812    
813     Net::SSLeay::CTX_set_options $CTX, Net::SSLeay::OP_ALL
814    
815     =cut
816    
817     our $TLS_CTX;
818    
819     sub TLS_CTX() {
820     $TLS_CTX || do {
821     require Net::SSLeay;
822    
823     Net::SSLeay::load_error_strings ();
824     Net::SSLeay::SSLeay_add_ssl_algorithms ();
825     Net::SSLeay::randomize ();
826    
827     $TLS_CTX = Net::SSLeay::CTX_new ();
828    
829     Net::SSLeay::CTX_set_options ($TLS_CTX, Net::SSLeay::OP_ALL ());
830    
831     $TLS_CTX
832     }
833     }
834    
835 elmex 1.1 =back
836    
837     =head1 AUTHOR
838    
839 root 1.8 Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
840 elmex 1.1
841     =cut
842    
843     1; # End of AnyEvent::Handle