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.172 by root, Wed Aug 5 20:50:27 2009 UTC vs.
Revision 1.184 by root, Thu Sep 3 13:14:38 2009 UTC

1package AnyEvent::Handle;
2
3use Scalar::Util ();
4use Carp ();
5use Errno qw(EAGAIN EINTR);
6
7use AnyEvent (); BEGIN { AnyEvent::common_sense }
8use AnyEvent::Util qw(WSAEWOULDBLOCK);
9
10=head1 NAME 1=head1 NAME
11 2
12AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent 3AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
13
14=cut
15
16our $VERSION = 4.901;
17 4
18=head1 SYNOPSIS 5=head1 SYNOPSIS
19 6
20 use AnyEvent; 7 use AnyEvent;
21 use AnyEvent::Handle; 8 use AnyEvent::Handle;
59C<on_error> callback. 46C<on_error> callback.
60 47
61All callbacks will be invoked with the handle object as their first 48All callbacks will be invoked with the handle object as their first
62argument. 49argument.
63 50
51=cut
52
53package AnyEvent::Handle;
54
55use Scalar::Util ();
56use List::Util ();
57use Carp ();
58use Errno qw(EAGAIN EINTR);
59
60use AnyEvent (); BEGIN { AnyEvent::common_sense }
61use AnyEvent::Util qw(WSAEWOULDBLOCK);
62
63our $VERSION = $AnyEvent::VERSION;
64
64=head1 METHODS 65=head1 METHODS
65 66
66=over 4 67=over 4
67 68
68=item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value... 69=item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value...
216memory and push it into the queue, but instead only read more data from 217memory and push it into the queue, but instead only read more data from
217the file when the write queue becomes empty. 218the file when the write queue becomes empty.
218 219
219=item timeout => $fractional_seconds 220=item timeout => $fractional_seconds
220 221
222=item rtimeout => $fractional_seconds
223
224=item wtimeout => $fractional_seconds
225
221If non-zero, then this enables an "inactivity" timeout: whenever this many 226If non-zero, then these enables an "inactivity" timeout: whenever this
222seconds pass without a successful read or write on the underlying file 227many seconds pass without a successful read or write on the underlying
223handle, the C<on_timeout> callback will be invoked (and if that one is 228file handle (or a call to C<timeout_reset>), the C<on_timeout> callback
224missing, a non-fatal C<ETIMEDOUT> error will be raised). 229will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT>
230error will be raised).
231
232There are three variants of the timeouts that work fully independent
233of each other, for both read and write, just read, and just write:
234C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks
235C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions
236C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>.
225 237
226Note that timeout processing is also active when you currently do not have 238Note that timeout processing is also active when you currently do not have
227any outstanding read or write requests: If you plan to keep the connection 239any outstanding read or write requests: If you plan to keep the connection
228idle then you should disable the timout temporarily or ignore the timeout 240idle then you should disable the timout temporarily or ignore the timeout
229in the C<on_timeout> callback, in which case AnyEvent::Handle will simply 241in the C<on_timeout> callback, in which case AnyEvent::Handle will simply
273accomplishd by setting this option to a true value. 285accomplishd by setting this option to a true value.
274 286
275The default is your opertaing system's default behaviour (most likely 287The default is your opertaing system's default behaviour (most likely
276enabled), this option explicitly enables or disables it, if possible. 288enabled), this option explicitly enables or disables it, if possible.
277 289
290=item keepalive => <boolean>
291
292Enables (default disable) the SO_KEEPALIVE option on the stream socket:
293normally, TCP connections have no time-out once established, so TCP
294conenctions, once established, can stay alive forever even when the other
295side has long gone. TCP keepalives are a cheap way to take down long-lived
296TCP connections whent he other side becomes unreachable. While the default
297is OS-dependent, TCP keepalives usually kick in after around two hours,
298and, if the other side doesn't reply, take down the TCP connection some 10
299to 15 minutes later.
300
301It is harmless to specify this option for file handles that do not support
302keepalives, and enabling it on connections that are potentially long-lived
303is usually a good idea.
304
305=item oobinline => <boolean>
306
307BSD majorly fucked up the implementation of TCP urgent data. The result
308is that almost no OS implements TCP according to the specs, and every OS
309implements it slightly differently.
310
311If you want to handle TCP urgent data, then setting this flag (the default
312is enabled) gives you the most portable way of getting urgent data, by
313putting it into the stream.
314
315Since BSD emulation of OOB data on top of TCP's urgent data can have
316security implications, AnyEvent::Handle sets this flag automatically
317unless explicitly specified. Note that setting this flag after
318establishing a connection I<may> be a bit too late (data loss could
319already have occured on BSD systems), but at least it will protect you
320from most attacks.
321
278=item read_size => <bytes> 322=item read_size => <bytes>
279 323
280The default read block size (the amount of bytes this module will 324The default read block size (the amount of bytes this module will
281try to read during each loop iteration, which affects memory 325try to read during each loop iteration, which affects memory
282requirements). Default: C<8192>. 326requirements). Default: C<8192>.
438 delete $self->{_skip_drain_rbuf}; 482 delete $self->{_skip_drain_rbuf};
439 $self->_start; 483 $self->_start;
440 484
441 $self->{on_connect} 485 $self->{on_connect}
442 and $self->{on_connect}($self, $host, $port, sub { 486 and $self->{on_connect}($self, $host, $port, sub {
443 delete @$self{qw(fh _tw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)}; 487 delete @$self{qw(fh _tw _rtw _wtw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)};
444 $self->{_skip_drain_rbuf} = 1; 488 $self->{_skip_drain_rbuf} = 1;
445 &$retry; 489 &$retry;
446 }); 490 });
447 491
448 } else { 492 } else {
474sub _start { 518sub _start {
475 my ($self) = @_; 519 my ($self) = @_;
476 520
477 AnyEvent::Util::fh_nonblocking $self->{fh}, 1; 521 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
478 522
523 $self->{_activity} =
524 $self->{_ractivity} =
479 $self->{_activity} = AnyEvent->now; 525 $self->{_wactivity} = AE::now;
480 $self->_timeout;
481 526
527 $self->timeout (delete $self->{timeout} ) if $self->{timeout};
528 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout};
529 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout};
530
482 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay}; 531 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay} && $self->{no_delay};
532 $self->keepalive (delete $self->{keepalive}) if exists $self->{keepalive} && $self->{keepalive};
483 533
534 $self->oobinline (exists $self->{oobinline} ? delete $self->{oobinline} : 1);
535
484 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 536 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
485 if $self->{tls}; 537 if $self->{tls};
486 538
487 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 539 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
488 540
489 $self->start_read 541 $self->start_read
490 if $self->{on_read} || @{ $self->{_queue} }; 542 if $self->{on_read} || @{ $self->{_queue} };
491 543
492 $self->_drain_wbuf; 544 $self->_drain_wbuf;
493} 545}
494
495#sub _shutdown {
496# my ($self) = @_;
497#
498# delete @$self{qw(_tw _rw _ww fh wbuf on_read _queue)};
499# $self->{_eof} = 1; # tell starttls et. al to stop trying
500#
501# &_freetls;
502#}
503 546
504sub _error { 547sub _error {
505 my ($self, $errno, $fatal, $message) = @_; 548 my ($self, $errno, $fatal, $message) = @_;
506 549
507 $! = $errno; 550 $! = $errno;
544 $_[0]{on_eof} = $_[1]; 587 $_[0]{on_eof} = $_[1];
545} 588}
546 589
547=item $handle->on_timeout ($cb) 590=item $handle->on_timeout ($cb)
548 591
549Replace the current C<on_timeout> callback, or disables the callback (but 592=item $handle->on_rtimeout ($cb)
550not the timeout) if C<$cb> = C<undef>. See the C<timeout> constructor
551argument and method.
552 593
553=cut 594=item $handle->on_wtimeout ($cb)
554 595
555sub on_timeout { 596Replace the current C<on_timeout>, C<on_rtimeout> or C<on_wtimeout>
556 $_[0]{on_timeout} = $_[1]; 597callback, or disables the callback (but not the timeout) if C<$cb> =
557} 598C<undef>. See the C<timeout> constructor argument and method.
599
600=cut
601
602# see below
558 603
559=item $handle->autocork ($boolean) 604=item $handle->autocork ($boolean)
560 605
561Enables or disables the current autocork behaviour (see C<autocork> 606Enables or disables the current autocork behaviour (see C<autocork>
562constructor argument). Changes will only take effect on the next write. 607constructor argument). Changes will only take effect on the next write.
577sub no_delay { 622sub no_delay {
578 $_[0]{no_delay} = $_[1]; 623 $_[0]{no_delay} = $_[1];
579 624
580 eval { 625 eval {
581 local $SIG{__DIE__}; 626 local $SIG{__DIE__};
582 setsockopt $_[0]{fh}, &Socket::IPPROTO_TCP, &Socket::TCP_NODELAY, int $_[1] 627 setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
583 if $_[0]{fh}; 628 if $_[0]{fh};
584 }; 629 };
585} 630}
586 631
632=item $handle->keepalive ($boolean)
633
634Enables or disables the C<keepalive> setting (see constructor argument of
635the same name for details).
636
637=cut
638
639sub keepalive {
640 $_[0]{keepalive} = $_[1];
641
642 eval {
643 local $SIG{__DIE__};
644 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
645 if $_[0]{fh};
646 };
647}
648
649=item $handle->oobinline ($boolean)
650
651Enables or disables the C<oobinline> setting (see constructor argument of
652the same name for details).
653
654=cut
655
656sub oobinline {
657 $_[0]{oobinline} = $_[1];
658
659 eval {
660 local $SIG{__DIE__};
661 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_OOBINLINE (), int $_[1]
662 if $_[0]{fh};
663 };
664}
665
666=item $handle->keepalive ($boolean)
667
668Enables or disables the C<keepalive> setting (see constructor argument of
669the same name for details).
670
671=cut
672
673sub keepalive {
674 $_[0]{keepalive} = $_[1];
675
676 eval {
677 local $SIG{__DIE__};
678 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
679 if $_[0]{fh};
680 };
681}
682
587=item $handle->on_starttls ($cb) 683=item $handle->on_starttls ($cb)
588 684
589Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument). 685Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument).
590 686
591=cut 687=cut
616 712
617############################################################################# 713#############################################################################
618 714
619=item $handle->timeout ($seconds) 715=item $handle->timeout ($seconds)
620 716
717=item $handle->rtimeout ($seconds)
718
719=item $handle->wtimeout ($seconds)
720
621Configures (or disables) the inactivity timeout. 721Configures (or disables) the inactivity timeout.
622 722
623=cut 723=item $handle->timeout_reset
624 724
625sub timeout { 725=item $handle->rtimeout_reset
726
727=item $handle->wtimeout_reset
728
729Reset the activity timeout, as if data was received or sent.
730
731These methods are cheap to call.
732
733=cut
734
735for my $dir ("", "r", "w") {
736 my $timeout = "${dir}timeout";
737 my $tw = "_${dir}tw";
738 my $on_timeout = "on_${dir}timeout";
739 my $activity = "_${dir}activity";
740 my $cb;
741
742 *$on_timeout = sub {
743 $_[0]{$on_timeout} = $_[1];
744 };
745
746 *$timeout = sub {
626 my ($self, $timeout) = @_; 747 my ($self, $new_value) = @_;
627 748
628 $self->{timeout} = $timeout; 749 $self->{$timeout} = $new_value;
629 $self->_timeout; 750 delete $self->{$tw}; &$cb;
630} 751 };
631 752
753 *{"${dir}timeout_reset"} = sub {
754 $_[0]{$activity} = AE::now;
755 };
756
757 # main workhorse:
632# reset the timeout watcher, as neccessary 758 # reset the timeout watcher, as neccessary
633# also check for time-outs 759 # also check for time-outs
634sub _timeout { 760 $cb = sub {
635 my ($self) = @_; 761 my ($self) = @_;
636 762
637 if ($self->{timeout} && $self->{fh}) { 763 if ($self->{$timeout} && $self->{fh}) {
638 my $NOW = AnyEvent->now; 764 my $NOW = AE::now;
639 765
640 # when would the timeout trigger? 766 # when would the timeout trigger?
641 my $after = $self->{_activity} + $self->{timeout} - $NOW; 767 my $after = $self->{$activity} + $self->{$timeout} - $NOW;
642 768
643 # now or in the past already? 769 # now or in the past already?
644 if ($after <= 0) { 770 if ($after <= 0) {
645 $self->{_activity} = $NOW; 771 $self->{$activity} = $NOW;
646 772
647 if ($self->{on_timeout}) { 773 if ($self->{$on_timeout}) {
648 $self->{on_timeout}($self); 774 $self->{$on_timeout}($self);
649 } else { 775 } else {
650 $self->_error (Errno::ETIMEDOUT); 776 $self->_error (Errno::ETIMEDOUT);
777 }
778
779 # callback could have changed timeout value, optimise
780 return unless $self->{$timeout};
781
782 # calculate new after
783 $after = $self->{$timeout};
651 } 784 }
652 785
653 # callback could have changed timeout value, optimise 786 Scalar::Util::weaken $self;
654 return unless $self->{timeout}; 787 return unless $self; # ->error could have destroyed $self
655 788
656 # calculate new after 789 $self->{$tw} ||= AE::timer $after, 0, sub {
657 $after = $self->{timeout}; 790 delete $self->{$tw};
791 $cb->($self);
792 };
793 } else {
794 delete $self->{$tw};
658 } 795 }
659
660 Scalar::Util::weaken $self;
661 return unless $self; # ->error could have destroyed $self
662
663 $self->{_tw} ||= AnyEvent->timer (after => $after, cb => sub {
664 delete $self->{_tw};
665 $self->_timeout;
666 });
667 } else {
668 delete $self->{_tw};
669 } 796 }
670} 797}
671 798
672############################################################################# 799#############################################################################
673 800
721 my $len = syswrite $self->{fh}, $self->{wbuf}; 848 my $len = syswrite $self->{fh}, $self->{wbuf};
722 849
723 if (defined $len) { 850 if (defined $len) {
724 substr $self->{wbuf}, 0, $len, ""; 851 substr $self->{wbuf}, 0, $len, "";
725 852
726 $self->{_activity} = AnyEvent->now; 853 $self->{_activity} = $self->{_wactivity} = AE::now;
727 854
728 $self->{on_drain}($self) 855 $self->{on_drain}($self)
729 if $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf}) 856 if $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf})
730 && $self->{on_drain}; 857 && $self->{on_drain};
731 858
737 864
738 # try to write data immediately 865 # try to write data immediately
739 $cb->() unless $self->{autocork}; 866 $cb->() unless $self->{autocork};
740 867
741 # if still data left in wbuf, we need to poll 868 # if still data left in wbuf, we need to poll
742 $self->{_ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb) 869 $self->{_ww} = AE::io $self->{fh}, 1, $cb
743 if length $self->{wbuf}; 870 if length $self->{wbuf};
744 }; 871 };
745} 872}
746 873
747our %WH; 874our %WH;
837Other languages could read single lines terminated by a newline and pass 964Other languages could read single lines terminated by a newline and pass
838this line into their JSON decoder of choice. 965this line into their JSON decoder of choice.
839 966
840=cut 967=cut
841 968
969sub json_coder() {
970 eval { require JSON::XS; JSON::XS->new->utf8 }
971 || do { require JSON; JSON->new->utf8 }
972}
973
842register_write_type json => sub { 974register_write_type json => sub {
843 my ($self, $ref) = @_; 975 my ($self, $ref) = @_;
844 976
845 require JSON; 977 my $json = $self->{json} ||= json_coder;
846 978
847 $self->{json} ? $self->{json}->encode ($ref) 979 $json->encode ($ref)
848 : JSON::encode_json ($ref)
849}; 980};
850 981
851=item storable => $reference 982=item storable => $reference
852 983
853Freezes the given reference using L<Storable> and writes it to the 984Freezes the given reference using L<Storable> and writes it to the
1146 1277
1147 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read") 1278 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
1148 ->($self, $cb, @_); 1279 ->($self, $cb, @_);
1149 } 1280 }
1150 1281
1151
1152 unshift @{ $self->{_queue} }, $cb; 1282 unshift @{ $self->{_queue} }, $cb;
1153 $self->_drain_rbuf; 1283 $self->_drain_rbuf;
1154} 1284}
1155 1285
1156=item $handle->push_read (type => @args, $cb) 1286=item $handle->push_read (type => @args, $cb)
1407=cut 1537=cut
1408 1538
1409register_read_type json => sub { 1539register_read_type json => sub {
1410 my ($self, $cb) = @_; 1540 my ($self, $cb) = @_;
1411 1541
1412 my $json = $self->{json} ||= 1542 my $json = $self->{json} ||= json_coder;
1413 eval { require JSON::XS; JSON::XS->new->utf8 }
1414 || do { require JSON; JSON->new->utf8 };
1415 1543
1416 my $data; 1544 my $data;
1417 my $rbuf = \$self->{rbuf}; 1545 my $rbuf = \$self->{rbuf};
1418 1546
1419 sub { 1547 sub {
1539 my ($self) = @_; 1667 my ($self) = @_;
1540 1668
1541 unless ($self->{_rw} || $self->{_eof}) { 1669 unless ($self->{_rw} || $self->{_eof}) {
1542 Scalar::Util::weaken $self; 1670 Scalar::Util::weaken $self;
1543 1671
1544 $self->{_rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub { 1672 $self->{_rw} = AE::io $self->{fh}, 0, sub {
1545 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf}); 1673 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1546 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1674 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
1547 1675
1548 if ($len > 0) { 1676 if ($len > 0) {
1549 $self->{_activity} = AnyEvent->now; 1677 $self->{_activity} = $self->{_ractivity} = AE::now;
1550 1678
1551 if ($self->{tls}) { 1679 if ($self->{tls}) {
1552 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf); 1680 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf);
1553 1681
1554 &_dotls ($self); 1682 &_dotls ($self);
1562 $self->_drain_rbuf; 1690 $self->_drain_rbuf;
1563 1691
1564 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) { 1692 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
1565 return $self->_error ($!, 1); 1693 return $self->_error ($!, 1);
1566 } 1694 }
1567 }); 1695 };
1568 } 1696 }
1569} 1697}
1570 1698
1571our $ERROR_SYSCALL; 1699our $ERROR_SYSCALL;
1572our $ERROR_WANT_READ; 1700our $ERROR_WANT_READ;
1693 require Net::SSLeay; 1821 require Net::SSLeay;
1694 1822
1695 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL (); 1823 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL ();
1696 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ (); 1824 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ ();
1697 1825
1698 $tls = $self->{tls}; 1826 $tls = delete $self->{tls};
1699 $ctx = $self->{tls_ctx}; 1827 $ctx = $self->{tls_ctx};
1700 1828
1701 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session 1829 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session
1702 1830
1703 if ("HASH" eq ref $ctx) { 1831 if ("HASH" eq ref $ctx) {
1790 my $fh = delete $self->{fh}; 1918 my $fh = delete $self->{fh};
1791 my $wbuf = delete $self->{wbuf}; 1919 my $wbuf = delete $self->{wbuf};
1792 1920
1793 my @linger; 1921 my @linger;
1794 1922
1795 push @linger, AnyEvent->io (fh => $fh, poll => "w", cb => sub { 1923 push @linger, AE::io $fh, 1, sub {
1796 my $len = syswrite $fh, $wbuf, length $wbuf; 1924 my $len = syswrite $fh, $wbuf, length $wbuf;
1797 1925
1798 if ($len > 0) { 1926 if ($len > 0) {
1799 substr $wbuf, 0, $len, ""; 1927 substr $wbuf, 0, $len, "";
1800 } else { 1928 } else {
1801 @linger = (); # end 1929 @linger = (); # end
1802 } 1930 }
1803 }); 1931 };
1804 push @linger, AnyEvent->timer (after => $linger, cb => sub { 1932 push @linger, AE::timer $linger, 0, sub {
1805 @linger = (); 1933 @linger = ();
1806 }); 1934 };
1807 } 1935 }
1808} 1936}
1809 1937
1810=item $handle->destroy 1938=item $handle->destroy
1811 1939

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines