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.176 by root, Sun Aug 9 00:20:35 2009 UTC vs.
Revision 1.190 by root, Thu Nov 26 10:30:24 2009 UTC

1=head1 NAME 1=head1 NAME
2 2
3AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent 3AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
4
5=cut
6
7our $VERSION = 4.92;
8 4
9=head1 SYNOPSIS 5=head1 SYNOPSIS
10 6
11 use AnyEvent; 7 use AnyEvent;
12 use AnyEvent::Handle; 8 use AnyEvent::Handle;
18 on_error => sub { 14 on_error => sub {
19 my ($hdl, $fatal, $msg) = @_; 15 my ($hdl, $fatal, $msg) = @_;
20 warn "got error $msg\n"; 16 warn "got error $msg\n";
21 $hdl->destroy; 17 $hdl->destroy;
22 $cv->send; 18 $cv->send;
23 ); 19 };
24 20
25 # send some request line 21 # send some request line
26 $hdl->push_write ("getinfo\015\012"); 22 $hdl->push_write ("getinfo\015\012");
27 23
28 # read the response line 24 # read the response line
62use Errno qw(EAGAIN EINTR); 58use Errno qw(EAGAIN EINTR);
63 59
64use AnyEvent (); BEGIN { AnyEvent::common_sense } 60use AnyEvent (); BEGIN { AnyEvent::common_sense }
65use AnyEvent::Util qw(WSAEWOULDBLOCK); 61use AnyEvent::Util qw(WSAEWOULDBLOCK);
66 62
63our $VERSION = $AnyEvent::VERSION;
64
65sub _load_func($) {
66 my $func = $_[0];
67
68 unless (defined &$func) {
69 my $pkg = $func;
70 do {
71 $pkg =~ s/::[^:]+$//
72 or return;
73 eval "require $pkg";
74 } until defined &$func;
75 }
76
77 \&$func
78}
79
67=head1 METHODS 80=head1 METHODS
68 81
69=over 4 82=over 4
70 83
71=item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value... 84=item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value...
116 129
117The actual numeric host and port (the socket peername) are passed as 130The actual numeric host and port (the socket peername) are passed as
118parameters, together with a retry callback. 131parameters, together with a retry callback.
119 132
120When, for some reason, the handle is not acceptable, then calling 133When, for some reason, the handle is not acceptable, then calling
121C<$retry> will continue with the next conenction target (in case of 134C<$retry> will continue with the next connection target (in case of
122multi-homed hosts or SRV records there can be multiple connection 135multi-homed hosts or SRV records there can be multiple connection
123endpoints). When it is called then the read and write queues, eof status, 136endpoints). At the time it is called the read and write queues, eof
124tls status and similar properties of the handle are being reset. 137status, tls status and similar properties of the handle will have been
138reset.
125 139
126In most cases, ignoring the C<$retry> parameter is the way to go. 140In most cases, ignoring the C<$retry> parameter is the way to go.
127 141
128=item on_connect_error => $cb->($handle, $message) 142=item on_connect_error => $cb->($handle, $message)
129 143
130This callback is called when the conenction could not be 144This callback is called when the connection could not be
131established. C<$!> will contain the relevant error code, and C<$message> a 145established. C<$!> will contain the relevant error code, and C<$message> a
132message describing it (usually the same as C<"$!">). 146message describing it (usually the same as C<"$!">).
133 147
134If this callback isn't specified, then C<on_error> will be called with a 148If this callback isn't specified, then C<on_error> will be called with a
135fatal error instead. 149fatal error instead.
287accomplishd by setting this option to a true value. 301accomplishd by setting this option to a true value.
288 302
289The default is your opertaing system's default behaviour (most likely 303The default is your opertaing system's default behaviour (most likely
290enabled), this option explicitly enables or disables it, if possible. 304enabled), this option explicitly enables or disables it, if possible.
291 305
306=item keepalive => <boolean>
307
308Enables (default disable) the SO_KEEPALIVE option on the stream socket:
309normally, TCP connections have no time-out once established, so TCP
310connections, once established, can stay alive forever even when the other
311side has long gone. TCP keepalives are a cheap way to take down long-lived
312TCP connections whent he other side becomes unreachable. While the default
313is OS-dependent, TCP keepalives usually kick in after around two hours,
314and, if the other side doesn't reply, take down the TCP connection some 10
315to 15 minutes later.
316
317It is harmless to specify this option for file handles that do not support
318keepalives, and enabling it on connections that are potentially long-lived
319is usually a good idea.
320
321=item oobinline => <boolean>
322
323BSD majorly fucked up the implementation of TCP urgent data. The result
324is that almost no OS implements TCP according to the specs, and every OS
325implements it slightly differently.
326
327If you want to handle TCP urgent data, then setting this flag (the default
328is enabled) gives you the most portable way of getting urgent data, by
329putting it into the stream.
330
331Since BSD emulation of OOB data on top of TCP's urgent data can have
332security implications, AnyEvent::Handle sets this flag automatically
333unless explicitly specified. Note that setting this flag after
334establishing a connection I<may> be a bit too late (data loss could
335already have occured on BSD systems), but at least it will protect you
336from most attacks.
337
292=item read_size => <bytes> 338=item read_size => <bytes>
293 339
294The default read block size (the amount of bytes this module will 340The default read block size (the amount of bytes this module will
295try to read during each loop iteration, which affects memory 341try to read during each loop iteration, which affects memory
296requirements). Default: C<8192>. 342requirements). Default: C<8192>.
329C<undef>. 375C<undef>.
330 376
331=item tls => "accept" | "connect" | Net::SSLeay::SSL object 377=item tls => "accept" | "connect" | Net::SSLeay::SSL object
332 378
333When this parameter is given, it enables TLS (SSL) mode, that means 379When this parameter is given, it enables TLS (SSL) mode, that means
334AnyEvent will start a TLS handshake as soon as the conenction has been 380AnyEvent will start a TLS handshake as soon as the connection has been
335established and will transparently encrypt/decrypt data afterwards. 381established and will transparently encrypt/decrypt data afterwards.
336 382
337All TLS protocol errors will be signalled as C<EPROTO>, with an 383All TLS protocol errors will be signalled as C<EPROTO>, with an
338appropriate error message. 384appropriate error message.
339 385
452 delete $self->{_skip_drain_rbuf}; 498 delete $self->{_skip_drain_rbuf};
453 $self->_start; 499 $self->_start;
454 500
455 $self->{on_connect} 501 $self->{on_connect}
456 and $self->{on_connect}($self, $host, $port, sub { 502 and $self->{on_connect}($self, $host, $port, sub {
457 delete @$self{qw(fh _tw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)}; 503 delete @$self{qw(fh _tw _rtw _wtw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)};
458 $self->{_skip_drain_rbuf} = 1; 504 $self->{_skip_drain_rbuf} = 1;
459 &$retry; 505 &$retry;
460 }); 506 });
461 507
462 } else { 508 } else {
492 538
493 $self->{_activity} = 539 $self->{_activity} =
494 $self->{_ractivity} = 540 $self->{_ractivity} =
495 $self->{_wactivity} = AE::now; 541 $self->{_wactivity} = AE::now;
496 542
497 $self->timeout (delete $self->{timeout} ) if $self->{timeout}; 543 $self->timeout (delete $self->{timeout} ) if $self->{timeout};
498 $self->rtimeout (delete $self->{rtimeout}) if $self->{rtimeout}; 544 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout};
499 $self->wtimeout (delete $self->{wtimeout}) if $self->{wtimeout}; 545 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout};
500 546
501 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay}; 547 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay} && $self->{no_delay};
548 $self->keepalive (delete $self->{keepalive}) if exists $self->{keepalive} && $self->{keepalive};
502 549
550 $self->oobinline (exists $self->{oobinline} ? delete $self->{oobinline} : 1);
551
503 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 552 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
504 if $self->{tls}; 553 if $self->{tls};
505 554
506 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 555 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
507 556
508 $self->start_read 557 $self->start_read
509 if $self->{on_read} || @{ $self->{_queue} }; 558 if $self->{on_read} || @{ $self->{_queue} };
510 559
511 $self->_drain_wbuf; 560 $self->_drain_wbuf;
512} 561}
513
514#sub _shutdown {
515# my ($self) = @_;
516#
517# delete @$self{qw(_tw _rw _ww fh wbuf on_read _queue)};
518# $self->{_eof} = 1; # tell starttls et. al to stop trying
519#
520# &_freetls;
521#}
522 562
523sub _error { 563sub _error {
524 my ($self, $errno, $fatal, $message) = @_; 564 my ($self, $errno, $fatal, $message) = @_;
525 565
526 $! = $errno; 566 $! = $errno;
527 $message ||= "$!"; 567 $message ||= "$!";
528 568
529 if ($self->{on_error}) { 569 if ($self->{on_error}) {
530 $self->{on_error}($self, $fatal, $message); 570 $self->{on_error}($self, $fatal, $message);
531 $self->destroy if $fatal; 571 $self->destroy if $fatal;
532 } elsif ($self->{fh}) { 572 } elsif ($self->{fh} || $self->{connect}) {
533 $self->destroy; 573 $self->destroy;
534 Carp::croak "AnyEvent::Handle uncaught error: $message"; 574 Carp::croak "AnyEvent::Handle uncaught error: $message";
535 } 575 }
536} 576}
537 577
598sub no_delay { 638sub no_delay {
599 $_[0]{no_delay} = $_[1]; 639 $_[0]{no_delay} = $_[1];
600 640
601 eval { 641 eval {
602 local $SIG{__DIE__}; 642 local $SIG{__DIE__};
603 setsockopt $_[0]{fh}, &Socket::IPPROTO_TCP, &Socket::TCP_NODELAY, int $_[1] 643 setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
604 if $_[0]{fh}; 644 if $_[0]{fh};
605 }; 645 };
606} 646}
607 647
648=item $handle->keepalive ($boolean)
649
650Enables or disables the C<keepalive> setting (see constructor argument of
651the same name for details).
652
653=cut
654
655sub keepalive {
656 $_[0]{keepalive} = $_[1];
657
658 eval {
659 local $SIG{__DIE__};
660 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
661 if $_[0]{fh};
662 };
663}
664
665=item $handle->oobinline ($boolean)
666
667Enables or disables the C<oobinline> setting (see constructor argument of
668the same name for details).
669
670=cut
671
672sub oobinline {
673 $_[0]{oobinline} = $_[1];
674
675 eval {
676 local $SIG{__DIE__};
677 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_OOBINLINE (), int $_[1]
678 if $_[0]{fh};
679 };
680}
681
682=item $handle->keepalive ($boolean)
683
684Enables or disables the C<keepalive> setting (see constructor argument of
685the same name for details).
686
687=cut
688
689sub keepalive {
690 $_[0]{keepalive} = $_[1];
691
692 eval {
693 local $SIG{__DIE__};
694 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
695 if $_[0]{fh};
696 };
697}
698
608=item $handle->on_starttls ($cb) 699=item $handle->on_starttls ($cb)
609 700
610Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument). 701Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument).
611 702
612=cut 703=cut
619 710
620Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument). 711Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument).
621 712
622=cut 713=cut
623 714
624sub on_starttls { 715sub on_stoptls {
625 $_[0]{on_stoptls} = $_[1]; 716 $_[0]{on_stoptls} = $_[1];
626} 717}
627 718
628=item $handle->rbuf_max ($max_octets) 719=item $handle->rbuf_max ($max_octets)
629 720
796 }; 887 };
797} 888}
798 889
799our %WH; 890our %WH;
800 891
892# deprecated
801sub register_write_type($$) { 893sub register_write_type($$) {
802 $WH{$_[0]} = $_[1]; 894 $WH{$_[0]} = $_[1];
803} 895}
804 896
805sub push_write { 897sub push_write {
806 my $self = shift; 898 my $self = shift;
807 899
808 if (@_ > 1) { 900 if (@_ > 1) {
809 my $type = shift; 901 my $type = shift;
810 902
903 @_ = ($WH{$type} ||= _load_func "$type\::anyevent_write_type"
811 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write") 904 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_write")
812 ->($self, @_); 905 ->($self, @_);
813 } 906 }
814 907
908 # we downgrade here to avoid hard-to-track-down bugs,
909 # and diagnose the problem earlier and better.
910
815 if ($self->{tls}) { 911 if ($self->{tls}) {
816 $self->{_tls_wbuf} .= $_[0]; 912 utf8::downgrade $self->{_tls_wbuf} .= $_[0];
817 &_dotls ($self) if $self->{fh}; 913 &_dotls ($self) if $self->{fh};
818 } else { 914 } else {
819 $self->{wbuf} .= $_[0]; 915 utf8::downgrade $self->{wbuf} .= $_[0];
820 $self->_drain_wbuf if $self->{fh}; 916 $self->_drain_wbuf if $self->{fh};
821 } 917 }
822} 918}
823 919
824=item $handle->push_write (type => @args) 920=item $handle->push_write (type => @args)
825 921
826Instead of formatting your data yourself, you can also let this module do 922Instead of formatting your data yourself, you can also let this module
827the job by specifying a type and type-specific arguments. 923do the job by specifying a type and type-specific arguments. You
924can also specify the (fully qualified) name of a package, in which
925case AnyEvent tries to load the package and then expects to find the
926C<anyevent_read_type> function inside (see "custom write types", below).
828 927
829Predefined types are (if you have ideas for additional types, feel free to 928Predefined types are (if you have ideas for additional types, feel free to
830drop by and tell us): 929drop by and tell us):
831 930
832=over 4 931=over 4
889Other languages could read single lines terminated by a newline and pass 988Other languages could read single lines terminated by a newline and pass
890this line into their JSON decoder of choice. 989this line into their JSON decoder of choice.
891 990
892=cut 991=cut
893 992
993sub json_coder() {
994 eval { require JSON::XS; JSON::XS->new->utf8 }
995 || do { require JSON; JSON->new->utf8 }
996}
997
894register_write_type json => sub { 998register_write_type json => sub {
895 my ($self, $ref) = @_; 999 my ($self, $ref) = @_;
896 1000
897 require JSON; 1001 my $json = $self->{json} ||= json_coder;
898 1002
899 $self->{json} ? $self->{json}->encode ($ref) 1003 $json->encode ($ref)
900 : JSON::encode_json ($ref)
901}; 1004};
902 1005
903=item storable => $reference 1006=item storable => $reference
904 1007
905Freezes the given reference using L<Storable> and writes it to the 1008Freezes the given reference using L<Storable> and writes it to the
940 1043
941 delete $self->{low_water_mark}; 1044 delete $self->{low_water_mark};
942 $self->on_drain (sub { shutdown $_[0]{fh}, 1 }); 1045 $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
943} 1046}
944 1047
945=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 1048=item custom write types - Package::anyevent_write_type $handle, @args
946 1049
947This function (not method) lets you add your own types to C<push_write>. 1050Instead of one of the predefined types, you can also specify the name of
1051a package. AnyEvent will try to load the package and then expects to find
1052a function named C<anyevent_write_type> inside. If it isn't found, it
1053progressively tries to load the parent package until it either finds the
1054function (good) or runs out of packages (bad).
1055
948Whenever the given C<type> is used, C<push_write> will invoke the code 1056Whenever the given C<type> is used, C<push_write> will the function with
949reference with the handle object and the remaining arguments. 1057the handle object and the remaining arguments.
950 1058
951The code reference is supposed to return a single octet string that will 1059The function is supposed to return a single octet string that will be
952be appended to the write buffer. 1060appended to the write buffer, so you cna mentally treat this function as a
1061"arguments to on-the-wire-format" converter.
953 1062
954Note that this is a function, and all types registered this way will be 1063Example: implement a custom write type C<join> that joins the remaining
955global, so try to use unique names. 1064arguments using the first one.
1065
1066 $handle->push_write (My::Type => " ", 1,2,3);
1067
1068 # uses the following package, which can be defined in the "My::Type" or in
1069 # the "My" modules to be auto-loaded, or just about anywhere when the
1070 # My::Type::anyevent_write_type is defined before invoking it.
1071
1072 package My::Type;
1073
1074 sub anyevent_write_type {
1075 my ($handle, $delim, @args) = @_;
1076
1077 join $delim, @args
1078 }
956 1079
957=cut 1080=cut
958 1081
959############################################################################# 1082#############################################################################
960 1083
1179 my $cb = pop; 1302 my $cb = pop;
1180 1303
1181 if (@_) { 1304 if (@_) {
1182 my $type = shift; 1305 my $type = shift;
1183 1306
1307 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1184 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 1308 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_read")
1185 ->($self, $cb, @_); 1309 ->($self, $cb, @_);
1186 } 1310 }
1187 1311
1188 push @{ $self->{_queue} }, $cb; 1312 push @{ $self->{_queue} }, $cb;
1189 $self->_drain_rbuf; 1313 $self->_drain_rbuf;
1198 1322
1199 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read") 1323 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
1200 ->($self, $cb, @_); 1324 ->($self, $cb, @_);
1201 } 1325 }
1202 1326
1203
1204 unshift @{ $self->{_queue} }, $cb; 1327 unshift @{ $self->{_queue} }, $cb;
1205 $self->_drain_rbuf; 1328 $self->_drain_rbuf;
1206} 1329}
1207 1330
1208=item $handle->push_read (type => @args, $cb) 1331=item $handle->push_read (type => @args, $cb)
1209 1332
1210=item $handle->unshift_read (type => @args, $cb) 1333=item $handle->unshift_read (type => @args, $cb)
1211 1334
1212Instead of providing a callback that parses the data itself you can chose 1335Instead of providing a callback that parses the data itself you can chose
1213between a number of predefined parsing formats, for chunks of data, lines 1336between a number of predefined parsing formats, for chunks of data, lines
1214etc. 1337etc. You can also specify the (fully qualified) name of a package, in
1338which case AnyEvent tries to load the package and then expects to find the
1339C<anyevent_read_type> function inside (see "custom read types", below).
1215 1340
1216Predefined types are (if you have ideas for additional types, feel free to 1341Predefined types are (if you have ideas for additional types, feel free to
1217drop by and tell us): 1342drop by and tell us):
1218 1343
1219=over 4 1344=over 4
1459=cut 1584=cut
1460 1585
1461register_read_type json => sub { 1586register_read_type json => sub {
1462 my ($self, $cb) = @_; 1587 my ($self, $cb) = @_;
1463 1588
1464 my $json = $self->{json} ||= 1589 my $json = $self->{json} ||= json_coder;
1465 eval { require JSON::XS; JSON::XS->new->utf8 }
1466 || do { require JSON; JSON->new->utf8 };
1467 1590
1468 my $data; 1591 my $data;
1469 my $rbuf = \$self->{rbuf}; 1592 my $rbuf = \$self->{rbuf};
1470 1593
1471 sub { 1594 sub {
1540 } 1663 }
1541}; 1664};
1542 1665
1543=back 1666=back
1544 1667
1545=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1668=item custom read types - Package::anyevent_read_type $handle, $cb, @args
1546 1669
1547This function (not method) lets you add your own types to C<push_read>. 1670Instead of one of the predefined types, you can also specify the name
1671of a package. AnyEvent will try to load the package and then expects to
1672find a function named C<anyevent_read_type> inside. If it isn't found, it
1673progressively tries to load the parent package until it either finds the
1674function (good) or runs out of packages (bad).
1548 1675
1549Whenever the given C<type> is used, C<push_read> will invoke the code 1676Whenever this type is used, C<push_read> will invoke the function with the
1550reference with the handle object, the callback and the remaining 1677handle object, the original callback and the remaining arguments.
1551arguments.
1552 1678
1553The code reference is supposed to return a callback (usually a closure) 1679The function is supposed to return a callback (usually a closure) that
1554that works as a plain read callback (see C<< ->push_read ($cb) >>). 1680works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
1681mentally treat the function as a "configurable read type to read callback"
1682converter.
1555 1683
1556It should invoke the passed callback when it is done reading (remember to 1684It should invoke the original callback when it is done reading (remember
1557pass C<$handle> as first argument as all other callbacks do that). 1685to pass C<$handle> as first argument as all other callbacks do that,
1686although there is no strict requirement on this).
1558 1687
1559Note that this is a function, and all types registered this way will be
1560global, so try to use unique names.
1561
1562For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, 1688For examples, see the source of this module (F<perldoc -m
1563search for C<register_read_type>)). 1689AnyEvent::Handle>, search for C<register_read_type>)).
1564 1690
1565=item $handle->stop_read 1691=item $handle->stop_read
1566 1692
1567=item $handle->start_read 1693=item $handle->start_read
1568 1694
1745 require Net::SSLeay; 1871 require Net::SSLeay;
1746 1872
1747 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL (); 1873 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL ();
1748 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ (); 1874 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ ();
1749 1875
1750 $tls = $self->{tls}; 1876 $tls = delete $self->{tls};
1751 $ctx = $self->{tls_ctx}; 1877 $ctx = $self->{tls_ctx};
1752 1878
1753 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session 1879 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session
1754 1880
1755 if ("HASH" eq ref $ctx) { 1881 if ("HASH" eq ref $ctx) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines