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.212 by root, Fri Dec 31 04:50:44 2010 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 streaming 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
34 30
35 $cv->recv; 31 $cv->recv;
36 32
37=head1 DESCRIPTION 33=head1 DESCRIPTION
38 34
39This module is a helper module to make it easier to do event-based I/O on 35This is a helper module to make it easier to do event-based I/O on
40filehandles. 36stream-based filehandles (sockets, pipes, and other stream things).
41 37
42The L<AnyEvent::Intro> tutorial contains some well-documented 38The L<AnyEvent::Intro> tutorial contains some well-documented
43AnyEvent::Handle examples. 39AnyEvent::Handle examples.
44 40
45In the following, when the documentation refers to of "bytes" then this 41In the following, where the documentation refers to "bytes", it means
46means characters. As sysread and syswrite are used for all I/O, their 42characters. As sysread and syswrite are used for all I/O, their
47treatment of characters applies to this module as well. 43treatment of characters applies to this module as well.
48 44
49At the very minimum, you should specify C<fh> or C<connect>, and the 45At the very minimum, you should specify C<fh> or C<connect>, and the
50C<on_error> callback. 46C<on_error> callback.
51 47
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
80sub MAX_READ_SIZE() { 131072 }
81
67=head1 METHODS 82=head1 METHODS
68 83
69=over 4 84=over 4
70 85
71=item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value... 86=item $handle = B<new> AnyEvent::Handle fh => $filehandle, key => value...
72 87
73The constructor supports these arguments (all as C<< key => value >> pairs). 88The constructor supports these arguments (all as C<< key => value >> pairs).
74 89
75=over 4 90=over 4
76 91
99=over 4 114=over 4
100 115
101=item on_prepare => $cb->($handle) 116=item on_prepare => $cb->($handle)
102 117
103This (rarely used) callback is called before a new connection is 118This (rarely used) callback is called before a new connection is
104attempted, but after the file handle has been created. It could be used to 119attempted, but after the file handle has been created (you can access that
120file handle via C<< $handle->{fh} >>). It could be used to prepare the
105prepare the file handle with parameters required for the actual connect 121file handle with parameters required for the actual connect (as opposed to
106(as opposed to settings that can be changed when the connection is already 122settings that can be changed when the connection is already established).
107established).
108 123
109The return value of this callback should be the connect timeout value in 124The return value of this callback should be the connect timeout value in
110seconds (or C<0>, or C<undef>, or the empty list, to indicate the default 125seconds (or C<0>, or C<undef>, or the empty list, to indicate that the
111timeout is to be used). 126default timeout is to be used).
112 127
113=item on_connect => $cb->($handle, $host, $port, $retry->()) 128=item on_connect => $cb->($handle, $host, $port, $retry->())
114 129
115This callback is called when a connection has been successfully established. 130This callback is called when a connection has been successfully established.
116 131
117The actual numeric host and port (the socket peername) are passed as 132The peer's numeric host and port (the socket peername) are passed as
118parameters, together with a retry callback. 133parameters, together with a retry callback.
119 134
120When, for some reason, the handle is not acceptable, then calling 135If, for some reason, the handle is not acceptable, calling C<$retry>
121C<$retry> will continue with the next conenction target (in case of 136will continue with the next connection target (in case of multi-homed
122multi-homed hosts or SRV records there can be multiple connection 137hosts or SRV records there can be multiple connection endpoints). At the
123endpoints). When it is called then the read and write queues, eof status, 138time it is called the read and write queues, eof status, tls status and
124tls status and similar properties of the handle are being reset. 139similar properties of the handle will have been reset.
125 140
126In most cases, ignoring the C<$retry> parameter is the way to go. 141In most cases, you should ignore the C<$retry> parameter.
127 142
128=item on_connect_error => $cb->($handle, $message) 143=item on_connect_error => $cb->($handle, $message)
129 144
130This callback is called when the conenction could not be 145This callback is called when the connection could not be
131established. C<$!> will contain the relevant error code, and C<$message> a 146established. C<$!> will contain the relevant error code, and C<$message> a
132message describing it (usually the same as C<"$!">). 147message describing it (usually the same as C<"$!">).
133 148
134If this callback isn't specified, then C<on_error> will be called with a 149If this callback isn't specified, then C<on_error> will be called with a
135fatal error instead. 150fatal error instead.
138 153
139=item on_error => $cb->($handle, $fatal, $message) 154=item on_error => $cb->($handle, $fatal, $message)
140 155
141This is the error callback, which is called when, well, some error 156This is the error callback, which is called when, well, some error
142occured, such as not being able to resolve the hostname, failure to 157occured, such as not being able to resolve the hostname, failure to
143connect or a read error. 158connect, or a read error.
144 159
145Some errors are fatal (which is indicated by C<$fatal> being true). On 160Some errors are fatal (which is indicated by C<$fatal> being true). On
146fatal errors the handle object will be destroyed (by a call to C<< -> 161fatal errors the handle object will be destroyed (by a call to C<< ->
147destroy >>) after invoking the error callback (which means you are free to 162destroy >>) after invoking the error callback (which means you are free to
148examine the handle object). Examples of fatal errors are an EOF condition 163examine the handle object). Examples of fatal errors are an EOF condition
149with active (but unsatisifable) read watchers (C<EPIPE>) or I/O errors. In 164with active (but unsatisfiable) read watchers (C<EPIPE>) or I/O errors. In
150cases where the other side can close the connection at their will it is 165cases where the other side can close the connection at will, it is
151often easiest to not report C<EPIPE> errors in this callback. 166often easiest to not report C<EPIPE> errors in this callback.
152 167
153AnyEvent::Handle tries to find an appropriate error code for you to check 168AnyEvent::Handle tries to find an appropriate error code for you to check
154against, but in some cases (TLS errors), this does not work well. It is 169against, but in some cases (TLS errors), this does not work well. It is
155recommended to always output the C<$message> argument in human-readable 170recommended to always output the C<$message> argument in human-readable
156error messages (it's usually the same as C<"$!">). 171error messages (it's usually the same as C<"$!">).
157 172
158Non-fatal errors can be retried by simply returning, but it is recommended 173Non-fatal errors can be retried by returning, but it is recommended
159to simply ignore this parameter and instead abondon the handle object 174to simply ignore this parameter and instead abondon the handle object
160when this callback is invoked. Examples of non-fatal errors are timeouts 175when this callback is invoked. Examples of non-fatal errors are timeouts
161C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>). 176C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>).
162 177
163On callback entrance, the value of C<$!> contains the operating system 178On entry to the callback, the value of C<$!> contains the operating
164error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or 179system error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or
165C<EPROTO>). 180C<EPROTO>).
166 181
167While not mandatory, it is I<highly> recommended to set this callback, as 182While not mandatory, it is I<highly> recommended to set this callback, as
168you will not be notified of errors otherwise. The default simply calls 183you will not be notified of errors otherwise. The default just calls
169C<croak>. 184C<croak>.
170 185
171=item on_read => $cb->($handle) 186=item on_read => $cb->($handle)
172 187
173This sets the default read callback, which is called when data arrives 188This sets the default read callback, which is called when data arrives
178To access (and remove data from) the read buffer, use the C<< ->rbuf >> 193To access (and remove data from) the read buffer, use the C<< ->rbuf >>
179method or access the C<< $handle->{rbuf} >> member directly. Note that you 194method or access the C<< $handle->{rbuf} >> member directly. Note that you
180must not enlarge or modify the read buffer, you can only remove data at 195must not enlarge or modify the read buffer, you can only remove data at
181the beginning from it. 196the beginning from it.
182 197
198You can also call C<< ->push_read (...) >> or any other function that
199modifies the read queue. Or do both. Or ...
200
183When an EOF condition is detected then AnyEvent::Handle will first try to 201When an EOF condition is detected, AnyEvent::Handle will first try to
184feed all the remaining data to the queued callbacks and C<on_read> before 202feed all the remaining data to the queued callbacks and C<on_read> before
185calling the C<on_eof> callback. If no progress can be made, then a fatal 203calling the C<on_eof> callback. If no progress can be made, then a fatal
186error will be raised (with C<$!> set to C<EPIPE>). 204error will be raised (with C<$!> set to C<EPIPE>).
187 205
188Note that, unlike requests in the read queue, an C<on_read> callback 206Note that, unlike requests in the read queue, an C<on_read> callback
207set, then a fatal error will be raised with C<$!> set to <0>. 225set, then a fatal error will be raised with C<$!> set to <0>.
208 226
209=item on_drain => $cb->($handle) 227=item on_drain => $cb->($handle)
210 228
211This sets the callback that is called when the write buffer becomes empty 229This sets the callback that is called when the write buffer becomes empty
212(or when the callback is set and the buffer is empty already). 230(or immediately if the buffer is empty already).
213 231
214To append to the write buffer, use the C<< ->push_write >> method. 232To append to the write buffer, use the C<< ->push_write >> method.
215 233
216This callback is useful when you don't want to put all of your write data 234This callback is useful when you don't want to put all of your write data
217into the queue at once, for example, when you want to write the contents 235into the queue at once, for example, when you want to write the contents
229many seconds pass without a successful read or write on the underlying 247many seconds pass without a successful read or write on the underlying
230file handle (or a call to C<timeout_reset>), the C<on_timeout> callback 248file handle (or a call to C<timeout_reset>), the C<on_timeout> callback
231will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT> 249will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT>
232error will be raised). 250error will be raised).
233 251
234There are three variants of the timeouts that work fully independent 252There are three variants of the timeouts that work independently
235of each other, for both read and write, just read, and just write: 253of each other, for both read and write, just read, and just write:
236C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks 254C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks
237C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions 255C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions
238C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>. 256C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>.
239 257
240Note that timeout processing is also active when you currently do not have 258Note that timeout processing is active even when you do not have
241any outstanding read or write requests: If you plan to keep the connection 259any outstanding read or write requests: If you plan to keep the connection
242idle then you should disable the timout temporarily or ignore the timeout 260idle then you should disable the timeout temporarily or ignore the timeout
243in the C<on_timeout> callback, in which case AnyEvent::Handle will simply 261in the C<on_timeout> callback, in which case AnyEvent::Handle will simply
244restart the timeout. 262restart the timeout.
245 263
246Zero (the default) disables this timeout. 264Zero (the default) disables this timeout.
247 265
261be configured to accept only so-and-so much data that it cannot act on 279be configured to accept only so-and-so much data that it cannot act on
262(for example, when expecting a line, an attacker could send an unlimited 280(for example, when expecting a line, an attacker could send an unlimited
263amount of data without a callback ever being called as long as the line 281amount of data without a callback ever being called as long as the line
264isn't finished). 282isn't finished).
265 283
284=item wbuf_max => <bytes>
285
286If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
287when the write buffer ever (strictly) exceeds this size. This is useful to
288avoid some forms of denial-of-service attacks.
289
290Although the units of this parameter is bytes, this is the I<raw> number
291of bytes not yet accepted by the kernel. This can make a difference when
292you e.g. use TLS, as TLS typically makes your write data larger (but it
293can also make it smaller due to compression).
294
295As an example of when this limit is useful, take a chat server that sends
296chat messages to a client. If the client does not read those in a timely
297manner then the send buffer in the server would grow unbounded.
298
266=item autocork => <boolean> 299=item autocork => <boolean>
267 300
268When disabled (the default), then C<push_write> will try to immediately 301When disabled (the default), C<push_write> will try to immediately
269write the data to the handle, if possible. This avoids having to register 302write the data to the handle if possible. This avoids having to register
270a write watcher and wait for the next event loop iteration, but can 303a write watcher and wait for the next event loop iteration, but can
271be inefficient if you write multiple small chunks (on the wire, this 304be inefficient if you write multiple small chunks (on the wire, this
272disadvantage is usually avoided by your kernel's nagle algorithm, see 305disadvantage is usually avoided by your kernel's nagle algorithm, see
273C<no_delay>, but this option can save costly syscalls). 306C<no_delay>, but this option can save costly syscalls).
274 307
275When enabled, then writes will always be queued till the next event loop 308When enabled, writes will always be queued till the next event loop
276iteration. This is efficient when you do many small writes per iteration, 309iteration. This is efficient when you do many small writes per iteration,
277but less efficient when you do a single write only per iteration (or when 310but less efficient when you do a single write only per iteration (or when
278the write buffer often is full). It also increases write latency. 311the write buffer often is full). It also increases write latency.
279 312
280=item no_delay => <boolean> 313=item no_delay => <boolean>
284the Nagle algorithm, and usually it is beneficial. 317the Nagle algorithm, and usually it is beneficial.
285 318
286In some situations you want as low a delay as possible, which can be 319In some situations you want as low a delay as possible, which can be
287accomplishd by setting this option to a true value. 320accomplishd by setting this option to a true value.
288 321
289The default is your opertaing system's default behaviour (most likely 322The default is your operating system's default behaviour (most likely
290enabled), this option explicitly enables or disables it, if possible. 323enabled). This option explicitly enables or disables it, if possible.
324
325=item keepalive => <boolean>
326
327Enables (default disable) the SO_KEEPALIVE option on the stream socket:
328normally, TCP connections have no time-out once established, so TCP
329connections, once established, can stay alive forever even when the other
330side has long gone. TCP keepalives are a cheap way to take down long-lived
331TCP connections when the other side becomes unreachable. While the default
332is OS-dependent, TCP keepalives usually kick in after around two hours,
333and, if the other side doesn't reply, take down the TCP connection some 10
334to 15 minutes later.
335
336It is harmless to specify this option for file handles that do not support
337keepalives, and enabling it on connections that are potentially long-lived
338is usually a good idea.
339
340=item oobinline => <boolean>
341
342BSD majorly fucked up the implementation of TCP urgent data. The result
343is that almost no OS implements TCP according to the specs, and every OS
344implements it slightly differently.
345
346If you want to handle TCP urgent data, then setting this flag (the default
347is enabled) gives you the most portable way of getting urgent data, by
348putting it into the stream.
349
350Since BSD emulation of OOB data on top of TCP's urgent data can have
351security implications, AnyEvent::Handle sets this flag automatically
352unless explicitly specified. Note that setting this flag after
353establishing a connection I<may> be a bit too late (data loss could
354already have occured on BSD systems), but at least it will protect you
355from most attacks.
291 356
292=item read_size => <bytes> 357=item read_size => <bytes>
293 358
294The default read block size (the amount of bytes this module will 359The initial read block size, the number of bytes this module will try to
295try to read during each loop iteration, which affects memory 360read during each loop iteration. Each handle object will consume at least
296requirements). Default: C<8192>. 361this amount of memory for the read buffer as well, so when handling many
362connections requirements). See also C<max_read_size>. Default: C<2048>.
363
364=item max_read_size => <bytes>
365
366The maximum read buffer size used by the dynamic adjustment
367algorithm: Each time AnyEvent::Handle can read C<read_size> bytes in
368one go it will double C<read_size> up to the maximum given by this
369option. Default: C<131072> or C<read_size>, whichever is higher.
297 370
298=item low_water_mark => <bytes> 371=item low_water_mark => <bytes>
299 372
300Sets the amount of bytes (default: C<0>) that make up an "empty" write 373Sets the number of bytes (default: C<0>) that make up an "empty" write
301buffer: If the write reaches this size or gets even samller it is 374buffer: If the buffer reaches this size or gets even samller it is
302considered empty. 375considered empty.
303 376
304Sometimes it can be beneficial (for performance reasons) to add data to 377Sometimes it can be beneficial (for performance reasons) to add data to
305the write buffer before it is fully drained, but this is a rare case, as 378the write buffer before it is fully drained, but this is a rare case, as
306the operating system kernel usually buffers data as well, so the default 379the operating system kernel usually buffers data as well, so the default
307is good in almost all cases. 380is good in almost all cases.
308 381
309=item linger => <seconds> 382=item linger => <seconds>
310 383
311If non-zero (default: C<3600>), then the destructor of the 384If this is non-zero (default: C<3600>), the destructor of the
312AnyEvent::Handle object will check whether there is still outstanding 385AnyEvent::Handle object will check whether there is still outstanding
313write data and will install a watcher that will write this data to the 386write data and will install a watcher that will write this data to the
314socket. No errors will be reported (this mostly matches how the operating 387socket. No errors will be reported (this mostly matches how the operating
315system treats outstanding data at socket close time). 388system treats outstanding data at socket close time).
316 389
323A string used to identify the remote site - usually the DNS hostname 396A string used to identify the remote site - usually the DNS hostname
324(I<not> IDN!) used to create the connection, rarely the IP address. 397(I<not> IDN!) used to create the connection, rarely the IP address.
325 398
326Apart from being useful in error messages, this string is also used in TLS 399Apart from being useful in error messages, this string is also used in TLS
327peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This 400peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This
328verification will be skipped when C<peername> is not specified or 401verification will be skipped when C<peername> is not specified or is
329C<undef>. 402C<undef>.
330 403
331=item tls => "accept" | "connect" | Net::SSLeay::SSL object 404=item tls => "accept" | "connect" | Net::SSLeay::SSL object
332 405
333When this parameter is given, it enables TLS (SSL) mode, that means 406When this parameter is given, it enables TLS (SSL) mode, that means
334AnyEvent will start a TLS handshake as soon as the conenction has been 407AnyEvent will start a TLS handshake as soon as the connection has been
335established and will transparently encrypt/decrypt data afterwards. 408established and will transparently encrypt/decrypt data afterwards.
336 409
337All TLS protocol errors will be signalled as C<EPROTO>, with an 410All TLS protocol errors will be signalled as C<EPROTO>, with an
338appropriate error message. 411appropriate error message.
339 412
359B<IMPORTANT:> since Net::SSLeay "objects" are really only integers, 432B<IMPORTANT:> since Net::SSLeay "objects" are really only integers,
360passing in the wrong integer will lead to certain crash. This most often 433passing in the wrong integer will lead to certain crash. This most often
361happens when one uses a stylish C<< tls => 1 >> and is surprised about the 434happens when one uses a stylish C<< tls => 1 >> and is surprised about the
362segmentation fault. 435segmentation fault.
363 436
364See the C<< ->starttls >> method for when need to start TLS negotiation later. 437Use the C<< ->starttls >> method if you need to start TLS negotiation later.
365 438
366=item tls_ctx => $anyevent_tls 439=item tls_ctx => $anyevent_tls
367 440
368Use the given C<AnyEvent::TLS> object to create the new TLS connection 441Use the given C<AnyEvent::TLS> object to create the new TLS connection
369(unless a connection object was specified directly). If this parameter is 442(unless a connection object was specified directly). If this
370missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>. 443parameter is missing (or C<undef>), then AnyEvent::Handle will use
444C<AnyEvent::Handle::TLS_CTX>.
371 445
372Instead of an object, you can also specify a hash reference with C<< key 446Instead of an object, you can also specify a hash reference with C<< key
373=> value >> pairs. Those will be passed to L<AnyEvent::TLS> to create a 447=> value >> pairs. Those will be passed to L<AnyEvent::TLS> to create a
374new TLS context object. 448new TLS context object.
375 449
384 458
385TLS handshake failures will not cause C<on_error> to be invoked when this 459TLS handshake failures will not cause C<on_error> to be invoked when this
386callback is in effect, instead, the error message will be passed to C<on_starttls>. 460callback is in effect, instead, the error message will be passed to C<on_starttls>.
387 461
388Without this callback, handshake failures lead to C<on_error> being 462Without this callback, handshake failures lead to C<on_error> being
389called, as normal. 463called as usual.
390 464
391Note that you cannot call C<starttls> right again in this callback. If you 465Note that you cannot just call C<starttls> again in this callback. If you
392need to do that, start an zero-second timer instead whose callback can 466need to do that, start an zero-second timer instead whose callback can
393then call C<< ->starttls >> again. 467then call C<< ->starttls >> again.
394 468
395=item on_stoptls => $cb->($handle) 469=item on_stoptls => $cb->($handle)
396 470
444 $self->{connect}[0], 518 $self->{connect}[0],
445 $self->{connect}[1], 519 $self->{connect}[1],
446 sub { 520 sub {
447 my ($fh, $host, $port, $retry) = @_; 521 my ($fh, $host, $port, $retry) = @_;
448 522
523 delete $self->{_connect}; # no longer needed
524
449 if ($fh) { 525 if ($fh) {
450 $self->{fh} = $fh; 526 $self->{fh} = $fh;
451 527
452 delete $self->{_skip_drain_rbuf}; 528 delete $self->{_skip_drain_rbuf};
453 $self->_start; 529 $self->_start;
454 530
455 $self->{on_connect} 531 $self->{on_connect}
456 and $self->{on_connect}($self, $host, $port, sub { 532 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)}; 533 delete @$self{qw(fh _tw _rtw _wtw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)};
458 $self->{_skip_drain_rbuf} = 1; 534 $self->{_skip_drain_rbuf} = 1;
459 &$retry; 535 &$retry;
460 }); 536 });
461 537
462 } else { 538 } else {
470 }, 546 },
471 sub { 547 sub {
472 local $self->{fh} = $_[0]; 548 local $self->{fh} = $_[0];
473 549
474 $self->{on_prepare} 550 $self->{on_prepare}
475 ? $self->{on_prepare}->($self) 551 ? $self->{on_prepare}->($self)
476 : () 552 : ()
477 } 553 }
478 ); 554 );
479 } 555 }
480 556
486} 562}
487 563
488sub _start { 564sub _start {
489 my ($self) = @_; 565 my ($self) = @_;
490 566
567 # too many clueless people try to use udp and similar sockets
568 # with AnyEvent::Handle, do them a favour.
569 my $type = getsockopt $self->{fh}, Socket::SOL_SOCKET (), Socket::SO_TYPE ();
570 Carp::croak "AnyEvent::Handle: only stream sockets supported, anything else will NOT work!"
571 if Socket::SOCK_STREAM () != (unpack "I", $type) && defined $type;
572
491 AnyEvent::Util::fh_nonblocking $self->{fh}, 1; 573 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
492 574
493 $self->{_activity} = 575 $self->{_activity} =
494 $self->{_ractivity} = 576 $self->{_ractivity} =
495 $self->{_wactivity} = AE::now; 577 $self->{_wactivity} = AE::now;
496 578
579 $self->{read_size} ||= 2048;
580 $self->{max_read_size} = $self->{read_size}
581 if $self->{read_size} > ($self->{max_read_size} || MAX_READ_SIZE);
582
497 $self->timeout (delete $self->{timeout} ) if $self->{timeout}; 583 $self->timeout (delete $self->{timeout} ) if $self->{timeout};
498 $self->rtimeout (delete $self->{rtimeout}) if $self->{rtimeout}; 584 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout};
499 $self->wtimeout (delete $self->{wtimeout}) if $self->{wtimeout}; 585 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout};
500 586
501 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay}; 587 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay} && $self->{no_delay};
588 $self->keepalive (delete $self->{keepalive}) if exists $self->{keepalive} && $self->{keepalive};
502 589
590 $self->oobinline (exists $self->{oobinline} ? delete $self->{oobinline} : 1);
591
503 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 592 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
504 if $self->{tls}; 593 if $self->{tls};
505 594
506 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 595 $self->on_drain (delete $self->{on_drain} ) if $self->{on_drain};
507 596
508 $self->start_read 597 $self->start_read
509 if $self->{on_read} || @{ $self->{_queue} }; 598 if $self->{on_read} || @{ $self->{_queue} };
510 599
511 $self->_drain_wbuf; 600 $self->_drain_wbuf;
512} 601}
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 602
523sub _error { 603sub _error {
524 my ($self, $errno, $fatal, $message) = @_; 604 my ($self, $errno, $fatal, $message) = @_;
525 605
526 $! = $errno; 606 $! = $errno;
527 $message ||= "$!"; 607 $message ||= "$!";
528 608
529 if ($self->{on_error}) { 609 if ($self->{on_error}) {
530 $self->{on_error}($self, $fatal, $message); 610 $self->{on_error}($self, $fatal, $message);
531 $self->destroy if $fatal; 611 $self->destroy if $fatal;
532 } elsif ($self->{fh}) { 612 } elsif ($self->{fh} || $self->{connect}) {
533 $self->destroy; 613 $self->destroy;
534 Carp::croak "AnyEvent::Handle uncaught error: $message"; 614 Carp::croak "AnyEvent::Handle uncaught error: $message";
535 } 615 }
536} 616}
537 617
596=cut 676=cut
597 677
598sub no_delay { 678sub no_delay {
599 $_[0]{no_delay} = $_[1]; 679 $_[0]{no_delay} = $_[1];
600 680
681 setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
682 if $_[0]{fh};
683}
684
685=item $handle->keepalive ($boolean)
686
687Enables or disables the C<keepalive> setting (see constructor argument of
688the same name for details).
689
690=cut
691
692sub keepalive {
693 $_[0]{keepalive} = $_[1];
694
601 eval { 695 eval {
602 local $SIG{__DIE__}; 696 local $SIG{__DIE__};
603 setsockopt $_[0]{fh}, &Socket::IPPROTO_TCP, &Socket::TCP_NODELAY, int $_[1] 697 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
604 if $_[0]{fh}; 698 if $_[0]{fh};
605 }; 699 };
606} 700}
607 701
702=item $handle->oobinline ($boolean)
703
704Enables or disables the C<oobinline> setting (see constructor argument of
705the same name for details).
706
707=cut
708
709sub oobinline {
710 $_[0]{oobinline} = $_[1];
711
712 eval {
713 local $SIG{__DIE__};
714 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_OOBINLINE (), int $_[1]
715 if $_[0]{fh};
716 };
717}
718
719=item $handle->keepalive ($boolean)
720
721Enables or disables the C<keepalive> setting (see constructor argument of
722the same name for details).
723
724=cut
725
726sub keepalive {
727 $_[0]{keepalive} = $_[1];
728
729 eval {
730 local $SIG{__DIE__};
731 setsockopt $_[0]{fh}, Socket::SOL_SOCKET (), Socket::SO_KEEPALIVE (), int $_[1]
732 if $_[0]{fh};
733 };
734}
735
608=item $handle->on_starttls ($cb) 736=item $handle->on_starttls ($cb)
609 737
610Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument). 738Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument).
611 739
612=cut 740=cut
619 747
620Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument). 748Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument).
621 749
622=cut 750=cut
623 751
624sub on_starttls { 752sub on_stoptls {
625 $_[0]{on_stoptls} = $_[1]; 753 $_[0]{on_stoptls} = $_[1];
626} 754}
627 755
628=item $handle->rbuf_max ($max_octets) 756=item $handle->rbuf_max ($max_octets)
629 757
630Configures the C<rbuf_max> setting (C<undef> disables it). 758Configures the C<rbuf_max> setting (C<undef> disables it).
759
760=item $handle->wbuf_max ($max_octets)
761
762Configures the C<wbuf_max> setting (C<undef> disables it).
631 763
632=cut 764=cut
633 765
634sub rbuf_max { 766sub rbuf_max {
635 $_[0]{rbuf_max} = $_[1]; 767 $_[0]{rbuf_max} = $_[1];
768}
769
770sub rbuf_max {
771 $_[0]{wbuf_max} = $_[1];
636} 772}
637 773
638############################################################################# 774#############################################################################
639 775
640=item $handle->timeout ($seconds) 776=item $handle->timeout ($seconds)
668 $_[0]{$on_timeout} = $_[1]; 804 $_[0]{$on_timeout} = $_[1];
669 }; 805 };
670 806
671 *$timeout = sub { 807 *$timeout = sub {
672 my ($self, $new_value) = @_; 808 my ($self, $new_value) = @_;
809
810 $new_value >= 0
811 or Carp::croak "AnyEvent::Handle->$timeout called with negative timeout ($new_value), caught";
673 812
674 $self->{$timeout} = $new_value; 813 $self->{$timeout} = $new_value;
675 delete $self->{$tw}; &$cb; 814 delete $self->{$tw}; &$cb;
676 }; 815 };
677 816
741=item $handle->on_drain ($cb) 880=item $handle->on_drain ($cb)
742 881
743Sets the C<on_drain> callback or clears it (see the description of 882Sets the C<on_drain> callback or clears it (see the description of
744C<on_drain> in the constructor). 883C<on_drain> in the constructor).
745 884
885This method may invoke callbacks (and therefore the handle might be
886destroyed after it returns).
887
746=cut 888=cut
747 889
748sub on_drain { 890sub on_drain {
749 my ($self, $cb) = @_; 891 my ($self, $cb) = @_;
750 892
754 if $cb && $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf}); 896 if $cb && $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf});
755} 897}
756 898
757=item $handle->push_write ($data) 899=item $handle->push_write ($data)
758 900
759Queues the given scalar to be written. You can push as much data as you 901Queues the given scalar to be written. You can push as much data as
760want (only limited by the available memory), as C<AnyEvent::Handle> 902you want (only limited by the available memory and C<wbuf_max>), as
761buffers it independently of the kernel. 903C<AnyEvent::Handle> buffers it independently of the kernel.
904
905This method may invoke callbacks (and therefore the handle might be
906destroyed after it returns).
762 907
763=cut 908=cut
764 909
765sub _drain_wbuf { 910sub _drain_wbuf {
766 my ($self) = @_; 911 my ($self) = @_;
791 $cb->() unless $self->{autocork}; 936 $cb->() unless $self->{autocork};
792 937
793 # if still data left in wbuf, we need to poll 938 # if still data left in wbuf, we need to poll
794 $self->{_ww} = AE::io $self->{fh}, 1, $cb 939 $self->{_ww} = AE::io $self->{fh}, 1, $cb
795 if length $self->{wbuf}; 940 if length $self->{wbuf};
941
942 if (
943 defined $self->{wbuf_max}
944 && $self->{wbuf_max} < length $self->{wbuf}
945 ) {
946 $self->_error (Errno::ENOSPC, 1), return;
947 }
796 }; 948 };
797} 949}
798 950
799our %WH; 951our %WH;
800 952
953# deprecated
801sub register_write_type($$) { 954sub register_write_type($$) {
802 $WH{$_[0]} = $_[1]; 955 $WH{$_[0]} = $_[1];
803} 956}
804 957
805sub push_write { 958sub push_write {
806 my $self = shift; 959 my $self = shift;
807 960
808 if (@_ > 1) { 961 if (@_ > 1) {
809 my $type = shift; 962 my $type = shift;
810 963
964 @_ = ($WH{$type} ||= _load_func "$type\::anyevent_write_type"
811 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write") 965 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_write")
812 ->($self, @_); 966 ->($self, @_);
813 } 967 }
814 968
969 # we downgrade here to avoid hard-to-track-down bugs,
970 # and diagnose the problem earlier and better.
971
815 if ($self->{tls}) { 972 if ($self->{tls}) {
816 $self->{_tls_wbuf} .= $_[0]; 973 utf8::downgrade $self->{_tls_wbuf} .= $_[0];
817 &_dotls ($self) if $self->{fh}; 974 &_dotls ($self) if $self->{fh};
818 } else { 975 } else {
819 $self->{wbuf} .= $_[0]; 976 utf8::downgrade $self->{wbuf} .= $_[0];
820 $self->_drain_wbuf if $self->{fh}; 977 $self->_drain_wbuf if $self->{fh};
821 } 978 }
822} 979}
823 980
824=item $handle->push_write (type => @args) 981=item $handle->push_write (type => @args)
825 982
826Instead of formatting your data yourself, you can also let this module do 983Instead of formatting your data yourself, you can also let this module
827the job by specifying a type and type-specific arguments. 984do the job by specifying a type and type-specific arguments. You
985can also specify the (fully qualified) name of a package, in which
986case AnyEvent tries to load the package and then expects to find the
987C<anyevent_write_type> function inside (see "custom write types", below).
828 988
829Predefined types are (if you have ideas for additional types, feel free to 989Predefined types are (if you have ideas for additional types, feel free to
830drop by and tell us): 990drop by and tell us):
831 991
832=over 4 992=over 4
889Other languages could read single lines terminated by a newline and pass 1049Other languages could read single lines terminated by a newline and pass
890this line into their JSON decoder of choice. 1050this line into their JSON decoder of choice.
891 1051
892=cut 1052=cut
893 1053
1054sub json_coder() {
1055 eval { require JSON::XS; JSON::XS->new->utf8 }
1056 || do { require JSON; JSON->new->utf8 }
1057}
1058
894register_write_type json => sub { 1059register_write_type json => sub {
895 my ($self, $ref) = @_; 1060 my ($self, $ref) = @_;
896 1061
897 require JSON; 1062 my $json = $self->{json} ||= json_coder;
898 1063
899 $self->{json} ? $self->{json}->encode ($ref) 1064 $json->encode ($ref)
900 : JSON::encode_json ($ref)
901}; 1065};
902 1066
903=item storable => $reference 1067=item storable => $reference
904 1068
905Freezes the given reference using L<Storable> and writes it to the 1069Freezes the given reference using L<Storable> and writes it to the
931the peer. 1095the peer.
932 1096
933You can rely on the normal read queue and C<on_eof> handling 1097You can rely on the normal read queue and C<on_eof> handling
934afterwards. This is the cleanest way to close a connection. 1098afterwards. This is the cleanest way to close a connection.
935 1099
1100This method may invoke callbacks (and therefore the handle might be
1101destroyed after it returns).
1102
936=cut 1103=cut
937 1104
938sub push_shutdown { 1105sub push_shutdown {
939 my ($self) = @_; 1106 my ($self) = @_;
940 1107
941 delete $self->{low_water_mark}; 1108 delete $self->{low_water_mark};
942 $self->on_drain (sub { shutdown $_[0]{fh}, 1 }); 1109 $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
943} 1110}
944 1111
945=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 1112=item custom write types - Package::anyevent_write_type $handle, @args
946 1113
947This function (not method) lets you add your own types to C<push_write>. 1114Instead of one of the predefined types, you can also specify the name of
1115a package. AnyEvent will try to load the package and then expects to find
1116a function named C<anyevent_write_type> inside. If it isn't found, it
1117progressively tries to load the parent package until it either finds the
1118function (good) or runs out of packages (bad).
1119
948Whenever the given C<type> is used, C<push_write> will invoke the code 1120Whenever the given C<type> is used, C<push_write> will the function with
949reference with the handle object and the remaining arguments. 1121the handle object and the remaining arguments.
950 1122
951The code reference is supposed to return a single octet string that will 1123The function is supposed to return a single octet string that will be
952be appended to the write buffer. 1124appended to the write buffer, so you cna mentally treat this function as a
1125"arguments to on-the-wire-format" converter.
953 1126
954Note that this is a function, and all types registered this way will be 1127Example: implement a custom write type C<join> that joins the remaining
955global, so try to use unique names. 1128arguments using the first one.
1129
1130 $handle->push_write (My::Type => " ", 1,2,3);
1131
1132 # uses the following package, which can be defined in the "My::Type" or in
1133 # the "My" modules to be auto-loaded, or just about anywhere when the
1134 # My::Type::anyevent_write_type is defined before invoking it.
1135
1136 package My::Type;
1137
1138 sub anyevent_write_type {
1139 my ($handle, $delim, @args) = @_;
1140
1141 join $delim, @args
1142 }
956 1143
957=cut 1144=cut
958 1145
959############################################################################# 1146#############################################################################
960 1147
969ways, the "simple" way, using only C<on_read> and the "complex" way, using 1156ways, the "simple" way, using only C<on_read> and the "complex" way, using
970a queue. 1157a queue.
971 1158
972In the simple case, you just install an C<on_read> callback and whenever 1159In the simple case, you just install an C<on_read> callback and whenever
973new data arrives, it will be called. You can then remove some data (if 1160new data arrives, it will be called. You can then remove some data (if
974enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna 1161enough is there) from the read buffer (C<< $handle->rbuf >>). Or you can
975leave the data there if you want to accumulate more (e.g. when only a 1162leave the data there if you want to accumulate more (e.g. when only a
976partial message has been received so far). 1163partial message has been received so far), or change the read queue with
1164e.g. C<push_read>.
977 1165
978In the more complex case, you want to queue multiple callbacks. In this 1166In the more complex case, you want to queue multiple callbacks. In this
979case, AnyEvent::Handle will call the first queued callback each time new 1167case, AnyEvent::Handle will call the first queued callback each time new
980data arrives (also the first time it is queued) and removes it when it has 1168data arrives (also the first time it is queued) and remove it when it has
981done its job (see C<push_read>, below). 1169done its job (see C<push_read>, below).
982 1170
983This way you can, for example, push three line-reads, followed by reading 1171This way you can, for example, push three line-reads, followed by reading
984a chunk of data, and AnyEvent::Handle will execute them in order. 1172a chunk of data, and AnyEvent::Handle will execute them in order.
985 1173
1116 1304
1117This replaces the currently set C<on_read> callback, or clears it (when 1305This replaces the currently set C<on_read> callback, or clears it (when
1118the new callback is C<undef>). See the description of C<on_read> in the 1306the new callback is C<undef>). See the description of C<on_read> in the
1119constructor. 1307constructor.
1120 1308
1309This method may invoke callbacks (and therefore the handle might be
1310destroyed after it returns).
1311
1121=cut 1312=cut
1122 1313
1123sub on_read { 1314sub on_read {
1124 my ($self, $cb) = @_; 1315 my ($self, $cb) = @_;
1125 1316
1127 $self->_drain_rbuf if $cb; 1318 $self->_drain_rbuf if $cb;
1128} 1319}
1129 1320
1130=item $handle->rbuf 1321=item $handle->rbuf
1131 1322
1132Returns the read buffer (as a modifiable lvalue). 1323Returns the read buffer (as a modifiable lvalue). You can also access the
1324read buffer directly as the C<< ->{rbuf} >> member, if you want (this is
1325much faster, and no less clean).
1133 1326
1134You can access the read buffer directly as the C<< ->{rbuf} >> 1327The only operation allowed on the read buffer (apart from looking at it)
1135member, if you want. However, the only operation allowed on the 1328is removing data from its beginning. Otherwise modifying or appending to
1136read buffer (apart from looking at it) is removing data from its 1329it is not allowed and will lead to hard-to-track-down bugs.
1137beginning. Otherwise modifying or appending to it is not allowed and will
1138lead to hard-to-track-down bugs.
1139 1330
1140NOTE: The read buffer should only be used or modified if the C<on_read>, 1331NOTE: The read buffer should only be used or modified in the C<on_read>
1141C<push_read> or C<unshift_read> methods are used. The other read methods 1332callback or when C<push_read> or C<unshift_read> are used with a single
1142automatically manage the read buffer. 1333callback (i.e. untyped). Typed C<push_read> and C<unshift_read> methods
1334will manage the read buffer on their own.
1143 1335
1144=cut 1336=cut
1145 1337
1146sub rbuf : lvalue { 1338sub rbuf : lvalue {
1147 $_[0]{rbuf} 1339 $_[0]{rbuf}
1164 1356
1165If enough data was available, then the callback must remove all data it is 1357If enough data was available, then the callback must remove all data it is
1166interested in (which can be none at all) and return a true value. After returning 1358interested in (which can be none at all) and return a true value. After returning
1167true, it will be removed from the queue. 1359true, it will be removed from the queue.
1168 1360
1361These methods may invoke callbacks (and therefore the handle might be
1362destroyed after it returns).
1363
1169=cut 1364=cut
1170 1365
1171our %RH; 1366our %RH;
1172 1367
1173sub register_read_type($$) { 1368sub register_read_type($$) {
1179 my $cb = pop; 1374 my $cb = pop;
1180 1375
1181 if (@_) { 1376 if (@_) {
1182 my $type = shift; 1377 my $type = shift;
1183 1378
1379 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1184 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 1380 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_read")
1185 ->($self, $cb, @_); 1381 ->($self, $cb, @_);
1186 } 1382 }
1187 1383
1188 push @{ $self->{_queue} }, $cb; 1384 push @{ $self->{_queue} }, $cb;
1189 $self->_drain_rbuf; 1385 $self->_drain_rbuf;
1194 my $cb = pop; 1390 my $cb = pop;
1195 1391
1196 if (@_) { 1392 if (@_) {
1197 my $type = shift; 1393 my $type = shift;
1198 1394
1395 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1199 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read") 1396 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::unshift_read")
1200 ->($self, $cb, @_); 1397 ->($self, $cb, @_);
1201 } 1398 }
1202
1203 1399
1204 unshift @{ $self->{_queue} }, $cb; 1400 unshift @{ $self->{_queue} }, $cb;
1205 $self->_drain_rbuf; 1401 $self->_drain_rbuf;
1206} 1402}
1207 1403
1209 1405
1210=item $handle->unshift_read (type => @args, $cb) 1406=item $handle->unshift_read (type => @args, $cb)
1211 1407
1212Instead of providing a callback that parses the data itself you can chose 1408Instead of providing a callback that parses the data itself you can chose
1213between a number of predefined parsing formats, for chunks of data, lines 1409between a number of predefined parsing formats, for chunks of data, lines
1214etc. 1410etc. You can also specify the (fully qualified) name of a package, in
1411which case AnyEvent tries to load the package and then expects to find the
1412C<anyevent_read_type> function inside (see "custom read types", below).
1215 1413
1216Predefined types are (if you have ideas for additional types, feel free to 1414Predefined types are (if you have ideas for additional types, feel free to
1217drop by and tell us): 1415drop by and tell us):
1218 1416
1219=over 4 1417=over 4
1311the receive buffer when neither C<$accept> nor C<$reject> match, 1509the receive buffer when neither C<$accept> nor C<$reject> match,
1312and everything preceding and including the match will be accepted 1510and everything preceding and including the match will be accepted
1313unconditionally. This is useful to skip large amounts of data that you 1511unconditionally. This is useful to skip large amounts of data that you
1314know cannot be matched, so that the C<$accept> or C<$reject> regex do not 1512know cannot be matched, so that the C<$accept> or C<$reject> regex do not
1315have to start matching from the beginning. This is purely an optimisation 1513have to start matching from the beginning. This is purely an optimisation
1316and is usually worth only when you expect more than a few kilobytes. 1514and is usually worth it only when you expect more than a few kilobytes.
1317 1515
1318Example: expect a http header, which ends at C<\015\012\015\012>. Since we 1516Example: expect a http header, which ends at C<\015\012\015\012>. Since we
1319expect the header to be very large (it isn't in practise, but...), we use 1517expect the header to be very large (it isn't in practice, but...), we use
1320a skip regex to skip initial portions. The skip regex is tricky in that 1518a skip regex to skip initial portions. The skip regex is tricky in that
1321it only accepts something not ending in either \015 or \012, as these are 1519it only accepts something not ending in either \015 or \012, as these are
1322required for the accept regex. 1520required for the accept regex.
1323 1521
1324 $handle->push_read (regex => 1522 $handle->push_read (regex =>
1459=cut 1657=cut
1460 1658
1461register_read_type json => sub { 1659register_read_type json => sub {
1462 my ($self, $cb) = @_; 1660 my ($self, $cb) = @_;
1463 1661
1464 my $json = $self->{json} ||= 1662 my $json = $self->{json} ||= json_coder;
1465 eval { require JSON::XS; JSON::XS->new->utf8 }
1466 || do { require JSON; JSON->new->utf8 };
1467 1663
1468 my $data; 1664 my $data;
1469 my $rbuf = \$self->{rbuf}; 1665 my $rbuf = \$self->{rbuf};
1470 1666
1471 sub { 1667 sub {
1540 } 1736 }
1541}; 1737};
1542 1738
1543=back 1739=back
1544 1740
1545=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1741=item custom read types - Package::anyevent_read_type $handle, $cb, @args
1546 1742
1547This function (not method) lets you add your own types to C<push_read>. 1743Instead of one of the predefined types, you can also specify the name
1744of a package. AnyEvent will try to load the package and then expects to
1745find a function named C<anyevent_read_type> inside. If it isn't found, it
1746progressively tries to load the parent package until it either finds the
1747function (good) or runs out of packages (bad).
1548 1748
1549Whenever the given C<type> is used, C<push_read> will invoke the code 1749Whenever this type is used, C<push_read> will invoke the function with the
1550reference with the handle object, the callback and the remaining 1750handle object, the original callback and the remaining arguments.
1551arguments.
1552 1751
1553The code reference is supposed to return a callback (usually a closure) 1752The function is supposed to return a callback (usually a closure) that
1554that works as a plain read callback (see C<< ->push_read ($cb) >>). 1753works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
1754mentally treat the function as a "configurable read type to read callback"
1755converter.
1555 1756
1556It should invoke the passed callback when it is done reading (remember to 1757It should invoke the original callback when it is done reading (remember
1557pass C<$handle> as first argument as all other callbacks do that). 1758to pass C<$handle> as first argument as all other callbacks do that,
1759although there is no strict requirement on this).
1558 1760
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>, 1761For examples, see the source of this module (F<perldoc -m
1563search for C<register_read_type>)). 1762AnyEvent::Handle>, search for C<register_read_type>)).
1564 1763
1565=item $handle->stop_read 1764=item $handle->stop_read
1566 1765
1567=item $handle->start_read 1766=item $handle->start_read
1568 1767
1588} 1787}
1589 1788
1590sub start_read { 1789sub start_read {
1591 my ($self) = @_; 1790 my ($self) = @_;
1592 1791
1593 unless ($self->{_rw} || $self->{_eof}) { 1792 unless ($self->{_rw} || $self->{_eof} || !$self->{fh}) {
1594 Scalar::Util::weaken $self; 1793 Scalar::Util::weaken $self;
1595 1794
1596 $self->{_rw} = AE::io $self->{fh}, 0, sub { 1795 $self->{_rw} = AE::io $self->{fh}, 0, sub {
1597 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf}); 1796 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1598 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1797 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size}, length $$rbuf;
1599 1798
1600 if ($len > 0) { 1799 if ($len > 0) {
1601 $self->{_activity} = $self->{_ractivity} = AE::now; 1800 $self->{_activity} = $self->{_ractivity} = AE::now;
1602 1801
1603 if ($self->{tls}) { 1802 if ($self->{tls}) {
1604 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf); 1803 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf);
1605 1804
1606 &_dotls ($self); 1805 &_dotls ($self);
1607 } else { 1806 } else {
1608 $self->_drain_rbuf; 1807 $self->_drain_rbuf;
1808 }
1809
1810 if ($len == $self->{read_size}) {
1811 $self->{read_size} *= 2;
1812 $self->{read_size} = $self->{max_read_size} || MAX_READ_SIZE
1813 if $self->{read_size} > ($self->{max_read_size} || MAX_READ_SIZE);
1609 } 1814 }
1610 1815
1611 } elsif (defined $len) { 1816 } elsif (defined $len) {
1612 delete $self->{_rw}; 1817 delete $self->{_rw};
1613 $self->{_eof} = 1; 1818 $self->{_eof} = 1;
1691 && ($tmp != $ERROR_SYSCALL || $!); 1896 && ($tmp != $ERROR_SYSCALL || $!);
1692 1897
1693 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) { 1898 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1694 $self->{wbuf} .= $tmp; 1899 $self->{wbuf} .= $tmp;
1695 $self->_drain_wbuf; 1900 $self->_drain_wbuf;
1901 $self->{tls} or return; # tls session might have gone away in callback
1696 } 1902 }
1697 1903
1698 $self->{_on_starttls} 1904 $self->{_on_starttls}
1699 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK () 1905 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
1700 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established"); 1906 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
1722context in C<< $handle->{tls_ctx} >> after this call and can be used or 1928context in C<< $handle->{tls_ctx} >> after this call and can be used or
1723changed to your liking. Note that the handshake might have already started 1929changed to your liking. Note that the handshake might have already started
1724when this function returns. 1930when this function returns.
1725 1931
1726Due to bugs in OpenSSL, it might or might not be possible to do multiple 1932Due to bugs in OpenSSL, it might or might not be possible to do multiple
1727handshakes on the same stream. Best do not attempt to use the stream after 1933handshakes on the same stream. It is best to not attempt to use the
1728stopping TLS. 1934stream after stopping TLS.
1935
1936This method may invoke callbacks (and therefore the handle might be
1937destroyed after it returns).
1729 1938
1730=cut 1939=cut
1731 1940
1732our %TLS_CACHE; #TODO not yet documented, should we? 1941our %TLS_CACHE; #TODO not yet documented, should we?
1733 1942
1745 require Net::SSLeay; 1954 require Net::SSLeay;
1746 1955
1747 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL (); 1956 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL ();
1748 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ (); 1957 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ ();
1749 1958
1750 $tls = $self->{tls}; 1959 $tls = delete $self->{tls};
1751 $ctx = $self->{tls_ctx}; 1960 $ctx = $self->{tls_ctx};
1752 1961
1753 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session 1962 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session
1754 1963
1755 if ("HASH" eq ref $ctx) { 1964 if ("HASH" eq ref $ctx) {
1799 2008
1800=item $handle->stoptls 2009=item $handle->stoptls
1801 2010
1802Shuts down the SSL connection - this makes a proper EOF handshake by 2011Shuts down the SSL connection - this makes a proper EOF handshake by
1803sending a close notify to the other side, but since OpenSSL doesn't 2012sending a close notify to the other side, but since OpenSSL doesn't
1804support non-blocking shut downs, it is not guarenteed that you can re-use 2013support non-blocking shut downs, it is not guaranteed that you can re-use
1805the stream afterwards. 2014the stream afterwards.
2015
2016This method may invoke callbacks (and therefore the handle might be
2017destroyed after it returns).
1806 2018
1807=cut 2019=cut
1808 2020
1809sub stoptls { 2021sub stoptls {
1810 my ($self) = @_; 2022 my ($self) = @_;
1811 2023
1812 if ($self->{tls}) { 2024 if ($self->{tls} && $self->{fh}) {
1813 Net::SSLeay::shutdown ($self->{tls}); 2025 Net::SSLeay::shutdown ($self->{tls});
1814 2026
1815 &_dotls; 2027 &_dotls;
1816 2028
1817# # we don't give a shit. no, we do, but we can't. no...#d# 2029# # we don't give a shit. no, we do, but we can't. no...#d#
1847 push @linger, AE::io $fh, 1, sub { 2059 push @linger, AE::io $fh, 1, sub {
1848 my $len = syswrite $fh, $wbuf, length $wbuf; 2060 my $len = syswrite $fh, $wbuf, length $wbuf;
1849 2061
1850 if ($len > 0) { 2062 if ($len > 0) {
1851 substr $wbuf, 0, $len, ""; 2063 substr $wbuf, 0, $len, "";
1852 } else { 2064 } elsif (defined $len || ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK)) {
1853 @linger = (); # end 2065 @linger = (); # end
1854 } 2066 }
1855 }; 2067 };
1856 push @linger, AE::timer $linger, 0, sub { 2068 push @linger, AE::timer $linger, 0, sub {
1857 @linger = (); 2069 @linger = ();
1894 2106
1895sub AnyEvent::Handle::destroyed::AUTOLOAD { 2107sub AnyEvent::Handle::destroyed::AUTOLOAD {
1896 #nop 2108 #nop
1897} 2109}
1898 2110
2111=item $handle->destroyed
2112
2113Returns false as long as the handle hasn't been destroyed by a call to C<<
2114->destroy >>, true otherwise.
2115
2116Can be useful to decide whether the handle is still valid after some
2117callback possibly destroyed the handle. For example, C<< ->push_write >>,
2118C<< ->starttls >> and other methods can call user callbacks, which in turn
2119can destroy the handle, so work can be avoided by checking sometimes:
2120
2121 $hdl->starttls ("accept");
2122 return if $hdl->destroyed;
2123 $hdl->push_write (...
2124
2125Note that the call to C<push_write> will silently be ignored if the handle
2126has been destroyed, so often you can just ignore the possibility of the
2127handle being destroyed.
2128
2129=cut
2130
2131sub destroyed { 0 }
2132sub AnyEvent::Handle::destroyed::destroyed { 1 }
2133
1899=item AnyEvent::Handle::TLS_CTX 2134=item AnyEvent::Handle::TLS_CTX
1900 2135
1901This function creates and returns the AnyEvent::TLS object used by default 2136This function creates and returns the AnyEvent::TLS object used by default
1902for TLS mode. 2137for TLS mode.
1903 2138
1930 2165
1931It is only safe to "forget" the reference inside EOF or error callbacks, 2166It is only safe to "forget" the reference inside EOF or error callbacks,
1932from within all other callbacks, you need to explicitly call the C<< 2167from within all other callbacks, you need to explicitly call the C<<
1933->destroy >> method. 2168->destroy >> method.
1934 2169
2170=item Why is my C<on_eof> callback never called?
2171
2172Probably because your C<on_error> callback is being called instead: When
2173you have outstanding requests in your read queue, then an EOF is
2174considered an error as you clearly expected some data.
2175
2176To avoid this, make sure you have an empty read queue whenever your handle
2177is supposed to be "idle" (i.e. connection closes are O.K.). You cna set
2178an C<on_read> handler that simply pushes the first read requests in the
2179queue.
2180
2181See also the next question, which explains this in a bit more detail.
2182
2183=item How can I serve requests in a loop?
2184
2185Most protocols consist of some setup phase (authentication for example)
2186followed by a request handling phase, where the server waits for requests
2187and handles them, in a loop.
2188
2189There are two important variants: The first (traditional, better) variant
2190handles requests until the server gets some QUIT command, causing it to
2191close the connection first (highly desirable for a busy TCP server). A
2192client dropping the connection is an error, which means this variant can
2193detect an unexpected detection close.
2194
2195To handle this case, always make sure you have a on-empty read queue, by
2196pushing the "read request start" handler on it:
2197
2198 # we assume a request starts with a single line
2199 my @start_request; @start_request = (line => sub {
2200 my ($hdl, $line) = @_;
2201
2202 ... handle request
2203
2204 # push next request read, possibly from a nested callback
2205 $hdl->push_read (@start_request);
2206 });
2207
2208 # auth done, now go into request handling loop
2209 # now push the first @start_request
2210 $hdl->push_read (@start_request);
2211
2212By always having an outstanding C<push_read>, the handle always expects
2213some data and raises the C<EPIPE> error when the connction is dropped
2214unexpectedly.
2215
2216The second variant is a protocol where the client can drop the connection
2217at any time. For TCP, this means that the server machine may run out of
2218sockets easier, and in general, it means you cnanot distinguish a protocl
2219failure/client crash from a normal connection close. Nevertheless, these
2220kinds of protocols are common (and sometimes even the best solution to the
2221problem).
2222
2223Having an outstanding read request at all times is possible if you ignore
2224C<EPIPE> errors, but this doesn't help with when the client drops the
2225connection during a request, which would still be an error.
2226
2227A better solution is to push the initial request read in an C<on_read>
2228callback. This avoids an error, as when the server doesn't expect data
2229(i.e. is idly waiting for the next request, an EOF will not raise an
2230error, but simply result in an C<on_eof> callback. It is also a bit slower
2231and simpler:
2232
2233 # auth done, now go into request handling loop
2234 $hdl->on_read (sub {
2235 my ($hdl) = @_;
2236
2237 # called each time we receive data but the read queue is empty
2238 # simply start read the request
2239
2240 $hdl->push_read (line => sub {
2241 my ($hdl, $line) = @_;
2242
2243 ... handle request
2244
2245 # do nothing special when the request has been handled, just
2246 # let the request queue go empty.
2247 });
2248 });
2249
1935=item I get different callback invocations in TLS mode/Why can't I pause 2250=item I get different callback invocations in TLS mode/Why can't I pause
1936reading? 2251reading?
1937 2252
1938Unlike, say, TCP, TLS connections do not consist of two independent 2253Unlike, say, TCP, TLS connections do not consist of two independent
1939communication channels, one for each direction. Or put differently. The 2254communication channels, one for each direction. Or put differently, the
1940read and write directions are not independent of each other: you cannot 2255read and write directions are not independent of each other: you cannot
1941write data unless you are also prepared to read, and vice versa. 2256write data unless you are also prepared to read, and vice versa.
1942 2257
1943This can mean than, in TLS mode, you might get C<on_error> or C<on_eof> 2258This means that, in TLS mode, you might get C<on_error> or C<on_eof>
1944callback invocations when you are not expecting any read data - the reason 2259callback invocations when you are not expecting any read data - the reason
1945is that AnyEvent::Handle always reads in TLS mode. 2260is that AnyEvent::Handle always reads in TLS mode.
1946 2261
1947During the connection, you have to make sure that you always have a 2262During the connection, you have to make sure that you always have a
1948non-empty read-queue, or an C<on_read> watcher. At the end of the 2263non-empty read-queue, or an C<on_read> watcher. At the end of the
1962 my $data = delete $_[0]{rbuf}; 2277 my $data = delete $_[0]{rbuf};
1963 }); 2278 });
1964 2279
1965The reason to use C<on_error> is that TCP connections, due to latencies 2280The reason to use C<on_error> is that TCP connections, due to latencies
1966and packets loss, might get closed quite violently with an error, when in 2281and packets loss, might get closed quite violently with an error, when in
1967fact, all data has been received. 2282fact all data has been received.
1968 2283
1969It is usually better to use acknowledgements when transferring data, 2284It is usually better to use acknowledgements when transferring data,
1970to make sure the other side hasn't just died and you got the data 2285to make sure the other side hasn't just died and you got the data
1971intact. This is also one reason why so many internet protocols have an 2286intact. This is also one reason why so many internet protocols have an
1972explicit QUIT command. 2287explicit QUIT command.
1989consider using C<< ->push_shutdown >> instead. 2304consider using C<< ->push_shutdown >> instead.
1990 2305
1991=item I want to contact a TLS/SSL server, I don't care about security. 2306=item I want to contact a TLS/SSL server, I don't care about security.
1992 2307
1993If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS, 2308If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS,
1994simply connect to it and then create the AnyEvent::Handle with the C<tls> 2309connect to it and then create the AnyEvent::Handle with the C<tls>
1995parameter: 2310parameter:
1996 2311
1997 tcp_connect $host, $port, sub { 2312 tcp_connect $host, $port, sub {
1998 my ($fh) = @_; 2313 my ($fh) = @_;
1999 2314
2099 2414
2100=item * all members not documented here and not prefixed with an underscore 2415=item * all members not documented here and not prefixed with an underscore
2101are free to use in subclasses. 2416are free to use in subclasses.
2102 2417
2103Of course, new versions of AnyEvent::Handle may introduce more "public" 2418Of course, new versions of AnyEvent::Handle may introduce more "public"
2104member variables, but thats just life, at least it is documented. 2419member variables, but that's just life. At least it is documented.
2105 2420
2106=back 2421=back
2107 2422
2108=head1 AUTHOR 2423=head1 AUTHOR
2109 2424

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines