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.182 by root, Thu Sep 3 12:35:01 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 gives you
312the most portable way of getting urgent data, by putting it into the
313stream.
314
278=item read_size => <bytes> 315=item read_size => <bytes>
279 316
280The default read block size (the amount of bytes this module will 317The default read block size (the amount of bytes this module will
281try to read during each loop iteration, which affects memory 318try to read during each loop iteration, which affects memory
282requirements). Default: C<8192>. 319requirements). Default: C<8192>.
438 delete $self->{_skip_drain_rbuf}; 475 delete $self->{_skip_drain_rbuf};
439 $self->_start; 476 $self->_start;
440 477
441 $self->{on_connect} 478 $self->{on_connect}
442 and $self->{on_connect}($self, $host, $port, sub { 479 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)}; 480 delete @$self{qw(fh _tw _rtw _wtw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)};
444 $self->{_skip_drain_rbuf} = 1; 481 $self->{_skip_drain_rbuf} = 1;
445 &$retry; 482 &$retry;
446 }); 483 });
447 484
448 } else { 485 } else {
474sub _start { 511sub _start {
475 my ($self) = @_; 512 my ($self) = @_;
476 513
477 AnyEvent::Util::fh_nonblocking $self->{fh}, 1; 514 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
478 515
516 $self->{_activity} =
517 $self->{_ractivity} =
479 $self->{_activity} = AnyEvent->now; 518 $self->{_wactivity} = AE::now;
480 $self->_timeout;
481 519
520 $self->timeout (delete $self->{timeout} ) if $self->{timeout};
521 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout};
522 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout};
523
482 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay}; 524 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay};
525 $self->keepalive (delete $self->{keepalive}) if exists $self->{keepalive};
526 $self->oobinline (delete $self->{oobinline}) if exists $self->{oobinline};
483 527
484 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 528 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
485 if $self->{tls}; 529 if $self->{tls};
486 530
487 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 531 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
488 532
489 $self->start_read 533 $self->start_read
490 if $self->{on_read} || @{ $self->{_queue} }; 534 if $self->{on_read} || @{ $self->{_queue} };
491 535
492 $self->_drain_wbuf; 536 $self->_drain_wbuf;
493} 537}
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 538
504sub _error { 539sub _error {
505 my ($self, $errno, $fatal, $message) = @_; 540 my ($self, $errno, $fatal, $message) = @_;
506 541
507 $! = $errno; 542 $! = $errno;
544 $_[0]{on_eof} = $_[1]; 579 $_[0]{on_eof} = $_[1];
545} 580}
546 581
547=item $handle->on_timeout ($cb) 582=item $handle->on_timeout ($cb)
548 583
549Replace the current C<on_timeout> callback, or disables the callback (but 584=item $handle->on_rtimeout ($cb)
550not the timeout) if C<$cb> = C<undef>. See the C<timeout> constructor
551argument and method.
552 585
553=cut 586=item $handle->on_wtimeout ($cb)
554 587
555sub on_timeout { 588Replace the current C<on_timeout>, C<on_rtimeout> or C<on_wtimeout>
556 $_[0]{on_timeout} = $_[1]; 589callback, or disables the callback (but not the timeout) if C<$cb> =
557} 590C<undef>. See the C<timeout> constructor argument and method.
591
592=cut
593
594# see below
558 595
559=item $handle->autocork ($boolean) 596=item $handle->autocork ($boolean)
560 597
561Enables or disables the current autocork behaviour (see C<autocork> 598Enables or disables the current autocork behaviour (see C<autocork>
562constructor argument). Changes will only take effect on the next write. 599constructor argument). Changes will only take effect on the next write.
577sub no_delay { 614sub no_delay {
578 $_[0]{no_delay} = $_[1]; 615 $_[0]{no_delay} = $_[1];
579 616
580 eval { 617 eval {
581 local $SIG{__DIE__}; 618 local $SIG{__DIE__};
582 setsockopt $_[0]{fh}, &Socket::IPPROTO_TCP, &Socket::TCP_NODELAY, int $_[1] 619 setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
583 if $_[0]{fh}; 620 if $_[0]{fh};
584 }; 621 };
585} 622}
586 623
624=item $handle->keepalive ($boolean)
625
626Enables or disables the C<keepalive> setting (see constructor argument of
627the same name for details).
628
629=cut
630
631sub keepalive {
632 $_[0]{keepalive} = $_[1];
633
634 eval {
635 local $SIG{__DIE__};
636 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
637 if $_[0]{fh};
638 };
639}
640
641=item $handle->oobinline ($boolean)
642
643Enables or disables the C<oobinline> setting (see constructor argument of
644the same name for details).
645
646=cut
647
648sub oobinline {
649 $_[0]{oobinline} = $_[1];
650
651 eval {
652 local $SIG{__DIE__};
653 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_OOBINLINE (), int $_[1]
654 if $_[0]{fh};
655 };
656}
657
658=item $handle->keepalive ($boolean)
659
660Enables or disables the C<keepalive> setting (see constructor argument of
661the same name for details).
662
663=cut
664
665sub keepalive {
666 $_[0]{keepalive} = $_[1];
667
668 eval {
669 local $SIG{__DIE__};
670 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
671 if $_[0]{fh};
672 };
673}
674
587=item $handle->on_starttls ($cb) 675=item $handle->on_starttls ($cb)
588 676
589Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument). 677Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument).
590 678
591=cut 679=cut
616 704
617############################################################################# 705#############################################################################
618 706
619=item $handle->timeout ($seconds) 707=item $handle->timeout ($seconds)
620 708
709=item $handle->rtimeout ($seconds)
710
711=item $handle->wtimeout ($seconds)
712
621Configures (or disables) the inactivity timeout. 713Configures (or disables) the inactivity timeout.
622 714
623=cut 715=item $handle->timeout_reset
624 716
625sub timeout { 717=item $handle->rtimeout_reset
718
719=item $handle->wtimeout_reset
720
721Reset the activity timeout, as if data was received or sent.
722
723These methods are cheap to call.
724
725=cut
726
727for my $dir ("", "r", "w") {
728 my $timeout = "${dir}timeout";
729 my $tw = "_${dir}tw";
730 my $on_timeout = "on_${dir}timeout";
731 my $activity = "_${dir}activity";
732 my $cb;
733
734 *$on_timeout = sub {
735 $_[0]{$on_timeout} = $_[1];
736 };
737
738 *$timeout = sub {
626 my ($self, $timeout) = @_; 739 my ($self, $new_value) = @_;
627 740
628 $self->{timeout} = $timeout; 741 $self->{$timeout} = $new_value;
629 $self->_timeout; 742 delete $self->{$tw}; &$cb;
630} 743 };
631 744
745 *{"${dir}timeout_reset"} = sub {
746 $_[0]{$activity} = AE::now;
747 };
748
749 # main workhorse:
632# reset the timeout watcher, as neccessary 750 # reset the timeout watcher, as neccessary
633# also check for time-outs 751 # also check for time-outs
634sub _timeout { 752 $cb = sub {
635 my ($self) = @_; 753 my ($self) = @_;
636 754
637 if ($self->{timeout} && $self->{fh}) { 755 if ($self->{$timeout} && $self->{fh}) {
638 my $NOW = AnyEvent->now; 756 my $NOW = AE::now;
639 757
640 # when would the timeout trigger? 758 # when would the timeout trigger?
641 my $after = $self->{_activity} + $self->{timeout} - $NOW; 759 my $after = $self->{$activity} + $self->{$timeout} - $NOW;
642 760
643 # now or in the past already? 761 # now or in the past already?
644 if ($after <= 0) { 762 if ($after <= 0) {
645 $self->{_activity} = $NOW; 763 $self->{$activity} = $NOW;
646 764
647 if ($self->{on_timeout}) { 765 if ($self->{$on_timeout}) {
648 $self->{on_timeout}($self); 766 $self->{$on_timeout}($self);
649 } else { 767 } else {
650 $self->_error (Errno::ETIMEDOUT); 768 $self->_error (Errno::ETIMEDOUT);
769 }
770
771 # callback could have changed timeout value, optimise
772 return unless $self->{$timeout};
773
774 # calculate new after
775 $after = $self->{$timeout};
651 } 776 }
652 777
653 # callback could have changed timeout value, optimise 778 Scalar::Util::weaken $self;
654 return unless $self->{timeout}; 779 return unless $self; # ->error could have destroyed $self
655 780
656 # calculate new after 781 $self->{$tw} ||= AE::timer $after, 0, sub {
657 $after = $self->{timeout}; 782 delete $self->{$tw};
783 $cb->($self);
784 };
785 } else {
786 delete $self->{$tw};
658 } 787 }
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 } 788 }
670} 789}
671 790
672############################################################################# 791#############################################################################
673 792
721 my $len = syswrite $self->{fh}, $self->{wbuf}; 840 my $len = syswrite $self->{fh}, $self->{wbuf};
722 841
723 if (defined $len) { 842 if (defined $len) {
724 substr $self->{wbuf}, 0, $len, ""; 843 substr $self->{wbuf}, 0, $len, "";
725 844
726 $self->{_activity} = AnyEvent->now; 845 $self->{_activity} = $self->{_wactivity} = AE::now;
727 846
728 $self->{on_drain}($self) 847 $self->{on_drain}($self)
729 if $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf}) 848 if $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf})
730 && $self->{on_drain}; 849 && $self->{on_drain};
731 850
737 856
738 # try to write data immediately 857 # try to write data immediately
739 $cb->() unless $self->{autocork}; 858 $cb->() unless $self->{autocork};
740 859
741 # if still data left in wbuf, we need to poll 860 # if still data left in wbuf, we need to poll
742 $self->{_ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb) 861 $self->{_ww} = AE::io $self->{fh}, 1, $cb
743 if length $self->{wbuf}; 862 if length $self->{wbuf};
744 }; 863 };
745} 864}
746 865
747our %WH; 866our %WH;
837Other languages could read single lines terminated by a newline and pass 956Other languages could read single lines terminated by a newline and pass
838this line into their JSON decoder of choice. 957this line into their JSON decoder of choice.
839 958
840=cut 959=cut
841 960
961sub json_coder() {
962 eval { require JSON::XS; JSON::XS->new->utf8 }
963 || do { require JSON; JSON->new->utf8 }
964}
965
842register_write_type json => sub { 966register_write_type json => sub {
843 my ($self, $ref) = @_; 967 my ($self, $ref) = @_;
844 968
845 require JSON; 969 my $json = $self->{json} ||= json_coder;
846 970
847 $self->{json} ? $self->{json}->encode ($ref) 971 $json->encode ($ref)
848 : JSON::encode_json ($ref)
849}; 972};
850 973
851=item storable => $reference 974=item storable => $reference
852 975
853Freezes the given reference using L<Storable> and writes it to the 976Freezes the given reference using L<Storable> and writes it to the
1146 1269
1147 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read") 1270 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
1148 ->($self, $cb, @_); 1271 ->($self, $cb, @_);
1149 } 1272 }
1150 1273
1151
1152 unshift @{ $self->{_queue} }, $cb; 1274 unshift @{ $self->{_queue} }, $cb;
1153 $self->_drain_rbuf; 1275 $self->_drain_rbuf;
1154} 1276}
1155 1277
1156=item $handle->push_read (type => @args, $cb) 1278=item $handle->push_read (type => @args, $cb)
1407=cut 1529=cut
1408 1530
1409register_read_type json => sub { 1531register_read_type json => sub {
1410 my ($self, $cb) = @_; 1532 my ($self, $cb) = @_;
1411 1533
1412 my $json = $self->{json} ||= 1534 my $json = $self->{json} ||= json_coder;
1413 eval { require JSON::XS; JSON::XS->new->utf8 }
1414 || do { require JSON; JSON->new->utf8 };
1415 1535
1416 my $data; 1536 my $data;
1417 my $rbuf = \$self->{rbuf}; 1537 my $rbuf = \$self->{rbuf};
1418 1538
1419 sub { 1539 sub {
1539 my ($self) = @_; 1659 my ($self) = @_;
1540 1660
1541 unless ($self->{_rw} || $self->{_eof}) { 1661 unless ($self->{_rw} || $self->{_eof}) {
1542 Scalar::Util::weaken $self; 1662 Scalar::Util::weaken $self;
1543 1663
1544 $self->{_rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub { 1664 $self->{_rw} = AE::io $self->{fh}, 0, sub {
1545 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf}); 1665 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1546 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1666 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
1547 1667
1548 if ($len > 0) { 1668 if ($len > 0) {
1549 $self->{_activity} = AnyEvent->now; 1669 $self->{_activity} = $self->{_ractivity} = AE::now;
1550 1670
1551 if ($self->{tls}) { 1671 if ($self->{tls}) {
1552 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf); 1672 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf);
1553 1673
1554 &_dotls ($self); 1674 &_dotls ($self);
1562 $self->_drain_rbuf; 1682 $self->_drain_rbuf;
1563 1683
1564 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) { 1684 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
1565 return $self->_error ($!, 1); 1685 return $self->_error ($!, 1);
1566 } 1686 }
1567 }); 1687 };
1568 } 1688 }
1569} 1689}
1570 1690
1571our $ERROR_SYSCALL; 1691our $ERROR_SYSCALL;
1572our $ERROR_WANT_READ; 1692our $ERROR_WANT_READ;
1693 require Net::SSLeay; 1813 require Net::SSLeay;
1694 1814
1695 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL (); 1815 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL ();
1696 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ (); 1816 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ ();
1697 1817
1698 $tls = $self->{tls}; 1818 $tls = delete $self->{tls};
1699 $ctx = $self->{tls_ctx}; 1819 $ctx = $self->{tls_ctx};
1700 1820
1701 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session 1821 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session
1702 1822
1703 if ("HASH" eq ref $ctx) { 1823 if ("HASH" eq ref $ctx) {
1790 my $fh = delete $self->{fh}; 1910 my $fh = delete $self->{fh};
1791 my $wbuf = delete $self->{wbuf}; 1911 my $wbuf = delete $self->{wbuf};
1792 1912
1793 my @linger; 1913 my @linger;
1794 1914
1795 push @linger, AnyEvent->io (fh => $fh, poll => "w", cb => sub { 1915 push @linger, AE::io $fh, 1, sub {
1796 my $len = syswrite $fh, $wbuf, length $wbuf; 1916 my $len = syswrite $fh, $wbuf, length $wbuf;
1797 1917
1798 if ($len > 0) { 1918 if ($len > 0) {
1799 substr $wbuf, 0, $len, ""; 1919 substr $wbuf, 0, $len, "";
1800 } else { 1920 } else {
1801 @linger = (); # end 1921 @linger = (); # end
1802 } 1922 }
1803 }); 1923 };
1804 push @linger, AnyEvent->timer (after => $linger, cb => sub { 1924 push @linger, AE::timer $linger, 0, sub {
1805 @linger = (); 1925 @linger = ();
1806 }); 1926 };
1807 } 1927 }
1808} 1928}
1809 1929
1810=item $handle->destroy 1930=item $handle->destroy
1811 1931

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines