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.10 by root, Sat May 3 12:17:35 2008 UTC vs.
Revision 1.30 by root, Sat May 24 23:56:26 2008 UTC

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 filehandles via AnyEvent 15AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
16 16
17=cut 17This module is experimental.
18 18
19=cut
20
19our $VERSION = '0.02'; 21our $VERSION = '0.04';
20 22
21=head1 SYNOPSIS 23=head1 SYNOPSIS
22 24
23 use AnyEvent; 25 use AnyEvent;
24 use AnyEvent::Handle; 26 use AnyEvent::Handle;
43 $cv->wait; 45 $cv->wait;
44 46
45=head1 DESCRIPTION 47=head1 DESCRIPTION
46 48
47This module is a helper module to make it easier to do event-based I/O on 49This module is a helper module to make it easier to do event-based I/O on
48filehandles (and sockets, see L<AnyEvent::Socket> for an easy way to make 50filehandles. For utility functions for doing non-blocking connects and accepts
49non-blocking resolves and connects). 51on sockets see L<AnyEvent::Util>.
50 52
51In the following, when the documentation refers to of "bytes" then this 53In the following, when the documentation refers to of "bytes" then this
52means characters. As sysread and syswrite are used for all I/O, their 54means characters. As sysread and syswrite are used for all I/O, their
53treatment of characters applies to this module as well. 55treatment of characters applies to this module as well.
54 56
70The filehandle this L<AnyEvent::Handle> object will operate on. 72The filehandle this L<AnyEvent::Handle> object will operate on.
71 73
72NOTE: The filehandle will be set to non-blocking (using 74NOTE: The filehandle will be set to non-blocking (using
73AnyEvent::Util::fh_nonblocking). 75AnyEvent::Util::fh_nonblocking).
74 76
75=item on_eof => $cb->($self) [MANDATORY] 77=item on_eof => $cb->($self)
76 78
77Set the callback to be called on EOF. 79Set the callback to be called on EOF.
78 80
81While not mandatory, it is highly recommended to set an eof callback,
82otherwise you might end up with a closed socket while you are still
83waiting for data.
84
79=item on_error => $cb->($self) 85=item on_error => $cb->($self)
80 86
81This is the fatal error callback, that is called when, well, a fatal error 87This is the fatal error callback, that is called when, well, a fatal error
82ocurs, such as not being able to resolve the hostname, failure to connect 88occurs, such as not being able to resolve the hostname, failure to connect
83or a read error. 89or a read error.
84 90
85The object will not be in a usable state when this callback has been 91The object will not be in a usable state when this callback has been
86called. 92called.
87 93
88On callback entrance, the value of C<$!> contains the operating system 94On callback entrance, the value of C<$!> contains the operating system
89error (or C<ENOSPC> or C<EPIPE>). 95error (or C<ENOSPC>, C<EPIPE> or C<EBADMSG>).
90 96
91While not mandatory, it is I<highly> recommended to set this callback, as 97While not mandatory, it is I<highly> recommended to set this callback, as
92you will not be notified of errors otherwise. The default simply calls 98you will not be notified of errors otherwise. The default simply calls
93die. 99die.
94 100
96 102
97This sets the default read callback, which is called when data arrives 103This sets the default read callback, which is called when data arrives
98and no read request is in the queue. 104and no read request is in the queue.
99 105
100To access (and remove data from) the read buffer, use the C<< ->rbuf >> 106To access (and remove data from) the read buffer, use the C<< ->rbuf >>
101method or acces sthe C<$self->{rbuf}> member directly. 107method or access the C<$self->{rbuf}> member directly.
102 108
103When an EOF condition is detected then AnyEvent::Handle will first try to 109When an EOF condition is detected then AnyEvent::Handle will first try to
104feed all the remaining data to the queued callbacks and C<on_read> before 110feed all the remaining data to the queued callbacks and C<on_read> before
105calling the C<on_eof> callback. If no progress can be made, then a fatal 111calling the C<on_eof> callback. If no progress can be made, then a fatal
106error will be raised (with C<$!> set to C<EPIPE>). 112error will be raised (with C<$!> set to C<EPIPE>).
133 139
134Sets the amount of bytes (default: C<0>) that make up an "empty" write 140Sets the amount of bytes (default: C<0>) that make up an "empty" write
135buffer: If the write reaches this size or gets even samller it is 141buffer: If the write reaches this size or gets even samller it is
136considered empty. 142considered empty.
137 143
144=item tls => "accept" | "connect" | Net::SSLeay::SSL object
145
146When this parameter is given, it enables TLS (SSL) mode, that means it
147will start making tls handshake and will transparently encrypt/decrypt
148data.
149
150TLS mode requires Net::SSLeay to be installed (it will be loaded
151automatically when you try to create a TLS handle).
152
153For the TLS server side, use C<accept>, and for the TLS client side of a
154connection, use C<connect> mode.
155
156You can also provide your own TLS connection object, but you have
157to 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
159AnyEvent::Handle.
160
161See the C<starttls> method if you need to start TLs negotiation later.
162
163=item tls_ctx => $ssl_ctx
164
165Use the given Net::SSLeay::CTX object to create the new TLS connection
166(unless a connection object was specified directly). If this parameter is
167missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>.
168
138=back 169=back
139 170
140=cut 171=cut
141 172
142sub new { 173sub new {
146 177
147 $self->{fh} or Carp::croak "mandatory argument fh is missing"; 178 $self->{fh} or Carp::croak "mandatory argument fh is missing";
148 179
149 AnyEvent::Util::fh_nonblocking $self->{fh}, 1; 180 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
150 181
151 $self->on_eof ((delete $self->{on_eof} ) or Carp::croak "mandatory argument on_eof is missing"); 182 if ($self->{tls}) {
183 require Net::SSLeay;
184 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
185 }
152 186
187 $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof};
153 $self->on_error (delete $self->{on_error}) if $self->{on_error}; 188 $self->on_error (delete $self->{on_error}) if $self->{on_error};
154 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 189 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
155 $self->on_read (delete $self->{on_read} ) if $self->{on_read}; 190 $self->on_read (delete $self->{on_read} ) if $self->{on_read};
156 191
157 $self->start_read; 192 $self->start_read;
176 } 211 }
177 212
178 if ($self->{on_error}) { 213 if ($self->{on_error}) {
179 $self->{on_error}($self); 214 $self->{on_error}($self);
180 } else { 215 } else {
181 die "AnyEvent::Handle uncaught fatal error: $!"; 216 Carp::croak "AnyEvent::Handle uncaught fatal error: $!";
182 } 217 }
183} 218}
184 219
185=item $fh = $handle->fh 220=item $fh = $handle->fh
186 221
187This method returns the filehandle of the L<AnyEvent::Handle> object. 222This method returns the file handle of the L<AnyEvent::Handle> object.
188 223
189=cut 224=cut
190 225
191sub fh { $_[0]->{fh} } 226sub fh { $_[0]->{fh} }
192 227
220for reading. 255for reading.
221 256
222The write queue is very simple: you can add data to its end, and 257The write queue is very simple: you can add data to its end, and
223AnyEvent::Handle will automatically try to get rid of it for you. 258AnyEvent::Handle will automatically try to get rid of it for you.
224 259
225When data could be writtena nd the write buffer is shorter then the low 260When data could be written and the write buffer is shorter then the low
226water mark, the C<on_drain> callback will be invoked. 261water mark, the C<on_drain> callback will be invoked.
227 262
228=over 4 263=over 4
229 264
230=item $handle->on_drain ($cb) 265=item $handle->on_drain ($cb)
249want (only limited by the available memory), as C<AnyEvent::Handle> 284want (only limited by the available memory), as C<AnyEvent::Handle>
250buffers it independently of the kernel. 285buffers it independently of the kernel.
251 286
252=cut 287=cut
253 288
254sub push_write { 289sub _drain_wbuf {
255 my ($self, $data) = @_; 290 my ($self) = @_;
256 291
257 $self->{wbuf} .= $data; 292 if (!$self->{ww} && length $self->{wbuf}) {
258
259 unless ($self->{ww}) {
260 Scalar::Util::weaken $self; 293 Scalar::Util::weaken $self;
261 my $cb = sub { 294 my $cb = sub {
262 my $len = syswrite $self->{fh}, $self->{wbuf}; 295 my $len = syswrite $self->{fh}, $self->{wbuf};
263 296
264 if ($len > 0) { 297 if ($len >= 0) {
265 substr $self->{wbuf}, 0, $len, ""; 298 substr $self->{wbuf}, 0, $len, "";
266
267 299
268 $self->{on_drain}($self) 300 $self->{on_drain}($self)
269 if $self->{low_water_mark} >= length $self->{wbuf} 301 if $self->{low_water_mark} >= length $self->{wbuf}
270 && $self->{on_drain}; 302 && $self->{on_drain};
271 303
278 $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb); 310 $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb);
279 311
280 $cb->($self); 312 $cb->($self);
281 }; 313 };
282} 314}
315
316our %WH;
317
318sub register_write_type($$) {
319 $WH{$_[0]} = $_[1];
320}
321
322sub push_write {
323 my $self = shift;
324
325 if (@_ > 1) {
326 my $type = shift;
327
328 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write")
329 ->($self, @_);
330 }
331
332 if ($self->{filter_w}) {
333 $self->{filter_w}->($self, \$_[0]);
334 } else {
335 $self->{wbuf} .= $_[0];
336 $self->_drain_wbuf;
337 }
338}
339
340=item $handle->push_write (type => @args)
341
342=item $handle->unshift_write (type => @args)
343
344Instead of formatting your data yourself, you can also let this module do
345the job by specifying a type and type-specific arguments.
346
347Predefined types are (if you have ideas for additional types, feel free to
348drop by and tell us):
349
350=over 4
351
352=item netstring => $string
353
354Formats the given value as netstring
355(http://cr.yp.to/proto/netstrings.txt, this is not a recommendation to use them).
356
357=back
358
359=cut
360
361register_write_type netstring => sub {
362 my ($self, $string) = @_;
363
364 sprintf "%d:%s,", (length $string), $string
365};
366
367=item AnyEvent::Handle::register_write_type type => $coderef->($self, @args)
368
369This 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
371reference with the handle object and the remaining arguments.
372
373The code reference is supposed to return a single octet string that will
374be appended to the write buffer.
375
376Note that this is a function, and all types registered this way will be
377global, so try to use unique names.
378
379=cut
283 380
284############################################################################# 381#############################################################################
285 382
286=back 383=back
287 384
362=cut 459=cut
363 460
364sub _drain_rbuf { 461sub _drain_rbuf {
365 my ($self) = @_; 462 my ($self) = @_;
366 463
464 if (
465 defined $self->{rbuf_max}
466 && $self->{rbuf_max} < length $self->{rbuf}
467 ) {
468 $! = &Errno::ENOSPC; return $self->error;
469 }
470
367 return if exists $self->{in_drain}; 471 return if $self->{in_drain};
368 local $self->{in_drain} = 1; 472 local $self->{in_drain} = 1;
369 473
370 while (my $len = length $self->{rbuf}) { 474 while (my $len = length $self->{rbuf}) {
371 no strict 'refs'; 475 no strict 'refs';
372 if (my $cb = shift @{ $self->{queue} }) { 476 if (my $cb = shift @{ $self->{queue} }) {
373 if (!$cb->($self)) { 477 unless ($cb->($self)) {
374 if ($self->{eof}) { 478 if ($self->{eof}) {
375 # no progress can be made (not enough data and no data forthcoming) 479 # no progress can be made (not enough data and no data forthcoming)
376 $! = &Errno::EPIPE; return $self->error; 480 $! = &Errno::EPIPE; return $self->error;
377 } 481 }
378 482
398 } 502 }
399 } 503 }
400 504
401 if ($self->{eof}) { 505 if ($self->{eof}) {
402 $self->_shutdown; 506 $self->_shutdown;
403 $self->{on_eof}($self); 507 $self->{on_eof}($self)
508 if $self->{on_eof};
404 } 509 }
405} 510}
406 511
407=item $handle->on_read ($cb) 512=item $handle->on_read ($cb)
408 513
442Append the given callback to the end of the queue (C<push_read>) or 547Append the given callback to the end of the queue (C<push_read>) or
443prepend it (C<unshift_read>). 548prepend it (C<unshift_read>).
444 549
445The callback is called each time some additional read data arrives. 550The callback is called each time some additional read data arrives.
446 551
447It must check wether enough data is in the read buffer already. 552It must check whether enough data is in the read buffer already.
448 553
449If not enough data is available, it must return the empty list or a false 554If not enough data is available, it must return the empty list or a false
450value, in which case it will be called repeatedly until enough data is 555value, in which case it will be called repeatedly until enough data is
451available (or an error condition is detected). 556available (or an error condition is detected).
452 557
454interested in (which can be none at all) and return a true value. After returning 559interested in (which can be none at all) and return a true value. After returning
455true, it will be removed from the queue. 560true, it will be removed from the queue.
456 561
457=cut 562=cut
458 563
564our %RH;
565
566sub register_read_type($$) {
567 $RH{$_[0]} = $_[1];
568}
569
459sub push_read { 570sub push_read {
460 my ($self, $cb) = @_; 571 my $self = shift;
572 my $cb = pop;
573
574 if (@_) {
575 my $type = shift;
576
577 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read")
578 ->($self, $cb, @_);
579 }
461 580
462 push @{ $self->{queue} }, $cb; 581 push @{ $self->{queue} }, $cb;
463 $self->_drain_rbuf; 582 $self->_drain_rbuf;
464} 583}
465 584
466sub unshift_read { 585sub unshift_read {
467 my ($self, $cb) = @_; 586 my $self = shift;
587 my $cb = pop;
468 588
589 if (@_) {
590 my $type = shift;
591
592 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
593 ->($self, $cb, @_);
594 }
595
596
469 push @{ $self->{queue} }, $cb; 597 unshift @{ $self->{queue} }, $cb;
470 $self->_drain_rbuf; 598 $self->_drain_rbuf;
471} 599}
472 600
473=item $handle->push_read_chunk ($len, $cb->($self, $data)) 601=item $handle->push_read (type => @args, $cb)
474 602
475=item $handle->unshift_read_chunk ($len, $cb->($self, $data)) 603=item $handle->unshift_read (type => @args, $cb)
476 604
477Append the given callback to the end of the queue (C<push_read_chunk>) or 605Instead of providing a callback that parses the data itself you can chose
478prepend it (C<unshift_read_chunk>). 606between a number of predefined parsing formats, for chunks of data, lines
607etc.
479 608
480The callback will be called only once C<$len> bytes have been read, and 609Predefined types are (if you have ideas for additional types, feel free to
481these C<$len> bytes will be passed to the callback. 610drop by and tell us):
482 611
483=cut 612=over 4
484 613
485sub _read_chunk($$) { 614=item chunk => $octets, $cb->($self, $data)
615
616Invoke 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
618data.
619
620Example: read 2 bytes.
621
622 $handle->push_read (chunk => 2, sub {
623 warn "yay ", unpack "H*", $_[1];
624 });
625
626=cut
627
628register_read_type chunk => sub {
486 my ($self, $len, $cb) = @_; 629 my ($self, $cb, $len) = @_;
487 630
488 sub { 631 sub {
489 $len <= length $_[0]{rbuf} or return; 632 $len <= length $_[0]{rbuf} or return;
490 $cb->($self, $_[0], substr $_[0]{rbuf}, 0, $len, ""); 633 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
491 1 634 1
492 } 635 }
493} 636};
494 637
638# compatibility with older API
495sub push_read_chunk { 639sub push_read_chunk {
496 $_[0]->push_read (&_read_chunk); 640 $_[0]->push_read (chunk => $_[1], $_[2]);
497} 641}
498
499 642
500sub unshift_read_chunk { 643sub unshift_read_chunk {
501 $_[0]->unshift_read (&_read_chunk); 644 $_[0]->unshift_read (chunk => $_[1], $_[2]);
502} 645}
503 646
504=item $handle->push_read_line ([$eol, ]$cb->($self, $line, $eol)) 647=item line => [$eol, ]$cb->($self, $line, $eol)
505
506=item $handle->unshift_read_line ([$eol, ]$cb->($self, $line, $eol))
507
508Append the given callback to the end of the queue (C<push_read_line>) or
509prepend it (C<unshift_read_line>).
510 648
511The callback will be called only once a full line (including the end of 649The callback will be called only once a full line (including the end of
512line marker, C<$eol>) has been read. This line (excluding the end of line 650line marker, C<$eol>) has been read. This line (excluding the end of line
513marker) will be passed to the callback as second argument (C<$line>), and 651marker) will be passed to the callback as second argument (C<$line>), and
514the end of line marker as the third argument (C<$eol>). 652the end of line marker as the third argument (C<$eol>).
525Partial lines at the end of the stream will never be returned, as they are 663Partial lines at the end of the stream will never be returned, as they are
526not marked by the end of line marker. 664not marked by the end of line marker.
527 665
528=cut 666=cut
529 667
530sub _read_line($$) { 668register_read_type line => sub {
531 my $self = shift; 669 my ($self, $cb, $eol) = @_;
532 my $cb = pop;
533 my $eol = @_ ? shift : qr|(\015?\012)|;
534 my $pos;
535 670
671 $eol = qr|(\015?\012)| if @_ < 3;
536 $eol = qr|(\Q$eol\E)| unless ref $eol; 672 $eol = quotemeta $eol unless ref $eol;
537 $eol = qr|^(.*?)($eol)|; 673 $eol = qr|^(.*?)($eol)|s;
538 674
539 sub { 675 sub {
540 $_[0]{rbuf} =~ s/$eol// or return; 676 $_[0]{rbuf} =~ s/$eol// or return;
541 677
542 $cb->($self, $1, $2); 678 $cb->($_[0], $1, $2);
543 1 679 1
544 } 680 }
545} 681};
546 682
683# compatibility with older API
547sub push_read_line { 684sub push_read_line {
548 $_[0]->push_read (&_read_line); 685 my $self = shift;
686 $self->push_read (line => @_);
549} 687}
550 688
551sub unshift_read_line { 689sub unshift_read_line {
552 $_[0]->unshift_read (&_read_line); 690 my $self = shift;
691 $self->unshift_read (line => @_);
553} 692}
693
694=item netstring => $cb->($string)
695
696A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
697
698Throws an error with C<$!> set to EBADMSG on format violations.
699
700=cut
701
702register_read_type netstring => sub {
703 my ($self, $cb) = @_;
704
705 sub {
706 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
707 if ($_[0]{rbuf} =~ /[^0-9]/) {
708 $! = &Errno::EBADMSG;
709 $self->error;
710 }
711 return;
712 }
713
714 my $len = $1;
715
716 $self->unshift_read (chunk => $len, sub {
717 my $string = $_[1];
718 $_[0]->unshift_read (chunk => 1, sub {
719 if ($_[1] eq ",") {
720 $cb->($_[0], $string);
721 } else {
722 $! = &Errno::EBADMSG;
723 $self->error;
724 }
725 });
726 });
727
728 1
729 }
730};
731
732=back
733
734=item AnyEvent::Handle::register_read_type type => $coderef->($self, $cb, @args)
735
736This function (not method) lets you add your own types to C<push_read>.
737
738Whenever the given C<type> is used, C<push_read> will invoke the code
739reference with the handle object, the callback and the remaining
740arguments.
741
742The code reference is supposed to return a callback (usually a closure)
743that works as a plain read callback (see C<< ->push_read ($cb) >>).
744
745It should invoke the passed callback when it is done reading (remember to
746pass C<$self> as first argument as all other callbacks do that).
747
748Note that this is a function, and all types registered this way will be
749global, so try to use unique names.
750
751For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>,
752search for C<register_read_type>)).
554 753
555=item $handle->stop_read 754=item $handle->stop_read
556 755
557=item $handle->start_read 756=item $handle->start_read
558 757
559In rare cases you actually do not want to read anything form the 758In rare cases you actually do not want to read anything from the
560socket. In this case you can call C<stop_read>. Neither C<on_read> no 759socket. In this case you can call C<stop_read>. Neither C<on_read> no
561any queued callbacks will be executed then. To start readign again, call 760any queued callbacks will be executed then. To start reading again, call
562C<start_read>. 761C<start_read>.
563 762
564=cut 763=cut
565 764
566sub stop_read { 765sub stop_read {
574 773
575 unless ($self->{rw} || $self->{eof}) { 774 unless ($self->{rw} || $self->{eof}) {
576 Scalar::Util::weaken $self; 775 Scalar::Util::weaken $self;
577 776
578 $self->{rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub { 777 $self->{rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
778 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf};
579 my $len = sysread $self->{fh}, $self->{rbuf}, $self->{read_size} || 8192, length $self->{rbuf}; 779 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
580 780
581 if ($len > 0) { 781 if ($len > 0) {
582 if (exists $self->{rbuf_max}) { 782 $self->{filter_r}
583 if ($self->{rbuf_max} < length $self->{rbuf}) { 783 ? $self->{filter_r}->($self, $rbuf)
584 $! = &Errno::ENOSPC; return $self->error; 784 : $self->_drain_rbuf;
585 }
586 }
587 785
588 } elsif (defined $len) { 786 } elsif (defined $len) {
787 delete $self->{rw};
589 $self->{eof} = 1; 788 $self->{eof} = 1;
590 delete $self->{rw}; 789 $self->_drain_rbuf;
591 790
592 } elsif ($! != EAGAIN && $! != EINTR) { 791 } elsif ($! != EAGAIN && $! != EINTR) {
593 return $self->error; 792 return $self->error;
594 } 793 }
595
596 $self->_drain_rbuf;
597 }); 794 });
598 } 795 }
599} 796}
600 797
798sub _dotls {
799 my ($self) = @_;
800
801 if (length $self->{tls_wbuf}) {
802 while ((my $len = Net::SSLeay::write ($self->{tls}, $self->{tls_wbuf})) > 0) {
803 substr $self->{tls_wbuf}, 0, $len, "";
804 }
805 }
806
807 if (defined (my $buf = Net::SSLeay::BIO_read ($self->{tls_wbio}))) {
808 $self->{wbuf} .= $buf;
809 $self->_drain_wbuf;
810 }
811
812 while (defined (my $buf = Net::SSLeay::read ($self->{tls}))) {
813 $self->{rbuf} .= $buf;
814 $self->_drain_rbuf;
815 }
816
817 my $err = Net::SSLeay::get_error ($self->{tls}, -1);
818
819 if ($err!= Net::SSLeay::ERROR_WANT_READ ()) {
820 if ($err == Net::SSLeay::ERROR_SYSCALL ()) {
821 $self->error;
822 } elsif ($err == Net::SSLeay::ERROR_SSL ()) {
823 $! = &Errno::EIO;
824 $self->error;
825 }
826
827 # all others are fine for our purposes
828 }
829}
830
831=item $handle->starttls ($tls[, $tls_ctx])
832
833Instead of starting TLS negotiation immediately when the AnyEvent::Handle
834object is created, you can also do that at a later time by calling
835C<starttls>.
836
837The first argument is the same as the C<tls> constructor argument (either
838C<"connect">, C<"accept"> or an existing Net::SSLeay object).
839
840The second argument is the optional C<Net::SSLeay::CTX> object that is
841used when AnyEvent::Handle has to create its own TLS connection object.
842
843=cut
844
845# TODO: maybe document...
846sub starttls {
847 my ($self, $ssl, $ctx) = @_;
848
849 $self->stoptls;
850
851 if ($ssl eq "accept") {
852 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
853 Net::SSLeay::set_accept_state ($ssl);
854 } elsif ($ssl eq "connect") {
855 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
856 Net::SSLeay::set_connect_state ($ssl);
857 }
858
859 $self->{tls} = $ssl;
860
861 # basically, this is deep magic (because SSL_read should have the same issues)
862 # but the openssl maintainers basically said: "trust us, it just works".
863 # (unfortunately, we have to hardcode constants because the abysmally misdesigned
864 # and mismaintained ssleay-module doesn't even offer them).
865 # http://www.mail-archive.com/openssl-dev@openssl.org/msg22420.html
866 Net::SSLeay::CTX_set_mode ($self->{tls},
867 (eval { Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1)
868 | (eval { Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2));
869
870 $self->{tls_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
871 $self->{tls_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
872
873 Net::SSLeay::set_bio ($ssl, $self->{tls_rbio}, $self->{tls_wbio});
874
875 $self->{filter_w} = sub {
876 $_[0]{tls_wbuf} .= ${$_[1]};
877 &_dotls;
878 };
879 $self->{filter_r} = sub {
880 Net::SSLeay::BIO_write ($_[0]{tls_rbio}, ${$_[1]});
881 &_dotls;
882 };
883}
884
885=item $handle->stoptls
886
887Destroys the SSL connection, if any. Partial read or write data will be
888lost.
889
890=cut
891
892sub stoptls {
893 my ($self) = @_;
894
895 Net::SSLeay::free (delete $self->{tls}) if $self->{tls};
896 delete $self->{tls_rbio};
897 delete $self->{tls_wbio};
898 delete $self->{tls_wbuf};
899 delete $self->{filter_r};
900 delete $self->{filter_w};
901}
902
903sub DESTROY {
904 my $self = shift;
905
906 $self->stoptls;
907}
908
909=item AnyEvent::Handle::TLS_CTX
910
911This function creates and returns the Net::SSLeay::CTX object used by
912default for TLS mode.
913
914The context is created like this:
915
916 Net::SSLeay::load_error_strings;
917 Net::SSLeay::SSLeay_add_ssl_algorithms;
918 Net::SSLeay::randomize;
919
920 my $CTX = Net::SSLeay::CTX_new;
921
922 Net::SSLeay::CTX_set_options $CTX, Net::SSLeay::OP_ALL
923
924=cut
925
926our $TLS_CTX;
927
928sub TLS_CTX() {
929 $TLS_CTX || do {
930 require Net::SSLeay;
931
932 Net::SSLeay::load_error_strings ();
933 Net::SSLeay::SSLeay_add_ssl_algorithms ();
934 Net::SSLeay::randomize ();
935
936 $TLS_CTX = Net::SSLeay::CTX_new ();
937
938 Net::SSLeay::CTX_set_options ($TLS_CTX, Net::SSLeay::OP_ALL ());
939
940 $TLS_CTX
941 }
942}
943
601=back 944=back
602 945
603=head1 AUTHOR 946=head1 AUTHOR
604 947
605Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>. 948Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines