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.218 by root, Thu Feb 24 12:04:20 2011 UTC vs.
Revision 1.231 by root, Tue Mar 27 23:47:57 2012 UTC

11 11
12 my $hdl; $hdl = new AnyEvent::Handle 12 my $hdl; $hdl = new AnyEvent::Handle
13 fh => \*STDIN, 13 fh => \*STDIN,
14 on_error => sub { 14 on_error => sub {
15 my ($hdl, $fatal, $msg) = @_; 15 my ($hdl, $fatal, $msg) = @_;
16 warn "got error $msg\n"; 16 AE::log error => "Got error $msg!";
17 $hdl->destroy; 17 $hdl->destroy;
18 $cv->send; 18 $cv->send;
19 }; 19 };
20 20
21 # send some request line 21 # send some request line
22 $hdl->push_write ("getinfo\015\012"); 22 $hdl->push_write ("getinfo\015\012");
23 23
24 # read the response line 24 # read the response line
25 $hdl->push_read (line => sub { 25 $hdl->push_read (line => sub {
26 my ($hdl, $line) = @_; 26 my ($hdl, $line) = @_;
27 warn "got line <$line>\n"; 27 say "got line <$line>";
28 $cv->send; 28 $cv->send;
29 }); 29 });
30 30
31 $cv->recv; 31 $cv->recv;
32 32
128=item on_connect => $cb->($handle, $host, $port, $retry->()) 128=item on_connect => $cb->($handle, $host, $port, $retry->())
129 129
130This callback is called when a connection has been successfully established. 130This callback is called when a connection has been successfully established.
131 131
132The peer's numeric host and port (the socket peername) are passed as 132The peer's numeric host and port (the socket peername) are passed as
133parameters, together with a retry callback. 133parameters, together with a retry callback. At the time it is called the
134read and write queues, EOF status, TLS status and similar properties of
135the handle will have been reset.
134 136
137It is not allowed to use the read or write queues while the handle object
138is connecting.
139
135If, for some reason, the handle is not acceptable, calling C<$retry> 140If, for some reason, the handle is not acceptable, calling C<$retry> will
136will continue with the next connection target (in case of multi-homed 141continue with the next connection target (in case of multi-homed hosts or
137hosts or SRV records there can be multiple connection endpoints). At the 142SRV records there can be multiple connection endpoints). The C<$retry>
138time it is called the read and write queues, eof status, tls status and 143callback can be invoked after the connect callback returns, i.e. one can
139similar properties of the handle will have been reset. 144start a handshake and then decide to retry with the next host if the
145handshake fails.
140 146
141In most cases, you should ignore the C<$retry> parameter. 147In most cases, you should ignore the C<$retry> parameter.
142 148
143=item on_connect_error => $cb->($handle, $message) 149=item on_connect_error => $cb->($handle, $message)
144 150
224If an EOF condition has been detected but no C<on_eof> callback has been 230If an EOF condition has been detected but no C<on_eof> callback has been
225set, then a fatal error will be raised with C<$!> set to <0>. 231set, then a fatal error will be raised with C<$!> set to <0>.
226 232
227=item on_drain => $cb->($handle) 233=item on_drain => $cb->($handle)
228 234
229This sets the callback that is called when the write buffer becomes empty 235This sets the callback that is called once when the write buffer becomes
230(or immediately if the buffer is empty already). 236empty (and immediately when the handle object is created).
231 237
232To append to the write buffer, use the C<< ->push_write >> method. 238To append to the write buffer, use the C<< ->push_write >> method.
233 239
234This callback is useful when you don't want to put all of your write data 240This callback is useful when you don't want to put all of your write data
235into the queue at once, for example, when you want to write the contents 241into the queue at once, for example, when you want to write the contents
359already have occured on BSD systems), but at least it will protect you 365already have occured on BSD systems), but at least it will protect you
360from most attacks. 366from most attacks.
361 367
362=item read_size => <bytes> 368=item read_size => <bytes>
363 369
364The initial read block size, the number of bytes this module will try to 370The initial read block size, the number of bytes this module will try
365read during each loop iteration. Each handle object will consume at least 371to read during each loop iteration. Each handle object will consume
366this amount of memory for the read buffer as well, so when handling many 372at least this amount of memory for the read buffer as well, so when
367connections requirements). See also C<max_read_size>. Default: C<2048>. 373handling many connections watch out for memory requirements). See also
374C<max_read_size>. Default: C<2048>.
368 375
369=item max_read_size => <bytes> 376=item max_read_size => <bytes>
370 377
371The maximum read buffer size used by the dynamic adjustment 378The maximum read buffer size used by the dynamic adjustment
372algorithm: Each time AnyEvent::Handle can read C<read_size> bytes in 379algorithm: Each time AnyEvent::Handle can read C<read_size> bytes in
879 886
880The write queue is very simple: you can add data to its end, and 887The write queue is very simple: you can add data to its end, and
881AnyEvent::Handle will automatically try to get rid of it for you. 888AnyEvent::Handle will automatically try to get rid of it for you.
882 889
883When data could be written and the write buffer is shorter then the low 890When data could be written and the write buffer is shorter then the low
884water mark, the C<on_drain> callback will be invoked. 891water mark, the C<on_drain> callback will be invoked once.
885 892
886=over 4 893=over 4
887 894
888=item $handle->on_drain ($cb) 895=item $handle->on_drain ($cb)
889 896
1080=cut 1087=cut
1081 1088
1082register_write_type storable => sub { 1089register_write_type storable => sub {
1083 my ($self, $ref) = @_; 1090 my ($self, $ref) = @_;
1084 1091
1085 require Storable; 1092 require Storable unless $Storable::VERSION;
1086 1093
1087 pack "w/a*", Storable::nfreeze ($ref) 1094 pack "w/a*", Storable::nfreeze ($ref)
1088}; 1095};
1089 1096
1090=back 1097=back
1127 1134
1128Whenever the given C<type> is used, C<push_write> will the function with 1135Whenever the given C<type> is used, C<push_write> will the function with
1129the handle object and the remaining arguments. 1136the handle object and the remaining arguments.
1130 1137
1131The function is supposed to return a single octet string that will be 1138The function is supposed to return a single octet string that will be
1132appended to the write buffer, so you cna mentally treat this function as a 1139appended to the write buffer, so you can mentally treat this function as a
1133"arguments to on-the-wire-format" converter. 1140"arguments to on-the-wire-format" converter.
1134 1141
1135Example: implement a custom write type C<join> that joins the remaining 1142Example: implement a custom write type C<join> that joins the remaining
1136arguments using the first one. 1143arguments using the first one.
1137 1144
1431data. 1438data.
1432 1439
1433Example: read 2 bytes. 1440Example: read 2 bytes.
1434 1441
1435 $handle->push_read (chunk => 2, sub { 1442 $handle->push_read (chunk => 2, sub {
1436 warn "yay ", unpack "H*", $_[1]; 1443 say "yay " . unpack "H*", $_[1];
1437 }); 1444 });
1438 1445
1439=cut 1446=cut
1440 1447
1441register_read_type chunk => sub { 1448register_read_type chunk => sub {
1475 if (@_ < 3) { 1482 if (@_ < 3) {
1476 # this is more than twice as fast as the generic code below 1483 # this is more than twice as fast as the generic code below
1477 sub { 1484 sub {
1478 $_[0]{rbuf} =~ s/^([^\015\012]*)(\015?\012)// or return; 1485 $_[0]{rbuf} =~ s/^([^\015\012]*)(\015?\012)// or return;
1479 1486
1480 $cb->($_[0], $1, $2); 1487 $cb->($_[0], "$1", "$2");
1481 1 1488 1
1482 } 1489 }
1483 } else { 1490 } else {
1484 $eol = quotemeta $eol unless ref $eol; 1491 $eol = quotemeta $eol unless ref $eol;
1485 $eol = qr|^(.*?)($eol)|s; 1492 $eol = qr|^(.*?)($eol)|s;
1486 1493
1487 sub { 1494 sub {
1488 $_[0]{rbuf} =~ s/$eol// or return; 1495 $_[0]{rbuf} =~ s/$eol// or return;
1489 1496
1490 $cb->($_[0], $1, $2); 1497 $cb->($_[0], "$1", "$2");
1491 1 1498 1
1492 } 1499 }
1493 } 1500 }
1494}; 1501};
1495 1502
1543 1550
1544 sub { 1551 sub {
1545 # accept 1552 # accept
1546 if ($$rbuf =~ $accept) { 1553 if ($$rbuf =~ $accept) {
1547 $data .= substr $$rbuf, 0, $+[0], ""; 1554 $data .= substr $$rbuf, 0, $+[0], "";
1548 $cb->($self, $data); 1555 $cb->($_[0], $data);
1549 return 1; 1556 return 1;
1550 } 1557 }
1551 1558
1552 # reject 1559 # reject
1553 if ($reject && $$rbuf =~ $reject) { 1560 if ($reject && $$rbuf =~ $reject) {
1554 $self->_error (Errno::EBADMSG); 1561 $_[0]->_error (Errno::EBADMSG);
1555 } 1562 }
1556 1563
1557 # skip 1564 # skip
1558 if ($skip && $$rbuf =~ $skip) { 1565 if ($skip && $$rbuf =~ $skip) {
1559 $data .= substr $$rbuf, 0, $+[0], ""; 1566 $data .= substr $$rbuf, 0, $+[0], "";
1575 my ($self, $cb) = @_; 1582 my ($self, $cb) = @_;
1576 1583
1577 sub { 1584 sub {
1578 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) { 1585 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
1579 if ($_[0]{rbuf} =~ /[^0-9]/) { 1586 if ($_[0]{rbuf} =~ /[^0-9]/) {
1580 $self->_error (Errno::EBADMSG); 1587 $_[0]->_error (Errno::EBADMSG);
1581 } 1588 }
1582 return; 1589 return;
1583 } 1590 }
1584 1591
1585 my $len = $1; 1592 my $len = $1;
1586 1593
1587 $self->unshift_read (chunk => $len, sub { 1594 $_[0]->unshift_read (chunk => $len, sub {
1588 my $string = $_[1]; 1595 my $string = $_[1];
1589 $_[0]->unshift_read (chunk => 1, sub { 1596 $_[0]->unshift_read (chunk => 1, sub {
1590 if ($_[1] eq ",") { 1597 if ($_[1] eq ",") {
1591 $cb->($_[0], $string); 1598 $cb->($_[0], $string);
1592 } else { 1599 } else {
1593 $self->_error (Errno::EBADMSG); 1600 $_[0]->_error (Errno::EBADMSG);
1594 } 1601 }
1595 }); 1602 });
1596 }); 1603 });
1597 1604
1598 1 1605 1
1671 1678
1672 my $data; 1679 my $data;
1673 my $rbuf = \$self->{rbuf}; 1680 my $rbuf = \$self->{rbuf};
1674 1681
1675 sub { 1682 sub {
1676 my $ref = eval { $json->incr_parse ($self->{rbuf}) }; 1683 my $ref = eval { $json->incr_parse ($_[0]{rbuf}) };
1677 1684
1678 if ($ref) { 1685 if ($ref) {
1679 $self->{rbuf} = $json->incr_text; 1686 $_[0]{rbuf} = $json->incr_text;
1680 $json->incr_text = ""; 1687 $json->incr_text = "";
1681 $cb->($self, $ref); 1688 $cb->($_[0], $ref);
1682 1689
1683 1 1690 1
1684 } elsif ($@) { 1691 } elsif ($@) {
1685 # error case 1692 # error case
1686 $json->incr_skip; 1693 $json->incr_skip;
1687 1694
1688 $self->{rbuf} = $json->incr_text; 1695 $_[0]{rbuf} = $json->incr_text;
1689 $json->incr_text = ""; 1696 $json->incr_text = "";
1690 1697
1691 $self->_error (Errno::EBADMSG); 1698 $_[0]->_error (Errno::EBADMSG);
1692 1699
1693 () 1700 ()
1694 } else { 1701 } else {
1695 $self->{rbuf} = ""; 1702 $_[0]{rbuf} = "";
1696 1703
1697 () 1704 ()
1698 } 1705 }
1699 } 1706 }
1700}; 1707};
1710=cut 1717=cut
1711 1718
1712register_read_type storable => sub { 1719register_read_type storable => sub {
1713 my ($self, $cb) = @_; 1720 my ($self, $cb) = @_;
1714 1721
1715 require Storable; 1722 require Storable unless $Storable::VERSION;
1716 1723
1717 sub { 1724 sub {
1718 # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method 1725 # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method
1719 defined (my $len = eval { unpack "w", $_[0]{rbuf} }) 1726 defined (my $len = eval { unpack "w", $_[0]{rbuf} })
1720 or return; 1727 or return;
1733 # read remaining chunk 1740 # read remaining chunk
1734 $_[0]->unshift_read (chunk => $len, sub { 1741 $_[0]->unshift_read (chunk => $len, sub {
1735 if (my $ref = eval { Storable::thaw ($_[1]) }) { 1742 if (my $ref = eval { Storable::thaw ($_[1]) }) {
1736 $cb->($_[0], $ref); 1743 $cb->($_[0], $ref);
1737 } else { 1744 } else {
1738 $self->_error (Errno::EBADMSG); 1745 $_[0]->_error (Errno::EBADMSG);
1739 } 1746 }
1740 }); 1747 });
1741 } 1748 }
1742 1749
1743 1 1750 1
1791some readings of the the SSL/TLS specifications basically require this 1798some readings of the the SSL/TLS specifications basically require this
1792attack to be working, as SSL/TLS implementations might stall sending data 1799attack to be working, as SSL/TLS implementations might stall sending data
1793during a rehandshake. 1800during a rehandshake.
1794 1801
1795As a guideline, during the initial handshake, you should not stop reading, 1802As a guideline, during the initial handshake, you should not stop reading,
1796and as a client, it might cause problems, depending on your applciation. 1803and as a client, it might cause problems, depending on your application.
1797 1804
1798=cut 1805=cut
1799 1806
1800sub stop_read { 1807sub stop_read {
1801 my ($self) = @_; 1808 my ($self) = @_;
2010 Net::SSLeay::CTX_set_mode ($tls, 1|2); 2017 Net::SSLeay::CTX_set_mode ($tls, 1|2);
2011 2018
2012 $self->{_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ()); 2019 $self->{_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
2013 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ()); 2020 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
2014 2021
2015 Net::SSLeay::BIO_write ($self->{_rbio}, delete $self->{rbuf}); 2022 Net::SSLeay::BIO_write ($self->{_rbio}, $self->{rbuf});
2023 $self->{rbuf} = "";
2016 2024
2017 Net::SSLeay::set_bio ($tls, $self->{_rbio}, $self->{_wbio}); 2025 Net::SSLeay::set_bio ($tls, $self->{_rbio}, $self->{_wbio});
2018 2026
2019 $self->{_on_starttls} = sub { $_[0]{on_starttls}(@_) } 2027 $self->{_on_starttls} = sub { $_[0]{on_starttls}(@_) }
2020 if $self->{on_starttls}; 2028 if $self->{on_starttls};
2202Probably because your C<on_error> callback is being called instead: When 2210Probably because your C<on_error> callback is being called instead: When
2203you have outstanding requests in your read queue, then an EOF is 2211you have outstanding requests in your read queue, then an EOF is
2204considered an error as you clearly expected some data. 2212considered an error as you clearly expected some data.
2205 2213
2206To avoid this, make sure you have an empty read queue whenever your handle 2214To avoid this, make sure you have an empty read queue whenever your handle
2207is supposed to be "idle" (i.e. connection closes are O.K.). You cna set 2215is supposed to be "idle" (i.e. connection closes are O.K.). You can set
2208an C<on_read> handler that simply pushes the first read requests in the 2216an C<on_read> handler that simply pushes the first read requests in the
2209queue. 2217queue.
2210 2218
2211See also the next question, which explains this in a bit more detail. 2219See also the next question, which explains this in a bit more detail.
2212 2220
2243some data and raises the C<EPIPE> error when the connction is dropped 2251some data and raises the C<EPIPE> error when the connction is dropped
2244unexpectedly. 2252unexpectedly.
2245 2253
2246The second variant is a protocol where the client can drop the connection 2254The second variant is a protocol where the client can drop the connection
2247at any time. For TCP, this means that the server machine may run out of 2255at any time. For TCP, this means that the server machine may run out of
2248sockets easier, and in general, it means you cnanot distinguish a protocl 2256sockets easier, and in general, it means you cannot distinguish a protocl
2249failure/client crash from a normal connection close. Nevertheless, these 2257failure/client crash from a normal connection close. Nevertheless, these
2250kinds of protocols are common (and sometimes even the best solution to the 2258kinds of protocols are common (and sometimes even the best solution to the
2251problem). 2259problem).
2252 2260
2253Having an outstanding read request at all times is possible if you ignore 2261Having an outstanding read request at all times is possible if you ignore
2305 $handle->on_eof (undef); 2313 $handle->on_eof (undef);
2306 $handle->on_error (sub { 2314 $handle->on_error (sub {
2307 my $data = delete $_[0]{rbuf}; 2315 my $data = delete $_[0]{rbuf};
2308 }); 2316 });
2309 2317
2318Note that this example removes the C<rbuf> member from the handle object,
2319which is not normally allowed by the API. It is expressly permitted in
2320this case only, as the handle object needs to be destroyed afterwards.
2321
2310The reason to use C<on_error> is that TCP connections, due to latencies 2322The reason to use C<on_error> is that TCP connections, due to latencies
2311and packets loss, might get closed quite violently with an error, when in 2323and packets loss, might get closed quite violently with an error, when in
2312fact all data has been received. 2324fact all data has been received.
2313 2325
2314It is usually better to use acknowledgements when transferring data, 2326It is usually better to use acknowledgements when transferring data,
2324C<low_water_mark> this will be called precisely when all data has been 2336C<low_water_mark> this will be called precisely when all data has been
2325written to the socket: 2337written to the socket:
2326 2338
2327 $handle->push_write (...); 2339 $handle->push_write (...);
2328 $handle->on_drain (sub { 2340 $handle->on_drain (sub {
2329 warn "all data submitted to the kernel\n"; 2341 AE::log debug => "All data submitted to the kernel.";
2330 undef $handle; 2342 undef $handle;
2331 }); 2343 });
2332 2344
2333If you just want to queue some data and then signal EOF to the other side, 2345If you just want to queue some data and then signal EOF to the other side,
2334consider using C<< ->push_shutdown >> instead. 2346consider using C<< ->push_shutdown >> instead.
2418When you have intermediate CA certificates that your clients might not 2430When you have intermediate CA certificates that your clients might not
2419know about, just append them to the C<cert_file>. 2431know about, just append them to the C<cert_file>.
2420 2432
2421=back 2433=back
2422 2434
2423
2424=head1 SUBCLASSING AnyEvent::Handle 2435=head1 SUBCLASSING AnyEvent::Handle
2425 2436
2426In many cases, you might want to subclass AnyEvent::Handle. 2437In many cases, you might want to subclass AnyEvent::Handle.
2427 2438
2428To make this easier, a given version of AnyEvent::Handle uses these 2439To make this easier, a given version of AnyEvent::Handle uses these
2454 2465
2455Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>. 2466Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
2456 2467
2457=cut 2468=cut
2458 2469
24591; # End of AnyEvent::Handle 24701
2471

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines