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.142 by root, Mon Jul 6 20:24:47 2009 UTC vs.
Revision 1.158 by root, Fri Jul 24 08:40:35 2009 UTC

1package AnyEvent::Handle; 1package AnyEvent::Handle;
2 2
3no warnings;
4use strict qw(subs vars);
5
6use AnyEvent ();
7use AnyEvent::Util qw(WSAEWOULDBLOCK);
8use Scalar::Util (); 3use Scalar::Util ();
9use Carp (); 4use Carp ();
10use Fcntl ();
11use Errno qw(EAGAIN EINTR); 5use Errno qw(EAGAIN EINTR);
12 6
7use AnyEvent (); BEGIN { AnyEvent::common_sense }
8use AnyEvent::Util qw(WSAEWOULDBLOCK);
9
13=head1 NAME 10=head1 NAME
14 11
15AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent 12AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
16 13
17=cut 14=cut
18 15
19our $VERSION = 4.452; 16our $VERSION = 4.86;
20 17
21=head1 SYNOPSIS 18=head1 SYNOPSIS
22 19
23 use AnyEvent; 20 use AnyEvent;
24 use AnyEvent::Handle; 21 use AnyEvent::Handle;
25 22
26 my $cv = AnyEvent->condvar; 23 my $cv = AnyEvent->condvar;
27 24
28 my $handle = 25 my $hdl; $hdl = new AnyEvent::Handle
29 AnyEvent::Handle->new (
30 fh => \*STDIN, 26 fh => \*STDIN,
31 on_eof => sub { 27 on_error => sub {
28 my ($hdl, $fatal, $msg) = @_;
29 warn "got error $msg\n";
30 $hdl->destroy;
32 $cv->send; 31 $cv->send;
33 },
34 ); 32 );
35 33
36 # send some request line 34 # send some request line
37 $handle->push_write ("getinfo\015\012"); 35 $hdl->push_write ("getinfo\015\012");
38 36
39 # read the response line 37 # read the response line
40 $handle->push_read (line => sub { 38 $hdl->push_read (line => sub {
41 my ($handle, $line) = @_; 39 my ($hdl, $line) = @_;
42 warn "read line <$line>\n"; 40 warn "got line <$line>\n";
43 $cv->send; 41 $cv->send;
44 }); 42 });
45 43
46 $cv->recv; 44 $cv->recv;
47 45
71 69
72=over 4 70=over 4
73 71
74=item fh => $filehandle [MANDATORY] 72=item fh => $filehandle [MANDATORY]
75 73
74#=item fh => $filehandle [C<fh> or C<connect> MANDATORY]
75
76The filehandle this L<AnyEvent::Handle> object will operate on. 76The filehandle this L<AnyEvent::Handle> object will operate on.
77
78NOTE: The filehandle will be set to non-blocking mode (using 77NOTE: The filehandle will be set to non-blocking mode (using
79C<AnyEvent::Util::fh_nonblocking>) by the constructor and needs to stay in 78C<AnyEvent::Util::fh_nonblocking>) by the constructor and needs to stay in
80that mode. 79that mode.
81 80
81#=item connect => [$host, $service]
82#
83# You have to specify either this parameter, or C<connect>, below.
84#Try to connect to the specified host and service (port), using
85#C<AnyEvent::Socket::tcp_connect>.
86#
87#When this
88
82=item on_eof => $cb->($handle) 89=item on_eof => $cb->($handle)
83 90
84Set the callback to be called when an end-of-file condition is detected, 91Set the callback to be called when an end-of-file condition is detected,
85i.e. in the case of a socket, when the other side has closed the 92i.e. in the case of a socket, when the other side has closed the
86connection cleanly. 93connection cleanly, and there are no outstanding read requests in the
94queue (if there are read requests, then an EOF counts as an unexpected
95connection close and will be flagged as an error).
87 96
88For sockets, this just means that the other side has stopped sending data, 97For sockets, this just means that the other side has stopped sending data,
89you can still try to write data, and, in fact, one can return from the EOF 98you can still try to write data, and, in fact, one can return from the EOF
90callback and continue writing data, as only the read part has been shut 99callback and continue writing data, as only the read part has been shut
91down. 100down.
92 101
93While not mandatory, it is I<highly> recommended to set an EOF callback,
94otherwise you might end up with a closed socket while you are still
95waiting for data.
96
97If an EOF condition has been detected but no C<on_eof> callback has been 102If an EOF condition has been detected but no C<on_eof> callback has been
98set, then a fatal error will be raised with C<$!> set to <0>. 103set, then a fatal error will be raised with C<$!> set to <0>.
99 104
100=item on_error => $cb->($handle, $fatal, $message) 105=item on_error => $cb->($handle, $fatal, $message)
101 106
102This is the error callback, which is called when, well, some error 107This is the error callback, which is called when, well, some error
103occured, such as not being able to resolve the hostname, failure to 108occured, such as not being able to resolve the hostname, failure to
104connect or a read error. 109connect or a read error.
105 110
106Some errors are fatal (which is indicated by C<$fatal> being true). On 111Some errors are fatal (which is indicated by C<$fatal> being true). On
107fatal errors the handle object will be shut down and will not be usable 112fatal errors the handle object will be destroyed (by a call to C<< ->
108(but you are free to look at the current C<< ->rbuf >>). Examples of fatal 113destroy >>) after invoking the error callback (which means you are free to
109errors are an EOF condition with active (but unsatisifable) read watchers 114examine the handle object). Examples of fatal errors are an EOF condition
110(C<EPIPE>) or I/O errors. 115with active (but unsatisifable) read watchers (C<EPIPE>) or I/O errors.
111 116
112AnyEvent::Handle tries to find an appropriate error code for you to check 117AnyEvent::Handle tries to find an appropriate error code for you to check
113against, but in some cases (TLS errors), this does not work well. It is 118against, but in some cases (TLS errors), this does not work well. It is
114recommended to always output the C<$message> argument in human-readable 119recommended to always output the C<$message> argument in human-readable
115error messages (it's usually the same as C<"$!">). 120error messages (it's usually the same as C<"$!">).
141 146
142When an EOF condition is detected then AnyEvent::Handle will first try to 147When an EOF condition is detected then AnyEvent::Handle will first try to
143feed all the remaining data to the queued callbacks and C<on_read> before 148feed all the remaining data to the queued callbacks and C<on_read> before
144calling the C<on_eof> callback. If no progress can be made, then a fatal 149calling the C<on_eof> callback. If no progress can be made, then a fatal
145error will be raised (with C<$!> set to C<EPIPE>). 150error will be raised (with C<$!> set to C<EPIPE>).
151
152Note that, unlike requests in the read queue, an C<on_read> callback
153doesn't mean you I<require> some data: if there is an EOF and there
154are outstanding read requests then an error will be flagged. With an
155C<on_read> callback, the C<on_eof> callback will be invoked.
146 156
147=item on_drain => $cb->($handle) 157=item on_drain => $cb->($handle)
148 158
149This sets the callback that is called when the write buffer becomes empty 159This sets the callback that is called when the write buffer becomes empty
150(or when the callback is set and the buffer is empty already). 160(or when the callback is set and the buffer is empty already).
249 259
250A string used to identify the remote site - usually the DNS hostname 260A string used to identify the remote site - usually the DNS hostname
251(I<not> IDN!) used to create the connection, rarely the IP address. 261(I<not> IDN!) used to create the connection, rarely the IP address.
252 262
253Apart from being useful in error messages, this string is also used in TLS 263Apart from being useful in error messages, this string is also used in TLS
254peername verification (see C<verify_peername> in L<AnyEvent::TLS>). 264peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This
265verification will be skipped when C<peername> is not specified or
266C<undef>.
255 267
256=item tls => "accept" | "connect" | Net::SSLeay::SSL object 268=item tls => "accept" | "connect" | Net::SSLeay::SSL object
257 269
258When this parameter is given, it enables TLS (SSL) mode, that means 270When this parameter is given, it enables TLS (SSL) mode, that means
259AnyEvent will start a TLS handshake as soon as the conenction has been 271AnyEvent will start a TLS handshake as soon as the conenction has been
296 308
297Instead of an object, you can also specify a hash reference with C<< key 309Instead of an object, you can also specify a hash reference with C<< key
298=> value >> pairs. Those will be passed to L<AnyEvent::TLS> to create a 310=> value >> pairs. Those will be passed to L<AnyEvent::TLS> to create a
299new TLS context object. 311new TLS context object.
300 312
301=item on_starttls => $cb->($handle, $success) 313=item on_starttls => $cb->($handle, $success[, $error_message])
302 314
303This callback will be invoked when the TLS/SSL handshake has finished. If 315This callback will be invoked when the TLS/SSL handshake has finished. If
304C<$success> is true, then the TLS handshake succeeded, otherwise it failed 316C<$success> is true, then the TLS handshake succeeded, otherwise it failed
305(C<on_stoptls> will not be called in this case). 317(C<on_stoptls> will not be called in this case).
306 318
307The session in C<< $handle->{tls} >> can still be examined in this 319The session in C<< $handle->{tls} >> can still be examined in this
308callback, even when the handshake was not successful. 320callback, even when the handshake was not successful.
321
322TLS handshake failures will not cause C<on_error> to be invoked when this
323callback is in effect, instead, the error message will be passed to C<on_starttls>.
324
325Without this callback, handshake failures lead to C<on_error> being
326called, as normal.
327
328Note that you cannot call C<starttls> right again in this callback. If you
329need to do that, start an zero-second timer instead whose callback can
330then call C<< ->starttls >> again.
309 331
310=item on_stoptls => $cb->($handle) 332=item on_stoptls => $cb->($handle)
311 333
312When a SSLv3/TLS shutdown/close notify/EOF is detected and this callback is 334When a SSLv3/TLS shutdown/close notify/EOF is detected and this callback is
313set, then it will be invoked after freeing the TLS session. If it is not, 335set, then it will be invoked after freeing the TLS session. If it is not,
349 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay}; 371 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay};
350 372
351 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 373 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
352 if $self->{tls}; 374 if $self->{tls};
353 375
354 $self->on_drain (delete $self->{on_drain}) if exists $self->{on_drain}; 376 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
355 377
356 $self->start_read 378 $self->start_read
357 if $self->{on_read}; 379 if $self->{on_read};
358 380
359 $self->{fh} && $self 381 $self->{fh} && $self
360} 382}
361 383
362sub _shutdown { 384#sub _shutdown {
363 my ($self) = @_; 385# my ($self) = @_;
364 386#
365 delete @$self{qw(_tw _rw _ww fh wbuf on_read _queue)}; 387# delete @$self{qw(_tw _rw _ww fh wbuf on_read _queue)};
366 $self->{_eof} = 1; # tell starttls et. al to stop trying 388# $self->{_eof} = 1; # tell starttls et. al to stop trying
367 389#
368 &_freetls; 390# &_freetls;
369} 391#}
370 392
371sub _error { 393sub _error {
372 my ($self, $errno, $fatal, $message) = @_; 394 my ($self, $errno, $fatal, $message) = @_;
373 395
374 $self->_shutdown
375 if $fatal;
376
377 $! = $errno; 396 $! = $errno;
378 $message ||= "$!"; 397 $message ||= "$!";
379 398
380 if ($self->{on_error}) { 399 if ($self->{on_error}) {
381 $self->{on_error}($self, $fatal, $message); 400 $self->{on_error}($self, $fatal, $message);
401 $self->destroy if $fatal;
382 } elsif ($self->{fh}) { 402 } elsif ($self->{fh}) {
403 $self->destroy;
383 Carp::croak "AnyEvent::Handle uncaught error: $message"; 404 Carp::croak "AnyEvent::Handle uncaught error: $message";
384 } 405 }
385} 406}
386 407
387=item $fh = $handle->fh 408=item $fh = $handle->fh
502 $self->{_activity} = $NOW; 523 $self->{_activity} = $NOW;
503 524
504 if ($self->{on_timeout}) { 525 if ($self->{on_timeout}) {
505 $self->{on_timeout}($self); 526 $self->{on_timeout}($self);
506 } else { 527 } else {
507 $self->_error (&Errno::ETIMEDOUT); 528 $self->_error (Errno::ETIMEDOUT);
508 } 529 }
509 530
510 # callback could have changed timeout value, optimise 531 # callback could have changed timeout value, optimise
511 return unless $self->{timeout}; 532 return unless $self->{timeout};
512 533
575 Scalar::Util::weaken $self; 596 Scalar::Util::weaken $self;
576 597
577 my $cb = sub { 598 my $cb = sub {
578 my $len = syswrite $self->{fh}, $self->{wbuf}; 599 my $len = syswrite $self->{fh}, $self->{wbuf};
579 600
580 if ($len >= 0) { 601 if (defined $len) {
581 substr $self->{wbuf}, 0, $len, ""; 602 substr $self->{wbuf}, 0, $len, "";
582 603
583 $self->{_activity} = AnyEvent->now; 604 $self->{_activity} = AnyEvent->now;
584 605
585 $self->{on_drain}($self) 606 $self->{on_drain}($self)
854 875
855 if ( 876 if (
856 defined $self->{rbuf_max} 877 defined $self->{rbuf_max}
857 && $self->{rbuf_max} < length $self->{rbuf} 878 && $self->{rbuf_max} < length $self->{rbuf}
858 ) { 879 ) {
859 $self->_error (&Errno::ENOSPC, 1), return; 880 $self->_error (Errno::ENOSPC, 1), return;
860 } 881 }
861 882
862 while () { 883 while () {
863 # we need to use a separate tls read buffer, as we must not receive data while 884 # we need to use a separate tls read buffer, as we must not receive data while
864 # we are draining the buffer, and this can only happen with TLS. 885 # we are draining the buffer, and this can only happen with TLS.
868 889
869 if (my $cb = shift @{ $self->{_queue} }) { 890 if (my $cb = shift @{ $self->{_queue} }) {
870 unless ($cb->($self)) { 891 unless ($cb->($self)) {
871 if ($self->{_eof}) { 892 if ($self->{_eof}) {
872 # no progress can be made (not enough data and no data forthcoming) 893 # no progress can be made (not enough data and no data forthcoming)
873 $self->_error (&Errno::EPIPE, 1), return; 894 $self->_error (Errno::EPIPE, 1), return;
874 } 895 }
875 896
876 unshift @{ $self->{_queue} }, $cb; 897 unshift @{ $self->{_queue} }, $cb;
877 last; 898 last;
878 } 899 }
886 && !@{ $self->{_queue} } # and the queue is still empty 907 && !@{ $self->{_queue} } # and the queue is still empty
887 && $self->{on_read} # but we still have on_read 908 && $self->{on_read} # but we still have on_read
888 ) { 909 ) {
889 # no further data will arrive 910 # no further data will arrive
890 # so no progress can be made 911 # so no progress can be made
891 $self->_error (&Errno::EPIPE, 1), return 912 $self->_error (Errno::EPIPE, 1), return
892 if $self->{_eof}; 913 if $self->{_eof};
893 914
894 last; # more data might arrive 915 last; # more data might arrive
895 } 916 }
896 } else { 917 } else {
1146 return 1; 1167 return 1;
1147 } 1168 }
1148 1169
1149 # reject 1170 # reject
1150 if ($reject && $$rbuf =~ $reject) { 1171 if ($reject && $$rbuf =~ $reject) {
1151 $self->_error (&Errno::EBADMSG); 1172 $self->_error (Errno::EBADMSG);
1152 } 1173 }
1153 1174
1154 # skip 1175 # skip
1155 if ($skip && $$rbuf =~ $skip) { 1176 if ($skip && $$rbuf =~ $skip) {
1156 $data .= substr $$rbuf, 0, $+[0], ""; 1177 $data .= substr $$rbuf, 0, $+[0], "";
1172 my ($self, $cb) = @_; 1193 my ($self, $cb) = @_;
1173 1194
1174 sub { 1195 sub {
1175 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) { 1196 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
1176 if ($_[0]{rbuf} =~ /[^0-9]/) { 1197 if ($_[0]{rbuf} =~ /[^0-9]/) {
1177 $self->_error (&Errno::EBADMSG); 1198 $self->_error (Errno::EBADMSG);
1178 } 1199 }
1179 return; 1200 return;
1180 } 1201 }
1181 1202
1182 my $len = $1; 1203 my $len = $1;
1185 my $string = $_[1]; 1206 my $string = $_[1];
1186 $_[0]->unshift_read (chunk => 1, sub { 1207 $_[0]->unshift_read (chunk => 1, sub {
1187 if ($_[1] eq ",") { 1208 if ($_[1] eq ",") {
1188 $cb->($_[0], $string); 1209 $cb->($_[0], $string);
1189 } else { 1210 } else {
1190 $self->_error (&Errno::EBADMSG); 1211 $self->_error (Errno::EBADMSG);
1191 } 1212 }
1192 }); 1213 });
1193 }); 1214 });
1194 1215
1195 1 1216 1
1285 $json->incr_skip; 1306 $json->incr_skip;
1286 1307
1287 $self->{rbuf} = $json->incr_text; 1308 $self->{rbuf} = $json->incr_text;
1288 $json->incr_text = ""; 1309 $json->incr_text = "";
1289 1310
1290 $self->_error (&Errno::EBADMSG); 1311 $self->_error (Errno::EBADMSG);
1291 1312
1292 () 1313 ()
1293 } else { 1314 } else {
1294 $self->{rbuf} = ""; 1315 $self->{rbuf} = "";
1295 1316
1332 # read remaining chunk 1353 # read remaining chunk
1333 $_[0]->unshift_read (chunk => $len, sub { 1354 $_[0]->unshift_read (chunk => $len, sub {
1334 if (my $ref = eval { Storable::thaw ($_[1]) }) { 1355 if (my $ref = eval { Storable::thaw ($_[1]) }) {
1335 $cb->($_[0], $ref); 1356 $cb->($_[0], $ref);
1336 } else { 1357 } else {
1337 $self->_error (&Errno::EBADMSG); 1358 $self->_error (Errno::EBADMSG);
1338 } 1359 }
1339 }); 1360 });
1340 } 1361 }
1341 1362
1342 1 1363 1
1435 my $err =Net::SSLeay::ERR_error_string (Net::SSLeay::ERR_get_error ()); 1456 my $err =Net::SSLeay::ERR_error_string (Net::SSLeay::ERR_get_error ());
1436 1457
1437 # reduce error string to look less scary 1458 # reduce error string to look less scary
1438 $err =~ s/^error:[0-9a-fA-F]{8}:[^:]+:([^:]+):/\L$1: /; 1459 $err =~ s/^error:[0-9a-fA-F]{8}:[^:]+:([^:]+):/\L$1: /;
1439 1460
1461 if ($self->{_on_starttls}) {
1462 (delete $self->{_on_starttls})->($self, undef, $err);
1463 &_freetls;
1464 } else {
1465 &_freetls;
1440 $self->_error (&Errno::EPROTO, 1, $err); 1466 $self->_error (Errno::EPROTO, 1, $err);
1467 }
1441} 1468}
1442 1469
1443# poll the write BIO and send the data if applicable 1470# poll the write BIO and send the data if applicable
1444# also decode read data if possible 1471# also decode read data if possible
1445# this is basiclaly our TLS state machine 1472# this is basiclaly our TLS state machine
1461 && ($tmp != $ERROR_SYSCALL || $!); 1488 && ($tmp != $ERROR_SYSCALL || $!);
1462 } 1489 }
1463 1490
1464 while (defined ($tmp = Net::SSLeay::read ($self->{tls}))) { 1491 while (defined ($tmp = Net::SSLeay::read ($self->{tls}))) {
1465 unless (length $tmp) { 1492 unless (length $tmp) {
1493 $self->{_on_starttls}
1494 and (delete $self->{_on_starttls})->($self, undef, "EOF during handshake"); # ???
1466 &_freetls; 1495 &_freetls;
1496
1467 if ($self->{on_stoptls}) { 1497 if ($self->{on_stoptls}) {
1468 $self->{on_stoptls}($self); 1498 $self->{on_stoptls}($self);
1469 return; 1499 return;
1470 } else { 1500 } else {
1471 # let's treat SSL-eof as we treat normal EOF 1501 # let's treat SSL-eof as we treat normal EOF
1489 $self->_drain_wbuf; 1519 $self->_drain_wbuf;
1490 } 1520 }
1491 1521
1492 $self->{_on_starttls} 1522 $self->{_on_starttls}
1493 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK () 1523 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
1494 and (delete $self->{_on_starttls})->($self, 1); 1524 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
1495} 1525}
1496 1526
1497=item $handle->starttls ($tls[, $tls_ctx]) 1527=item $handle->starttls ($tls[, $tls_ctx])
1498 1528
1499Instead of starting TLS negotiation immediately when the AnyEvent::Handle 1529Instead of starting TLS negotiation immediately when the AnyEvent::Handle
1500object is created, you can also do that at a later time by calling 1530object is created, you can also do that at a later time by calling
1501C<starttls>. 1531C<starttls>.
1532
1533Starting TLS is currently an asynchronous operation - when you push some
1534write data and then call C<< ->starttls >> then TLS negotiation will start
1535immediately, after which the queued write data is then sent.
1502 1536
1503The first argument is the same as the C<tls> constructor argument (either 1537The first argument is the same as the C<tls> constructor argument (either
1504C<"connect">, C<"accept"> or an existing Net::SSLeay object). 1538C<"connect">, C<"accept"> or an existing Net::SSLeay object).
1505 1539
1506The second argument is the optional C<AnyEvent::TLS> object that is used 1540The second argument is the optional C<AnyEvent::TLS> object that is used
1531 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL (); 1565 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL ();
1532 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ (); 1566 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ ();
1533 1567
1534 $ctx ||= $self->{tls_ctx}; 1568 $ctx ||= $self->{tls_ctx};
1535 1569
1570 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session
1571
1536 if ("HASH" eq ref $ctx) { 1572 if ("HASH" eq ref $ctx) {
1537 require AnyEvent::TLS; 1573 require AnyEvent::TLS;
1538
1539 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context
1540 1574
1541 if ($ctx->{cache}) { 1575 if ($ctx->{cache}) {
1542 my $key = $ctx+0; 1576 my $key = $ctx+0;
1543 $ctx = $TLS_CACHE{$key} ||= new AnyEvent::TLS %$ctx; 1577 $ctx = $TLS_CACHE{$key} ||= new AnyEvent::TLS %$ctx;
1544 } else { 1578 } else {
1570 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ()); 1604 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
1571 1605
1572 Net::SSLeay::set_bio ($ssl, $self->{_rbio}, $self->{_wbio}); 1606 Net::SSLeay::set_bio ($ssl, $self->{_rbio}, $self->{_wbio});
1573 1607
1574 $self->{_on_starttls} = sub { $_[0]{on_starttls}(@_) } 1608 $self->{_on_starttls} = sub { $_[0]{on_starttls}(@_) }
1575 if exists $self->{on_starttls}; 1609 if $self->{on_starttls};
1576 1610
1577 &_dotls; # need to trigger the initial handshake 1611 &_dotls; # need to trigger the initial handshake
1578 $self->start_read; # make sure we actually do read 1612 $self->start_read; # make sure we actually do read
1579} 1613}
1580 1614
1604sub _freetls { 1638sub _freetls {
1605 my ($self) = @_; 1639 my ($self) = @_;
1606 1640
1607 return unless $self->{tls}; 1641 return unless $self->{tls};
1608 1642
1609 $self->{_on_starttls}
1610 and (delete $self->{_on_starttls})->($self, undef);
1611
1612 $self->{tls_ctx}->_put_session (delete $self->{tls}); 1643 $self->{tls_ctx}->_put_session (delete $self->{tls});
1613 1644
1614 delete @$self{qw(_rbio _wbio _tls_wbuf)}; 1645 delete @$self{qw(_rbio _wbio _tls_wbuf _on_starttls)};
1615} 1646}
1616 1647
1617sub DESTROY { 1648sub DESTROY {
1618 my ($self) = @_; 1649 my ($self) = @_;
1619 1650
1620 &_freetls; 1651 &_freetls;
1621 1652
1622 my $linger = exists $self->{linger} ? $self->{linger} : 3600; 1653 my $linger = exists $self->{linger} ? $self->{linger} : 3600;
1623 1654
1624 if ($linger && length $self->{wbuf}) { 1655 if ($linger && length $self->{wbuf} && $self->{fh}) {
1625 my $fh = delete $self->{fh}; 1656 my $fh = delete $self->{fh};
1626 my $wbuf = delete $self->{wbuf}; 1657 my $wbuf = delete $self->{wbuf};
1627 1658
1628 my @linger; 1659 my @linger;
1629 1660
1653callbacks, as well as code outside. It does I<NOT> work in a read or write 1684callbacks, as well as code outside. It does I<NOT> work in a read or write
1654callback, so when you want to destroy the AnyEvent::Handle object from 1685callback, so when you want to destroy the AnyEvent::Handle object from
1655within such an callback. You I<MUST> call C<< ->destroy >> explicitly in 1686within such an callback. You I<MUST> call C<< ->destroy >> explicitly in
1656that case. 1687that case.
1657 1688
1689Destroying the handle object in this way has the advantage that callbacks
1690will be removed as well, so if those are the only reference holders (as
1691is common), then one doesn't need to do anything special to break any
1692reference cycles.
1693
1658The handle might still linger in the background and write out remaining 1694The handle might still linger in the background and write out remaining
1659data, as specified by the C<linger> option, however. 1695data, as specified by the C<linger> option, however.
1660 1696
1661=cut 1697=cut
1662 1698
1729 1765
1730 $handle->on_read (sub { }); 1766 $handle->on_read (sub { });
1731 $handle->on_eof (undef); 1767 $handle->on_eof (undef);
1732 $handle->on_error (sub { 1768 $handle->on_error (sub {
1733 my $data = delete $_[0]{rbuf}; 1769 my $data = delete $_[0]{rbuf};
1734 undef $handle;
1735 }); 1770 });
1736 1771
1737The reason to use C<on_error> is that TCP connections, due to latencies 1772The reason to use C<on_error> is that TCP connections, due to latencies
1738and packets loss, might get closed quite violently with an error, when in 1773and packets loss, might get closed quite violently with an error, when in
1739fact, all data has been received. 1774fact, all data has been received.
1755 $handle->on_drain (sub { 1790 $handle->on_drain (sub {
1756 warn "all data submitted to the kernel\n"; 1791 warn "all data submitted to the kernel\n";
1757 undef $handle; 1792 undef $handle;
1758 }); 1793 });
1759 1794
1795If you just want to queue some data and then signal EOF to the other side,
1796consider using C<< ->push_shutdown >> instead.
1797
1798=item I want to contact a TLS/SSL server, I don't care about security.
1799
1800If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS,
1801simply connect to it and then create the AnyEvent::Handle with the C<tls>
1802parameter:
1803
1804 tcp_connect $host, $port, sub {
1805 my ($fh) = @_;
1806
1807 my $handle = new AnyEvent::Handle
1808 fh => $fh,
1809 tls => "connect",
1810 on_error => sub { ... };
1811
1812 $handle->push_write (...);
1813 };
1814
1815=item I want to contact a TLS/SSL server, I do care about security.
1816
1817Then you should additionally enable certificate verification, including
1818peername verification, if the protocol you use supports it (see
1819L<AnyEvent::TLS>, C<verify_peername>).
1820
1821E.g. for HTTPS:
1822
1823 tcp_connect $host, $port, sub {
1824 my ($fh) = @_;
1825
1826 my $handle = new AnyEvent::Handle
1827 fh => $fh,
1828 peername => $host,
1829 tls => "connect",
1830 tls_ctx => { verify => 1, verify_peername => "https" },
1831 ...
1832
1833Note that you must specify the hostname you connected to (or whatever
1834"peername" the protocol needs) as the C<peername> argument, otherwise no
1835peername verification will be done.
1836
1837The above will use the system-dependent default set of trusted CA
1838certificates. If you want to check against a specific CA, add the
1839C<ca_file> (or C<ca_cert>) arguments to C<tls_ctx>:
1840
1841 tls_ctx => {
1842 verify => 1,
1843 verify_peername => "https",
1844 ca_file => "my-ca-cert.pem",
1845 },
1846
1847=item I want to create a TLS/SSL server, how do I do that?
1848
1849Well, you first need to get a server certificate and key. You have
1850three options: a) ask a CA (buy one, use cacert.org etc.) b) create a
1851self-signed certificate (cheap. check the search engine of your choice,
1852there are many tutorials on the net) or c) make your own CA (tinyca2 is a
1853nice program for that purpose).
1854
1855Then create a file with your private key (in PEM format, see
1856L<AnyEvent::TLS>), followed by the certificate (also in PEM format). The
1857file should then look like this:
1858
1859 -----BEGIN RSA PRIVATE KEY-----
1860 ...header data
1861 ... lots of base64'y-stuff
1862 -----END RSA PRIVATE KEY-----
1863
1864 -----BEGIN CERTIFICATE-----
1865 ... lots of base64'y-stuff
1866 -----END CERTIFICATE-----
1867
1868The important bits are the "PRIVATE KEY" and "CERTIFICATE" parts. Then
1869specify this file as C<cert_file>:
1870
1871 tcp_server undef, $port, sub {
1872 my ($fh) = @_;
1873
1874 my $handle = new AnyEvent::Handle
1875 fh => $fh,
1876 tls => "accept",
1877 tls_ctx => { cert_file => "my-server-keycert.pem" },
1878 ...
1879
1880When you have intermediate CA certificates that your clients might not
1881know about, just append them to the C<cert_file>.
1882
1760=back 1883=back
1761 1884
1762 1885
1763=head1 SUBCLASSING AnyEvent::Handle 1886=head1 SUBCLASSING AnyEvent::Handle
1764 1887

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines