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.183 by root, Thu Sep 3 12:45:35 2009 UTC vs.
Revision 1.232 by root, Fri Mar 30 03:11:17 2012 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 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent; 7 use AnyEvent;
8 use AnyEvent::Handle; 8 use AnyEvent::Handle;
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
33=head1 DESCRIPTION 33=head1 DESCRIPTION
34 34
35This 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
36filehandles. 36stream-based filehandles (sockets, pipes, and other stream things).
37 37
38The L<AnyEvent::Intro> tutorial contains some well-documented 38The L<AnyEvent::Intro> tutorial contains some well-documented
39AnyEvent::Handle examples. 39AnyEvent::Handle examples.
40 40
41In the following, when the documentation refers to of "bytes" then this 41In the following, where the documentation refers to "bytes", it means
42means characters. As sysread and syswrite are used for all I/O, their 42characters. As sysread and syswrite are used for all I/O, their
43treatment of characters applies to this module as well. 43treatment of characters applies to this module as well.
44 44
45At 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
46C<on_error> callback. 46C<on_error> callback.
47 47
60use AnyEvent (); BEGIN { AnyEvent::common_sense } 60use AnyEvent (); BEGIN { AnyEvent::common_sense }
61use AnyEvent::Util qw(WSAEWOULDBLOCK); 61use AnyEvent::Util qw(WSAEWOULDBLOCK);
62 62
63our $VERSION = $AnyEvent::VERSION; 63our $VERSION = $AnyEvent::VERSION;
64 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
65=head1 METHODS 82=head1 METHODS
66 83
67=over 4 84=over 4
68 85
69=item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value... 86=item $handle = B<new> AnyEvent::Handle fh => $filehandle, key => value...
70 87
71The constructor supports these arguments (all as C<< key => value >> pairs). 88The constructor supports these arguments (all as C<< key => value >> pairs).
72 89
73=over 4 90=over 4
74 91
97=over 4 114=over 4
98 115
99=item on_prepare => $cb->($handle) 116=item on_prepare => $cb->($handle)
100 117
101This (rarely used) callback is called before a new connection is 118This (rarely used) callback is called before a new connection is
102attempted, 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
103prepare the file handle with parameters required for the actual connect 121file handle with parameters required for the actual connect (as opposed to
104(as opposed to settings that can be changed when the connection is already 122settings that can be changed when the connection is already established).
105established).
106 123
107The 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
108seconds (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
109timeout is to be used). 126default timeout is to be used).
110 127
111=item on_connect => $cb->($handle, $host, $port, $retry->()) 128=item on_connect => $cb->($handle, $host, $port, $retry->())
112 129
113This callback is called when a connection has been successfully established. 130This callback is called when a connection has been successfully established.
114 131
115The actual numeric host and port (the socket peername) are passed as 132The peer's numeric host and port (the socket peername) are passed as
116parameters, 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.
117 136
137It is not allowed to use the read or write queues while the handle object
138is connecting.
139
118When, for some reason, the handle is not acceptable, then calling 140If, for some reason, the handle is not acceptable, calling C<$retry> will
119C<$retry> will continue with the next conenction target (in case of 141continue with the next connection target (in case of multi-homed hosts or
120multi-homed hosts or SRV records there can be multiple connection 142SRV records there can be multiple connection endpoints). The C<$retry>
121endpoints). When it is called then the read and write queues, eof status, 143callback can be invoked after the connect callback returns, i.e. one can
122tls status and similar properties of the handle are being reset. 144start a handshake and then decide to retry with the next host if the
145handshake fails.
123 146
124In most cases, ignoring the C<$retry> parameter is the way to go. 147In most cases, you should ignore the C<$retry> parameter.
125 148
126=item on_connect_error => $cb->($handle, $message) 149=item on_connect_error => $cb->($handle, $message)
127 150
128This callback is called when the conenction could not be 151This callback is called when the connection could not be
129established. C<$!> will contain the relevant error code, and C<$message> a 152established. C<$!> will contain the relevant error code, and C<$message> a
130message describing it (usually the same as C<"$!">). 153message describing it (usually the same as C<"$!">).
131 154
132If this callback isn't specified, then C<on_error> will be called with a 155If this callback isn't specified, then C<on_error> will be called with a
133fatal error instead. 156fatal error instead.
136 159
137=item on_error => $cb->($handle, $fatal, $message) 160=item on_error => $cb->($handle, $fatal, $message)
138 161
139This is the error callback, which is called when, well, some error 162This is the error callback, which is called when, well, some error
140occured, such as not being able to resolve the hostname, failure to 163occured, such as not being able to resolve the hostname, failure to
141connect or a read error. 164connect, or a read error.
142 165
143Some errors are fatal (which is indicated by C<$fatal> being true). On 166Some errors are fatal (which is indicated by C<$fatal> being true). On
144fatal errors the handle object will be destroyed (by a call to C<< -> 167fatal errors the handle object will be destroyed (by a call to C<< ->
145destroy >>) after invoking the error callback (which means you are free to 168destroy >>) after invoking the error callback (which means you are free to
146examine the handle object). Examples of fatal errors are an EOF condition 169examine the handle object). Examples of fatal errors are an EOF condition
147with active (but unsatisifable) read watchers (C<EPIPE>) or I/O errors. In 170with active (but unsatisfiable) read watchers (C<EPIPE>) or I/O errors. In
148cases where the other side can close the connection at their will it is 171cases where the other side can close the connection at will, it is
149often easiest to not report C<EPIPE> errors in this callback. 172often easiest to not report C<EPIPE> errors in this callback.
150 173
151AnyEvent::Handle tries to find an appropriate error code for you to check 174AnyEvent::Handle tries to find an appropriate error code for you to check
152against, but in some cases (TLS errors), this does not work well. It is 175against, but in some cases (TLS errors), this does not work well. It is
153recommended to always output the C<$message> argument in human-readable 176recommended to always output the C<$message> argument in human-readable
154error messages (it's usually the same as C<"$!">). 177error messages (it's usually the same as C<"$!">).
155 178
156Non-fatal errors can be retried by simply returning, but it is recommended 179Non-fatal errors can be retried by returning, but it is recommended
157to simply ignore this parameter and instead abondon the handle object 180to simply ignore this parameter and instead abondon the handle object
158when this callback is invoked. Examples of non-fatal errors are timeouts 181when this callback is invoked. Examples of non-fatal errors are timeouts
159C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>). 182C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>).
160 183
161On callback entrance, the value of C<$!> contains the operating system 184On entry to the callback, the value of C<$!> contains the operating
162error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or 185system error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or
163C<EPROTO>). 186C<EPROTO>).
164 187
165While not mandatory, it is I<highly> recommended to set this callback, as 188While not mandatory, it is I<highly> recommended to set this callback, as
166you will not be notified of errors otherwise. The default simply calls 189you will not be notified of errors otherwise. The default just calls
167C<croak>. 190C<croak>.
168 191
169=item on_read => $cb->($handle) 192=item on_read => $cb->($handle)
170 193
171This sets the default read callback, which is called when data arrives 194This sets the default read callback, which is called when data arrives
176To access (and remove data from) the read buffer, use the C<< ->rbuf >> 199To access (and remove data from) the read buffer, use the C<< ->rbuf >>
177method or access the C<< $handle->{rbuf} >> member directly. Note that you 200method or access the C<< $handle->{rbuf} >> member directly. Note that you
178must not enlarge or modify the read buffer, you can only remove data at 201must not enlarge or modify the read buffer, you can only remove data at
179the beginning from it. 202the beginning from it.
180 203
204You can also call C<< ->push_read (...) >> or any other function that
205modifies the read queue. Or do both. Or ...
206
181When an EOF condition is detected then AnyEvent::Handle will first try to 207When an EOF condition is detected, AnyEvent::Handle will first try to
182feed all the remaining data to the queued callbacks and C<on_read> before 208feed all the remaining data to the queued callbacks and C<on_read> before
183calling the C<on_eof> callback. If no progress can be made, then a fatal 209calling the C<on_eof> callback. If no progress can be made, then a fatal
184error will be raised (with C<$!> set to C<EPIPE>). 210error will be raised (with C<$!> set to C<EPIPE>).
185 211
186Note that, unlike requests in the read queue, an C<on_read> callback 212Note that, unlike requests in the read queue, an C<on_read> callback
204If 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
205set, 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>.
206 232
207=item on_drain => $cb->($handle) 233=item on_drain => $cb->($handle)
208 234
209This 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
210(or when the callback is set and the buffer is empty already). 236empty (and immediately when the handle object is created).
211 237
212To append to the write buffer, use the C<< ->push_write >> method. 238To append to the write buffer, use the C<< ->push_write >> method.
213 239
214This 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
215into 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
227many seconds pass without a successful read or write on the underlying 253many seconds pass without a successful read or write on the underlying
228file handle (or a call to C<timeout_reset>), the C<on_timeout> callback 254file handle (or a call to C<timeout_reset>), the C<on_timeout> callback
229will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT> 255will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT>
230error will be raised). 256error will be raised).
231 257
232There are three variants of the timeouts that work fully independent 258There are three variants of the timeouts that work independently of each
233of each other, for both read and write, just read, and just write: 259other, for both read and write (triggered when nothing was read I<OR>
260written), just read (triggered when nothing was read), and just write:
234C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks 261C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks
235C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions 262C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions
236C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>. 263C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>.
237 264
238Note that timeout processing is also active when you currently do not have 265Note that timeout processing is active even when you do not have any
239any outstanding read or write requests: If you plan to keep the connection 266outstanding read or write requests: If you plan to keep the connection
240idle then you should disable the timout temporarily or ignore the timeout 267idle then you should disable the timeout temporarily or ignore the
241in the C<on_timeout> callback, in which case AnyEvent::Handle will simply 268timeout in the corresponding C<on_timeout> callback, in which case
242restart the timeout. 269AnyEvent::Handle will simply restart the timeout.
243 270
244Zero (the default) disables this timeout. 271Zero (the default) disables the corresponding timeout.
245 272
246=item on_timeout => $cb->($handle) 273=item on_timeout => $cb->($handle)
274
275=item on_rtimeout => $cb->($handle)
276
277=item on_wtimeout => $cb->($handle)
247 278
248Called whenever the inactivity timeout passes. If you return from this 279Called whenever the inactivity timeout passes. If you return from this
249callback, then the timeout will be reset as if some activity had happened, 280callback, then the timeout will be reset as if some activity had happened,
250so this condition is not fatal in any way. 281so this condition is not fatal in any way.
251 282
259be configured to accept only so-and-so much data that it cannot act on 290be configured to accept only so-and-so much data that it cannot act on
260(for example, when expecting a line, an attacker could send an unlimited 291(for example, when expecting a line, an attacker could send an unlimited
261amount of data without a callback ever being called as long as the line 292amount of data without a callback ever being called as long as the line
262isn't finished). 293isn't finished).
263 294
295=item wbuf_max => <bytes>
296
297If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
298when the write buffer ever (strictly) exceeds this size. This is useful to
299avoid some forms of denial-of-service attacks.
300
301Although the units of this parameter is bytes, this is the I<raw> number
302of bytes not yet accepted by the kernel. This can make a difference when
303you e.g. use TLS, as TLS typically makes your write data larger (but it
304can also make it smaller due to compression).
305
306As an example of when this limit is useful, take a chat server that sends
307chat messages to a client. If the client does not read those in a timely
308manner then the send buffer in the server would grow unbounded.
309
264=item autocork => <boolean> 310=item autocork => <boolean>
265 311
266When disabled (the default), then C<push_write> will try to immediately 312When disabled (the default), C<push_write> will try to immediately
267write the data to the handle, if possible. This avoids having to register 313write the data to the handle if possible. This avoids having to register
268a write watcher and wait for the next event loop iteration, but can 314a write watcher and wait for the next event loop iteration, but can
269be inefficient if you write multiple small chunks (on the wire, this 315be inefficient if you write multiple small chunks (on the wire, this
270disadvantage is usually avoided by your kernel's nagle algorithm, see 316disadvantage is usually avoided by your kernel's nagle algorithm, see
271C<no_delay>, but this option can save costly syscalls). 317C<no_delay>, but this option can save costly syscalls).
272 318
273When enabled, then writes will always be queued till the next event loop 319When enabled, writes will always be queued till the next event loop
274iteration. This is efficient when you do many small writes per iteration, 320iteration. This is efficient when you do many small writes per iteration,
275but less efficient when you do a single write only per iteration (or when 321but less efficient when you do a single write only per iteration (or when
276the write buffer often is full). It also increases write latency. 322the write buffer often is full). It also increases write latency.
277 323
278=item no_delay => <boolean> 324=item no_delay => <boolean>
282the Nagle algorithm, and usually it is beneficial. 328the Nagle algorithm, and usually it is beneficial.
283 329
284In some situations you want as low a delay as possible, which can be 330In some situations you want as low a delay as possible, which can be
285accomplishd by setting this option to a true value. 331accomplishd by setting this option to a true value.
286 332
287The default is your opertaing system's default behaviour (most likely 333The default is your operating system's default behaviour (most likely
288enabled), this option explicitly enables or disables it, if possible. 334enabled). This option explicitly enables or disables it, if possible.
289 335
290=item keepalive => <boolean> 336=item keepalive => <boolean>
291 337
292Enables (default disable) the SO_KEEPALIVE option on the stream socket: 338Enables (default disable) the SO_KEEPALIVE option on the stream socket:
293normally, TCP connections have no time-out once established, so TCP 339normally, TCP connections have no time-out once established, so TCP
294conenctions, once established, can stay alive forever even when the other 340connections, once established, can stay alive forever even when the other
295side has long gone. TCP keepalives are a cheap way to take down long-lived 341side has long gone. TCP keepalives are a cheap way to take down long-lived
296TCP connections whent he other side becomes unreachable. While the default 342TCP connections when the other side becomes unreachable. While the default
297is OS-dependent, TCP keepalives usually kick in after around two hours, 343is OS-dependent, TCP keepalives usually kick in after around two hours,
298and, if the other side doesn't reply, take down the TCP connection some 10 344and, if the other side doesn't reply, take down the TCP connection some 10
299to 15 minutes later. 345to 15 minutes later.
300 346
301It is harmless to specify this option for file handles that do not support 347It is harmless to specify this option for file handles that do not support
312is enabled) gives you the most portable way of getting urgent data, by 358is enabled) gives you the most portable way of getting urgent data, by
313putting it into the stream. 359putting it into the stream.
314 360
315Since BSD emulation of OOB data on top of TCP's urgent data can have 361Since BSD emulation of OOB data on top of TCP's urgent data can have
316security implications, AnyEvent::Handle sets this flag automatically 362security implications, AnyEvent::Handle sets this flag automatically
317unless explicitly specified. 363unless explicitly specified. Note that setting this flag after
364establishing a connection I<may> be a bit too late (data loss could
365already have occured on BSD systems), but at least it will protect you
366from most attacks.
318 367
319=item read_size => <bytes> 368=item read_size => <bytes>
320 369
321The default read block size (the amount of bytes this module will 370The initial read block size, the number of bytes this module will try
322try to read during each loop iteration, which affects memory 371to read during each loop iteration. Each handle object will consume
323requirements). Default: C<8192>. 372at least this amount of memory for the read buffer as well, so when
373handling many connections watch out for memory requirements). See also
374C<max_read_size>. Default: C<2048>.
375
376=item max_read_size => <bytes>
377
378The maximum read buffer size used by the dynamic adjustment
379algorithm: Each time AnyEvent::Handle can read C<read_size> bytes in
380one go it will double C<read_size> up to the maximum given by this
381option. Default: C<131072> or C<read_size>, whichever is higher.
324 382
325=item low_water_mark => <bytes> 383=item low_water_mark => <bytes>
326 384
327Sets the amount of bytes (default: C<0>) that make up an "empty" write 385Sets the number of bytes (default: C<0>) that make up an "empty" write
328buffer: If the write reaches this size or gets even samller it is 386buffer: If the buffer reaches this size or gets even samller it is
329considered empty. 387considered empty.
330 388
331Sometimes it can be beneficial (for performance reasons) to add data to 389Sometimes it can be beneficial (for performance reasons) to add data to
332the write buffer before it is fully drained, but this is a rare case, as 390the write buffer before it is fully drained, but this is a rare case, as
333the operating system kernel usually buffers data as well, so the default 391the operating system kernel usually buffers data as well, so the default
334is good in almost all cases. 392is good in almost all cases.
335 393
336=item linger => <seconds> 394=item linger => <seconds>
337 395
338If non-zero (default: C<3600>), then the destructor of the 396If this is non-zero (default: C<3600>), the destructor of the
339AnyEvent::Handle object will check whether there is still outstanding 397AnyEvent::Handle object will check whether there is still outstanding
340write data and will install a watcher that will write this data to the 398write data and will install a watcher that will write this data to the
341socket. No errors will be reported (this mostly matches how the operating 399socket. No errors will be reported (this mostly matches how the operating
342system treats outstanding data at socket close time). 400system treats outstanding data at socket close time).
343 401
350A string used to identify the remote site - usually the DNS hostname 408A string used to identify the remote site - usually the DNS hostname
351(I<not> IDN!) used to create the connection, rarely the IP address. 409(I<not> IDN!) used to create the connection, rarely the IP address.
352 410
353Apart from being useful in error messages, this string is also used in TLS 411Apart from being useful in error messages, this string is also used in TLS
354peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This 412peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This
355verification will be skipped when C<peername> is not specified or 413verification will be skipped when C<peername> is not specified or is
356C<undef>. 414C<undef>.
357 415
358=item tls => "accept" | "connect" | Net::SSLeay::SSL object 416=item tls => "accept" | "connect" | Net::SSLeay::SSL object
359 417
360When this parameter is given, it enables TLS (SSL) mode, that means 418When this parameter is given, it enables TLS (SSL) mode, that means
361AnyEvent will start a TLS handshake as soon as the conenction has been 419AnyEvent will start a TLS handshake as soon as the connection has been
362established and will transparently encrypt/decrypt data afterwards. 420established and will transparently encrypt/decrypt data afterwards.
363 421
364All TLS protocol errors will be signalled as C<EPROTO>, with an 422All TLS protocol errors will be signalled as C<EPROTO>, with an
365appropriate error message. 423appropriate error message.
366 424
386B<IMPORTANT:> since Net::SSLeay "objects" are really only integers, 444B<IMPORTANT:> since Net::SSLeay "objects" are really only integers,
387passing in the wrong integer will lead to certain crash. This most often 445passing in the wrong integer will lead to certain crash. This most often
388happens when one uses a stylish C<< tls => 1 >> and is surprised about the 446happens when one uses a stylish C<< tls => 1 >> and is surprised about the
389segmentation fault. 447segmentation fault.
390 448
391See the C<< ->starttls >> method for when need to start TLS negotiation later. 449Use the C<< ->starttls >> method if you need to start TLS negotiation later.
392 450
393=item tls_ctx => $anyevent_tls 451=item tls_ctx => $anyevent_tls
394 452
395Use the given C<AnyEvent::TLS> object to create the new TLS connection 453Use the given C<AnyEvent::TLS> object to create the new TLS connection
396(unless a connection object was specified directly). If this parameter is 454(unless a connection object was specified directly). If this
397missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>. 455parameter is missing (or C<undef>), then AnyEvent::Handle will use
456C<AnyEvent::Handle::TLS_CTX>.
398 457
399Instead of an object, you can also specify a hash reference with C<< key 458Instead of an object, you can also specify a hash reference with C<< key
400=> value >> pairs. Those will be passed to L<AnyEvent::TLS> to create a 459=> value >> pairs. Those will be passed to L<AnyEvent::TLS> to create a
401new TLS context object. 460new TLS context object.
402 461
411 470
412TLS handshake failures will not cause C<on_error> to be invoked when this 471TLS handshake failures will not cause C<on_error> to be invoked when this
413callback is in effect, instead, the error message will be passed to C<on_starttls>. 472callback is in effect, instead, the error message will be passed to C<on_starttls>.
414 473
415Without this callback, handshake failures lead to C<on_error> being 474Without this callback, handshake failures lead to C<on_error> being
416called, as normal. 475called as usual.
417 476
418Note that you cannot call C<starttls> right again in this callback. If you 477Note that you cannot just call C<starttls> again in this callback. If you
419need to do that, start an zero-second timer instead whose callback can 478need to do that, start an zero-second timer instead whose callback can
420then call C<< ->starttls >> again. 479then call C<< ->starttls >> again.
421 480
422=item on_stoptls => $cb->($handle) 481=item on_stoptls => $cb->($handle)
423 482
471 $self->{connect}[0], 530 $self->{connect}[0],
472 $self->{connect}[1], 531 $self->{connect}[1],
473 sub { 532 sub {
474 my ($fh, $host, $port, $retry) = @_; 533 my ($fh, $host, $port, $retry) = @_;
475 534
535 delete $self->{_connect}; # no longer needed
536
476 if ($fh) { 537 if ($fh) {
477 $self->{fh} = $fh; 538 $self->{fh} = $fh;
478 539
479 delete $self->{_skip_drain_rbuf}; 540 delete $self->{_skip_drain_rbuf};
480 $self->_start; 541 $self->_start;
487 }); 548 });
488 549
489 } else { 550 } else {
490 if ($self->{on_connect_error}) { 551 if ($self->{on_connect_error}) {
491 $self->{on_connect_error}($self, "$!"); 552 $self->{on_connect_error}($self, "$!");
492 $self->destroy; 553 $self->destroy if $self;
493 } else { 554 } else {
494 $self->_error ($!, 1); 555 $self->_error ($!, 1);
495 } 556 }
496 } 557 }
497 }, 558 },
498 sub { 559 sub {
499 local $self->{fh} = $_[0]; 560 local $self->{fh} = $_[0];
500 561
501 $self->{on_prepare} 562 $self->{on_prepare}
502 ? $self->{on_prepare}->($self) 563 ? $self->{on_prepare}->($self)
503 : () 564 : ()
504 } 565 }
505 ); 566 );
506 } 567 }
507 568
513} 574}
514 575
515sub _start { 576sub _start {
516 my ($self) = @_; 577 my ($self) = @_;
517 578
579 # too many clueless people try to use udp and similar sockets
580 # with AnyEvent::Handle, do them a favour.
581 my $type = getsockopt $self->{fh}, Socket::SOL_SOCKET (), Socket::SO_TYPE ();
582 Carp::croak "AnyEvent::Handle: only stream sockets supported, anything else will NOT work!"
583 if Socket::SOCK_STREAM () != (unpack "I", $type) && defined $type;
584
518 AnyEvent::Util::fh_nonblocking $self->{fh}, 1; 585 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
519 586
520 $self->{_activity} = 587 $self->{_activity} =
521 $self->{_ractivity} = 588 $self->{_ractivity} =
522 $self->{_wactivity} = AE::now; 589 $self->{_wactivity} = AE::now;
523 590
591 $self->{read_size} ||= 2048;
592 $self->{max_read_size} = $self->{read_size}
593 if $self->{read_size} > ($self->{max_read_size} || MAX_READ_SIZE);
594
524 $self->timeout (delete $self->{timeout} ) if $self->{timeout}; 595 $self->timeout (delete $self->{timeout} ) if $self->{timeout};
525 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout}; 596 $self->rtimeout (delete $self->{rtimeout} ) if $self->{rtimeout};
526 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout}; 597 $self->wtimeout (delete $self->{wtimeout} ) if $self->{wtimeout};
527 598
528 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay} && $self->{no_delay}; 599 $self->no_delay (delete $self->{no_delay} ) if exists $self->{no_delay} && $self->{no_delay};
531 $self->oobinline (exists $self->{oobinline} ? delete $self->{oobinline} : 1); 602 $self->oobinline (exists $self->{oobinline} ? delete $self->{oobinline} : 1);
532 603
533 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}) 604 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
534 if $self->{tls}; 605 if $self->{tls};
535 606
536 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 607 $self->on_drain (delete $self->{on_drain} ) if $self->{on_drain};
537 608
538 $self->start_read 609 $self->start_read
539 if $self->{on_read} || @{ $self->{_queue} }; 610 if $self->{on_read} || @{ $self->{_queue} };
540 611
541 $self->_drain_wbuf; 612 $self->_drain_wbuf;
548 $message ||= "$!"; 619 $message ||= "$!";
549 620
550 if ($self->{on_error}) { 621 if ($self->{on_error}) {
551 $self->{on_error}($self, $fatal, $message); 622 $self->{on_error}($self, $fatal, $message);
552 $self->destroy if $fatal; 623 $self->destroy if $fatal;
553 } elsif ($self->{fh}) { 624 } elsif ($self->{fh} || $self->{connect}) {
554 $self->destroy; 625 $self->destroy;
555 Carp::croak "AnyEvent::Handle uncaught error: $message"; 626 Carp::croak "AnyEvent::Handle uncaught error: $message";
556 } 627 }
557} 628}
558 629
617=cut 688=cut
618 689
619sub no_delay { 690sub no_delay {
620 $_[0]{no_delay} = $_[1]; 691 $_[0]{no_delay} = $_[1];
621 692
622 eval {
623 local $SIG{__DIE__};
624 setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1] 693 setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
625 if $_[0]{fh}; 694 if $_[0]{fh};
626 };
627} 695}
628 696
629=item $handle->keepalive ($boolean) 697=item $handle->keepalive ($boolean)
630 698
631Enables or disables the C<keepalive> setting (see constructor argument of 699Enables or disables the C<keepalive> setting (see constructor argument of
691 759
692Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument). 760Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument).
693 761
694=cut 762=cut
695 763
696sub on_starttls { 764sub on_stoptls {
697 $_[0]{on_stoptls} = $_[1]; 765 $_[0]{on_stoptls} = $_[1];
698} 766}
699 767
700=item $handle->rbuf_max ($max_octets) 768=item $handle->rbuf_max ($max_octets)
701 769
702Configures the C<rbuf_max> setting (C<undef> disables it). 770Configures the C<rbuf_max> setting (C<undef> disables it).
771
772=item $handle->wbuf_max ($max_octets)
773
774Configures the C<wbuf_max> setting (C<undef> disables it).
703 775
704=cut 776=cut
705 777
706sub rbuf_max { 778sub rbuf_max {
707 $_[0]{rbuf_max} = $_[1]; 779 $_[0]{rbuf_max} = $_[1];
708} 780}
709 781
782sub wbuf_max {
783 $_[0]{wbuf_max} = $_[1];
784}
785
710############################################################################# 786#############################################################################
711 787
712=item $handle->timeout ($seconds) 788=item $handle->timeout ($seconds)
713 789
714=item $handle->rtimeout ($seconds) 790=item $handle->rtimeout ($seconds)
715 791
716=item $handle->wtimeout ($seconds) 792=item $handle->wtimeout ($seconds)
717 793
718Configures (or disables) the inactivity timeout. 794Configures (or disables) the inactivity timeout.
795
796The timeout will be checked instantly, so this method might destroy the
797handle before it returns.
719 798
720=item $handle->timeout_reset 799=item $handle->timeout_reset
721 800
722=item $handle->rtimeout_reset 801=item $handle->rtimeout_reset
723 802
740 $_[0]{$on_timeout} = $_[1]; 819 $_[0]{$on_timeout} = $_[1];
741 }; 820 };
742 821
743 *$timeout = sub { 822 *$timeout = sub {
744 my ($self, $new_value) = @_; 823 my ($self, $new_value) = @_;
824
825 $new_value >= 0
826 or Carp::croak "AnyEvent::Handle->$timeout called with negative timeout ($new_value), caught";
745 827
746 $self->{$timeout} = $new_value; 828 $self->{$timeout} = $new_value;
747 delete $self->{$tw}; &$cb; 829 delete $self->{$tw}; &$cb;
748 }; 830 };
749 831
804 886
805The 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
806AnyEvent::Handle will automatically try to get rid of it for you. 888AnyEvent::Handle will automatically try to get rid of it for you.
807 889
808When 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
809water mark, the C<on_drain> callback will be invoked. 891water mark, the C<on_drain> callback will be invoked once.
810 892
811=over 4 893=over 4
812 894
813=item $handle->on_drain ($cb) 895=item $handle->on_drain ($cb)
814 896
815Sets the C<on_drain> callback or clears it (see the description of 897Sets the C<on_drain> callback or clears it (see the description of
816C<on_drain> in the constructor). 898C<on_drain> in the constructor).
817 899
900This method may invoke callbacks (and therefore the handle might be
901destroyed after it returns).
902
818=cut 903=cut
819 904
820sub on_drain { 905sub on_drain {
821 my ($self, $cb) = @_; 906 my ($self, $cb) = @_;
822 907
826 if $cb && $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf}); 911 if $cb && $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf});
827} 912}
828 913
829=item $handle->push_write ($data) 914=item $handle->push_write ($data)
830 915
831Queues the given scalar to be written. You can push as much data as you 916Queues the given scalar to be written. You can push as much data as
832want (only limited by the available memory), as C<AnyEvent::Handle> 917you want (only limited by the available memory and C<wbuf_max>), as
833buffers it independently of the kernel. 918C<AnyEvent::Handle> buffers it independently of the kernel.
919
920This method may invoke callbacks (and therefore the handle might be
921destroyed after it returns).
834 922
835=cut 923=cut
836 924
837sub _drain_wbuf { 925sub _drain_wbuf {
838 my ($self) = @_; 926 my ($self) = @_;
863 $cb->() unless $self->{autocork}; 951 $cb->() unless $self->{autocork};
864 952
865 # if still data left in wbuf, we need to poll 953 # if still data left in wbuf, we need to poll
866 $self->{_ww} = AE::io $self->{fh}, 1, $cb 954 $self->{_ww} = AE::io $self->{fh}, 1, $cb
867 if length $self->{wbuf}; 955 if length $self->{wbuf};
956
957 if (
958 defined $self->{wbuf_max}
959 && $self->{wbuf_max} < length $self->{wbuf}
960 ) {
961 $self->_error (Errno::ENOSPC, 1), return;
962 }
868 }; 963 };
869} 964}
870 965
871our %WH; 966our %WH;
872 967
968# deprecated
873sub register_write_type($$) { 969sub register_write_type($$) {
874 $WH{$_[0]} = $_[1]; 970 $WH{$_[0]} = $_[1];
875} 971}
876 972
877sub push_write { 973sub push_write {
878 my $self = shift; 974 my $self = shift;
879 975
880 if (@_ > 1) { 976 if (@_ > 1) {
881 my $type = shift; 977 my $type = shift;
882 978
979 @_ = ($WH{$type} ||= _load_func "$type\::anyevent_write_type"
883 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write") 980 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_write")
884 ->($self, @_); 981 ->($self, @_);
885 } 982 }
886 983
984 # we downgrade here to avoid hard-to-track-down bugs,
985 # and diagnose the problem earlier and better.
986
887 if ($self->{tls}) { 987 if ($self->{tls}) {
888 $self->{_tls_wbuf} .= $_[0]; 988 utf8::downgrade $self->{_tls_wbuf} .= $_[0];
889 &_dotls ($self) if $self->{fh}; 989 &_dotls ($self) if $self->{fh};
890 } else { 990 } else {
891 $self->{wbuf} .= $_[0]; 991 utf8::downgrade $self->{wbuf} .= $_[0];
892 $self->_drain_wbuf if $self->{fh}; 992 $self->_drain_wbuf if $self->{fh};
893 } 993 }
894} 994}
895 995
896=item $handle->push_write (type => @args) 996=item $handle->push_write (type => @args)
897 997
898Instead of formatting your data yourself, you can also let this module do 998Instead of formatting your data yourself, you can also let this module
899the job by specifying a type and type-specific arguments. 999do the job by specifying a type and type-specific arguments. You
1000can also specify the (fully qualified) name of a package, in which
1001case AnyEvent tries to load the package and then expects to find the
1002C<anyevent_write_type> function inside (see "custom write types", below).
900 1003
901Predefined types are (if you have ideas for additional types, feel free to 1004Predefined types are (if you have ideas for additional types, feel free to
902drop by and tell us): 1005drop by and tell us):
903 1006
904=over 4 1007=over 4
984=cut 1087=cut
985 1088
986register_write_type storable => sub { 1089register_write_type storable => sub {
987 my ($self, $ref) = @_; 1090 my ($self, $ref) = @_;
988 1091
989 require Storable; 1092 require Storable unless $Storable::VERSION;
990 1093
991 pack "w/a*", Storable::nfreeze ($ref) 1094 pack "w/a*", Storable::nfreeze ($ref)
992}; 1095};
993 1096
994=back 1097=back
999before it was actually written. One way to do that is to replace your 1102before it was actually written. One way to do that is to replace your
1000C<on_drain> handler by a callback that shuts down the socket (and set 1103C<on_drain> handler by a callback that shuts down the socket (and set
1001C<low_water_mark> to C<0>). This method is a shorthand for just that, and 1104C<low_water_mark> to C<0>). This method is a shorthand for just that, and
1002replaces the C<on_drain> callback with: 1105replaces the C<on_drain> callback with:
1003 1106
1004 sub { shutdown $_[0]{fh}, 1 } # for push_shutdown 1107 sub { shutdown $_[0]{fh}, 1 }
1005 1108
1006This simply shuts down the write side and signals an EOF condition to the 1109This simply shuts down the write side and signals an EOF condition to the
1007the peer. 1110the peer.
1008 1111
1009You can rely on the normal read queue and C<on_eof> handling 1112You can rely on the normal read queue and C<on_eof> handling
1010afterwards. This is the cleanest way to close a connection. 1113afterwards. This is the cleanest way to close a connection.
1011 1114
1115This method may invoke callbacks (and therefore the handle might be
1116destroyed after it returns).
1117
1012=cut 1118=cut
1013 1119
1014sub push_shutdown { 1120sub push_shutdown {
1015 my ($self) = @_; 1121 my ($self) = @_;
1016 1122
1017 delete $self->{low_water_mark}; 1123 delete $self->{low_water_mark};
1018 $self->on_drain (sub { shutdown $_[0]{fh}, 1 }); 1124 $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
1019} 1125}
1020 1126
1021=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args) 1127=item custom write types - Package::anyevent_write_type $handle, @args
1022 1128
1023This function (not method) lets you add your own types to C<push_write>. 1129Instead of one of the predefined types, you can also specify the name of
1130a package. AnyEvent will try to load the package and then expects to find
1131a function named C<anyevent_write_type> inside. If it isn't found, it
1132progressively tries to load the parent package until it either finds the
1133function (good) or runs out of packages (bad).
1134
1024Whenever the given C<type> is used, C<push_write> will invoke the code 1135Whenever the given C<type> is used, C<push_write> will the function with
1025reference with the handle object and the remaining arguments. 1136the handle object and the remaining arguments.
1026 1137
1027The code reference is supposed to return a single octet string that will 1138The function is supposed to return a single octet string that will be
1028be appended to the write buffer. 1139appended to the write buffer, so you can mentally treat this function as a
1140"arguments to on-the-wire-format" converter.
1029 1141
1030Note that this is a function, and all types registered this way will be 1142Example: implement a custom write type C<join> that joins the remaining
1031global, so try to use unique names. 1143arguments using the first one.
1144
1145 $handle->push_write (My::Type => " ", 1,2,3);
1146
1147 # uses the following package, which can be defined in the "My::Type" or in
1148 # the "My" modules to be auto-loaded, or just about anywhere when the
1149 # My::Type::anyevent_write_type is defined before invoking it.
1150
1151 package My::Type;
1152
1153 sub anyevent_write_type {
1154 my ($handle, $delim, @args) = @_;
1155
1156 join $delim, @args
1157 }
1032 1158
1033=cut 1159=cut
1034 1160
1035############################################################################# 1161#############################################################################
1036 1162
1045ways, the "simple" way, using only C<on_read> and the "complex" way, using 1171ways, the "simple" way, using only C<on_read> and the "complex" way, using
1046a queue. 1172a queue.
1047 1173
1048In the simple case, you just install an C<on_read> callback and whenever 1174In the simple case, you just install an C<on_read> callback and whenever
1049new data arrives, it will be called. You can then remove some data (if 1175new data arrives, it will be called. You can then remove some data (if
1050enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna 1176enough is there) from the read buffer (C<< $handle->rbuf >>). Or you can
1051leave the data there if you want to accumulate more (e.g. when only a 1177leave the data there if you want to accumulate more (e.g. when only a
1052partial message has been received so far). 1178partial message has been received so far), or change the read queue with
1179e.g. C<push_read>.
1053 1180
1054In the more complex case, you want to queue multiple callbacks. In this 1181In the more complex case, you want to queue multiple callbacks. In this
1055case, AnyEvent::Handle will call the first queued callback each time new 1182case, AnyEvent::Handle will call the first queued callback each time new
1056data arrives (also the first time it is queued) and removes it when it has 1183data arrives (also the first time it is queued) and remove it when it has
1057done its job (see C<push_read>, below). 1184done its job (see C<push_read>, below).
1058 1185
1059This way you can, for example, push three line-reads, followed by reading 1186This way you can, for example, push three line-reads, followed by reading
1060a chunk of data, and AnyEvent::Handle will execute them in order. 1187a chunk of data, and AnyEvent::Handle will execute them in order.
1061 1188
1192 1319
1193This replaces the currently set C<on_read> callback, or clears it (when 1320This replaces the currently set C<on_read> callback, or clears it (when
1194the new callback is C<undef>). See the description of C<on_read> in the 1321the new callback is C<undef>). See the description of C<on_read> in the
1195constructor. 1322constructor.
1196 1323
1324This method may invoke callbacks (and therefore the handle might be
1325destroyed after it returns).
1326
1197=cut 1327=cut
1198 1328
1199sub on_read { 1329sub on_read {
1200 my ($self, $cb) = @_; 1330 my ($self, $cb) = @_;
1201 1331
1203 $self->_drain_rbuf if $cb; 1333 $self->_drain_rbuf if $cb;
1204} 1334}
1205 1335
1206=item $handle->rbuf 1336=item $handle->rbuf
1207 1337
1208Returns the read buffer (as a modifiable lvalue). 1338Returns the read buffer (as a modifiable lvalue). You can also access the
1339read buffer directly as the C<< ->{rbuf} >> member, if you want (this is
1340much faster, and no less clean).
1209 1341
1210You can access the read buffer directly as the C<< ->{rbuf} >> 1342The only operation allowed on the read buffer (apart from looking at it)
1211member, if you want. However, the only operation allowed on the 1343is removing data from its beginning. Otherwise modifying or appending to
1212read buffer (apart from looking at it) is removing data from its 1344it is not allowed and will lead to hard-to-track-down bugs.
1213beginning. Otherwise modifying or appending to it is not allowed and will
1214lead to hard-to-track-down bugs.
1215 1345
1216NOTE: The read buffer should only be used or modified if the C<on_read>, 1346NOTE: The read buffer should only be used or modified in the C<on_read>
1217C<push_read> or C<unshift_read> methods are used. The other read methods 1347callback or when C<push_read> or C<unshift_read> are used with a single
1218automatically manage the read buffer. 1348callback (i.e. untyped). Typed C<push_read> and C<unshift_read> methods
1349will manage the read buffer on their own.
1219 1350
1220=cut 1351=cut
1221 1352
1222sub rbuf : lvalue { 1353sub rbuf : lvalue {
1223 $_[0]{rbuf} 1354 $_[0]{rbuf}
1240 1371
1241If enough data was available, then the callback must remove all data it is 1372If enough data was available, then the callback must remove all data it is
1242interested in (which can be none at all) and return a true value. After returning 1373interested in (which can be none at all) and return a true value. After returning
1243true, it will be removed from the queue. 1374true, it will be removed from the queue.
1244 1375
1376These methods may invoke callbacks (and therefore the handle might be
1377destroyed after it returns).
1378
1245=cut 1379=cut
1246 1380
1247our %RH; 1381our %RH;
1248 1382
1249sub register_read_type($$) { 1383sub register_read_type($$) {
1255 my $cb = pop; 1389 my $cb = pop;
1256 1390
1257 if (@_) { 1391 if (@_) {
1258 my $type = shift; 1392 my $type = shift;
1259 1393
1394 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1260 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read") 1395 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::push_read")
1261 ->($self, $cb, @_); 1396 ->($self, $cb, @_);
1262 } 1397 }
1263 1398
1264 push @{ $self->{_queue} }, $cb; 1399 push @{ $self->{_queue} }, $cb;
1265 $self->_drain_rbuf; 1400 $self->_drain_rbuf;
1270 my $cb = pop; 1405 my $cb = pop;
1271 1406
1272 if (@_) { 1407 if (@_) {
1273 my $type = shift; 1408 my $type = shift;
1274 1409
1410 $cb = ($RH{$type} ||= _load_func "$type\::anyevent_read_type"
1275 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read") 1411 or Carp::croak "unsupported/unloadable type '$type' passed to AnyEvent::Handle::unshift_read")
1276 ->($self, $cb, @_); 1412 ->($self, $cb, @_);
1277 } 1413 }
1278 1414
1279 unshift @{ $self->{_queue} }, $cb; 1415 unshift @{ $self->{_queue} }, $cb;
1280 $self->_drain_rbuf; 1416 $self->_drain_rbuf;
1284 1420
1285=item $handle->unshift_read (type => @args, $cb) 1421=item $handle->unshift_read (type => @args, $cb)
1286 1422
1287Instead of providing a callback that parses the data itself you can chose 1423Instead of providing a callback that parses the data itself you can chose
1288between a number of predefined parsing formats, for chunks of data, lines 1424between a number of predefined parsing formats, for chunks of data, lines
1289etc. 1425etc. You can also specify the (fully qualified) name of a package, in
1426which case AnyEvent tries to load the package and then expects to find the
1427C<anyevent_read_type> function inside (see "custom read types", below).
1290 1428
1291Predefined types are (if you have ideas for additional types, feel free to 1429Predefined types are (if you have ideas for additional types, feel free to
1292drop by and tell us): 1430drop by and tell us):
1293 1431
1294=over 4 1432=over 4
1300data. 1438data.
1301 1439
1302Example: read 2 bytes. 1440Example: read 2 bytes.
1303 1441
1304 $handle->push_read (chunk => 2, sub { 1442 $handle->push_read (chunk => 2, sub {
1305 warn "yay ", unpack "H*", $_[1]; 1443 say "yay " . unpack "H*", $_[1];
1306 }); 1444 });
1307 1445
1308=cut 1446=cut
1309 1447
1310register_read_type chunk => sub { 1448register_read_type chunk => sub {
1344 if (@_ < 3) { 1482 if (@_ < 3) {
1345 # 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
1346 sub { 1484 sub {
1347 $_[0]{rbuf} =~ s/^([^\015\012]*)(\015?\012)// or return; 1485 $_[0]{rbuf} =~ s/^([^\015\012]*)(\015?\012)// or return;
1348 1486
1349 $cb->($_[0], $1, $2); 1487 $cb->($_[0], "$1", "$2");
1350 1 1488 1
1351 } 1489 }
1352 } else { 1490 } else {
1353 $eol = quotemeta $eol unless ref $eol; 1491 $eol = quotemeta $eol unless ref $eol;
1354 $eol = qr|^(.*?)($eol)|s; 1492 $eol = qr|^(.*?)($eol)|s;
1355 1493
1356 sub { 1494 sub {
1357 $_[0]{rbuf} =~ s/$eol// or return; 1495 $_[0]{rbuf} =~ s/$eol// or return;
1358 1496
1359 $cb->($_[0], $1, $2); 1497 $cb->($_[0], "$1", "$2");
1360 1 1498 1
1361 } 1499 }
1362 } 1500 }
1363}; 1501};
1364 1502
1386the receive buffer when neither C<$accept> nor C<$reject> match, 1524the receive buffer when neither C<$accept> nor C<$reject> match,
1387and everything preceding and including the match will be accepted 1525and everything preceding and including the match will be accepted
1388unconditionally. This is useful to skip large amounts of data that you 1526unconditionally. This is useful to skip large amounts of data that you
1389know cannot be matched, so that the C<$accept> or C<$reject> regex do not 1527know cannot be matched, so that the C<$accept> or C<$reject> regex do not
1390have to start matching from the beginning. This is purely an optimisation 1528have to start matching from the beginning. This is purely an optimisation
1391and is usually worth only when you expect more than a few kilobytes. 1529and is usually worth it only when you expect more than a few kilobytes.
1392 1530
1393Example: expect a http header, which ends at C<\015\012\015\012>. Since we 1531Example: expect a http header, which ends at C<\015\012\015\012>. Since we
1394expect the header to be very large (it isn't in practise, but...), we use 1532expect the header to be very large (it isn't in practice, but...), we use
1395a skip regex to skip initial portions. The skip regex is tricky in that 1533a skip regex to skip initial portions. The skip regex is tricky in that
1396it only accepts something not ending in either \015 or \012, as these are 1534it only accepts something not ending in either \015 or \012, as these are
1397required for the accept regex. 1535required for the accept regex.
1398 1536
1399 $handle->push_read (regex => 1537 $handle->push_read (regex =>
1412 1550
1413 sub { 1551 sub {
1414 # accept 1552 # accept
1415 if ($$rbuf =~ $accept) { 1553 if ($$rbuf =~ $accept) {
1416 $data .= substr $$rbuf, 0, $+[0], ""; 1554 $data .= substr $$rbuf, 0, $+[0], "";
1417 $cb->($self, $data); 1555 $cb->($_[0], $data);
1418 return 1; 1556 return 1;
1419 } 1557 }
1420 1558
1421 # reject 1559 # reject
1422 if ($reject && $$rbuf =~ $reject) { 1560 if ($reject && $$rbuf =~ $reject) {
1423 $self->_error (Errno::EBADMSG); 1561 $_[0]->_error (Errno::EBADMSG);
1424 } 1562 }
1425 1563
1426 # skip 1564 # skip
1427 if ($skip && $$rbuf =~ $skip) { 1565 if ($skip && $$rbuf =~ $skip) {
1428 $data .= substr $$rbuf, 0, $+[0], ""; 1566 $data .= substr $$rbuf, 0, $+[0], "";
1444 my ($self, $cb) = @_; 1582 my ($self, $cb) = @_;
1445 1583
1446 sub { 1584 sub {
1447 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) { 1585 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
1448 if ($_[0]{rbuf} =~ /[^0-9]/) { 1586 if ($_[0]{rbuf} =~ /[^0-9]/) {
1449 $self->_error (Errno::EBADMSG); 1587 $_[0]->_error (Errno::EBADMSG);
1450 } 1588 }
1451 return; 1589 return;
1452 } 1590 }
1453 1591
1454 my $len = $1; 1592 my $len = $1;
1455 1593
1456 $self->unshift_read (chunk => $len, sub { 1594 $_[0]->unshift_read (chunk => $len, sub {
1457 my $string = $_[1]; 1595 my $string = $_[1];
1458 $_[0]->unshift_read (chunk => 1, sub { 1596 $_[0]->unshift_read (chunk => 1, sub {
1459 if ($_[1] eq ",") { 1597 if ($_[1] eq ",") {
1460 $cb->($_[0], $string); 1598 $cb->($_[0], $string);
1461 } else { 1599 } else {
1462 $self->_error (Errno::EBADMSG); 1600 $_[0]->_error (Errno::EBADMSG);
1463 } 1601 }
1464 }); 1602 });
1465 }); 1603 });
1466 1604
1467 1 1605 1
1540 1678
1541 my $data; 1679 my $data;
1542 my $rbuf = \$self->{rbuf}; 1680 my $rbuf = \$self->{rbuf};
1543 1681
1544 sub { 1682 sub {
1545 my $ref = eval { $json->incr_parse ($self->{rbuf}) }; 1683 my $ref = eval { $json->incr_parse ($_[0]{rbuf}) };
1546 1684
1547 if ($ref) { 1685 if ($ref) {
1548 $self->{rbuf} = $json->incr_text; 1686 $_[0]{rbuf} = $json->incr_text;
1549 $json->incr_text = ""; 1687 $json->incr_text = "";
1550 $cb->($self, $ref); 1688 $cb->($_[0], $ref);
1551 1689
1552 1 1690 1
1553 } elsif ($@) { 1691 } elsif ($@) {
1554 # error case 1692 # error case
1555 $json->incr_skip; 1693 $json->incr_skip;
1556 1694
1557 $self->{rbuf} = $json->incr_text; 1695 $_[0]{rbuf} = $json->incr_text;
1558 $json->incr_text = ""; 1696 $json->incr_text = "";
1559 1697
1560 $self->_error (Errno::EBADMSG); 1698 $_[0]->_error (Errno::EBADMSG);
1561 1699
1562 () 1700 ()
1563 } else { 1701 } else {
1564 $self->{rbuf} = ""; 1702 $_[0]{rbuf} = "";
1565 1703
1566 () 1704 ()
1567 } 1705 }
1568 } 1706 }
1569}; 1707};
1579=cut 1717=cut
1580 1718
1581register_read_type storable => sub { 1719register_read_type storable => sub {
1582 my ($self, $cb) = @_; 1720 my ($self, $cb) = @_;
1583 1721
1584 require Storable; 1722 require Storable unless $Storable::VERSION;
1585 1723
1586 sub { 1724 sub {
1587 # 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
1588 defined (my $len = eval { unpack "w", $_[0]{rbuf} }) 1726 defined (my $len = eval { unpack "w", $_[0]{rbuf} })
1589 or return; 1727 or return;
1592 1730
1593 # bypass unshift if we already have the remaining chunk 1731 # bypass unshift if we already have the remaining chunk
1594 if ($format + $len <= length $_[0]{rbuf}) { 1732 if ($format + $len <= length $_[0]{rbuf}) {
1595 my $data = substr $_[0]{rbuf}, $format, $len; 1733 my $data = substr $_[0]{rbuf}, $format, $len;
1596 substr $_[0]{rbuf}, 0, $format + $len, ""; 1734 substr $_[0]{rbuf}, 0, $format + $len, "";
1735
1597 $cb->($_[0], Storable::thaw ($data)); 1736 eval { $cb->($_[0], Storable::thaw ($data)); 1 }
1737 or return $_[0]->_error (Errno::EBADMSG);
1598 } else { 1738 } else {
1599 # remove prefix 1739 # remove prefix
1600 substr $_[0]{rbuf}, 0, $format, ""; 1740 substr $_[0]{rbuf}, 0, $format, "";
1601 1741
1602 # read remaining chunk 1742 # read remaining chunk
1603 $_[0]->unshift_read (chunk => $len, sub { 1743 $_[0]->unshift_read (chunk => $len, sub {
1604 if (my $ref = eval { Storable::thaw ($_[1]) }) { 1744 eval { $cb->($_[0], Storable::thaw ($_[1])); 1 }
1605 $cb->($_[0], $ref);
1606 } else {
1607 $self->_error (Errno::EBADMSG); 1745 or $_[0]->_error (Errno::EBADMSG);
1608 }
1609 }); 1746 });
1610 } 1747 }
1611 1748
1612 1 1749 1
1613 } 1750 }
1614}; 1751};
1615 1752
1616=back 1753=back
1617 1754
1618=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args) 1755=item custom read types - Package::anyevent_read_type $handle, $cb, @args
1619 1756
1620This function (not method) lets you add your own types to C<push_read>. 1757Instead of one of the predefined types, you can also specify the name
1758of a package. AnyEvent will try to load the package and then expects to
1759find a function named C<anyevent_read_type> inside. If it isn't found, it
1760progressively tries to load the parent package until it either finds the
1761function (good) or runs out of packages (bad).
1621 1762
1622Whenever the given C<type> is used, C<push_read> will invoke the code 1763Whenever this type is used, C<push_read> will invoke the function with the
1623reference with the handle object, the callback and the remaining 1764handle object, the original callback and the remaining arguments.
1624arguments.
1625 1765
1626The code reference is supposed to return a callback (usually a closure) 1766The function is supposed to return a callback (usually a closure) that
1627that works as a plain read callback (see C<< ->push_read ($cb) >>). 1767works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
1768mentally treat the function as a "configurable read type to read callback"
1769converter.
1628 1770
1629It should invoke the passed callback when it is done reading (remember to 1771It should invoke the original callback when it is done reading (remember
1630pass C<$handle> as first argument as all other callbacks do that). 1772to pass C<$handle> as first argument as all other callbacks do that,
1773although there is no strict requirement on this).
1631 1774
1632Note that this is a function, and all types registered this way will be
1633global, so try to use unique names.
1634
1635For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, 1775For examples, see the source of this module (F<perldoc -m
1636search for C<register_read_type>)). 1776AnyEvent::Handle>, search for C<register_read_type>)).
1637 1777
1638=item $handle->stop_read 1778=item $handle->stop_read
1639 1779
1640=item $handle->start_read 1780=item $handle->start_read
1641 1781
1647Note that AnyEvent::Handle will automatically C<start_read> for you when 1787Note that AnyEvent::Handle will automatically C<start_read> for you when
1648you change the C<on_read> callback or push/unshift a read callback, and it 1788you change the C<on_read> callback or push/unshift a read callback, and it
1649will automatically C<stop_read> for you when neither C<on_read> is set nor 1789will automatically C<stop_read> for you when neither C<on_read> is set nor
1650there are any read requests in the queue. 1790there are any read requests in the queue.
1651 1791
1652These methods will have no effect when in TLS mode (as TLS doesn't support 1792In older versions of this module (<= 5.3), these methods had no effect,
1653half-duplex connections). 1793as TLS does not support half-duplex connections. In current versions they
1794work as expected, as this behaviour is required to avoid certain resource
1795attacks, where the program would be forced to read (and buffer) arbitrary
1796amounts of data before being able to send some data. The drawback is that
1797some readings of the the SSL/TLS specifications basically require this
1798attack to be working, as SSL/TLS implementations might stall sending data
1799during a rehandshake.
1800
1801As a guideline, during the initial handshake, you should not stop reading,
1802and as a client, it might cause problems, depending on your application.
1654 1803
1655=cut 1804=cut
1656 1805
1657sub stop_read { 1806sub stop_read {
1658 my ($self) = @_; 1807 my ($self) = @_;
1659 1808
1660 delete $self->{_rw} unless $self->{tls}; 1809 delete $self->{_rw};
1661} 1810}
1662 1811
1663sub start_read { 1812sub start_read {
1664 my ($self) = @_; 1813 my ($self) = @_;
1665 1814
1666 unless ($self->{_rw} || $self->{_eof}) { 1815 unless ($self->{_rw} || $self->{_eof} || !$self->{fh}) {
1667 Scalar::Util::weaken $self; 1816 Scalar::Util::weaken $self;
1668 1817
1669 $self->{_rw} = AE::io $self->{fh}, 0, sub { 1818 $self->{_rw} = AE::io $self->{fh}, 0, sub {
1670 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf}); 1819 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1671 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1820 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size}, length $$rbuf;
1672 1821
1673 if ($len > 0) { 1822 if ($len > 0) {
1674 $self->{_activity} = $self->{_ractivity} = AE::now; 1823 $self->{_activity} = $self->{_ractivity} = AE::now;
1675 1824
1676 if ($self->{tls}) { 1825 if ($self->{tls}) {
1677 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf); 1826 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf);
1678 1827
1679 &_dotls ($self); 1828 &_dotls ($self);
1680 } else { 1829 } else {
1681 $self->_drain_rbuf; 1830 $self->_drain_rbuf;
1831 }
1832
1833 if ($len == $self->{read_size}) {
1834 $self->{read_size} *= 2;
1835 $self->{read_size} = $self->{max_read_size} || MAX_READ_SIZE
1836 if $self->{read_size} > ($self->{max_read_size} || MAX_READ_SIZE);
1682 } 1837 }
1683 1838
1684 } elsif (defined $len) { 1839 } elsif (defined $len) {
1685 delete $self->{_rw}; 1840 delete $self->{_rw};
1686 $self->{_eof} = 1; 1841 $self->{_eof} = 1;
1764 && ($tmp != $ERROR_SYSCALL || $!); 1919 && ($tmp != $ERROR_SYSCALL || $!);
1765 1920
1766 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) { 1921 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1767 $self->{wbuf} .= $tmp; 1922 $self->{wbuf} .= $tmp;
1768 $self->_drain_wbuf; 1923 $self->_drain_wbuf;
1924 $self->{tls} or return; # tls session might have gone away in callback
1769 } 1925 }
1770 1926
1771 $self->{_on_starttls} 1927 $self->{_on_starttls}
1772 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK () 1928 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
1773 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established"); 1929 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
1795context in C<< $handle->{tls_ctx} >> after this call and can be used or 1951context in C<< $handle->{tls_ctx} >> after this call and can be used or
1796changed to your liking. Note that the handshake might have already started 1952changed to your liking. Note that the handshake might have already started
1797when this function returns. 1953when this function returns.
1798 1954
1799Due to bugs in OpenSSL, it might or might not be possible to do multiple 1955Due to bugs in OpenSSL, it might or might not be possible to do multiple
1800handshakes on the same stream. Best do not attempt to use the stream after 1956handshakes on the same stream. It is best to not attempt to use the
1801stopping TLS. 1957stream after stopping TLS.
1958
1959This method may invoke callbacks (and therefore the handle might be
1960destroyed after it returns).
1802 1961
1803=cut 1962=cut
1804 1963
1805our %TLS_CACHE; #TODO not yet documented, should we? 1964our %TLS_CACHE; #TODO not yet documented, should we?
1806 1965
1857 Net::SSLeay::CTX_set_mode ($tls, 1|2); 2016 Net::SSLeay::CTX_set_mode ($tls, 1|2);
1858 2017
1859 $self->{_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ()); 2018 $self->{_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
1860 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ()); 2019 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
1861 2020
1862 Net::SSLeay::BIO_write ($self->{_rbio}, delete $self->{rbuf}); 2021 Net::SSLeay::BIO_write ($self->{_rbio}, $self->{rbuf});
2022 $self->{rbuf} = "";
1863 2023
1864 Net::SSLeay::set_bio ($tls, $self->{_rbio}, $self->{_wbio}); 2024 Net::SSLeay::set_bio ($tls, $self->{_rbio}, $self->{_wbio});
1865 2025
1866 $self->{_on_starttls} = sub { $_[0]{on_starttls}(@_) } 2026 $self->{_on_starttls} = sub { $_[0]{on_starttls}(@_) }
1867 if $self->{on_starttls}; 2027 if $self->{on_starttls};
1872 2032
1873=item $handle->stoptls 2033=item $handle->stoptls
1874 2034
1875Shuts down the SSL connection - this makes a proper EOF handshake by 2035Shuts down the SSL connection - this makes a proper EOF handshake by
1876sending a close notify to the other side, but since OpenSSL doesn't 2036sending a close notify to the other side, but since OpenSSL doesn't
1877support non-blocking shut downs, it is not guarenteed that you can re-use 2037support non-blocking shut downs, it is not guaranteed that you can re-use
1878the stream afterwards. 2038the stream afterwards.
2039
2040This method may invoke callbacks (and therefore the handle might be
2041destroyed after it returns).
1879 2042
1880=cut 2043=cut
1881 2044
1882sub stoptls { 2045sub stoptls {
1883 my ($self) = @_; 2046 my ($self) = @_;
1884 2047
1885 if ($self->{tls}) { 2048 if ($self->{tls} && $self->{fh}) {
1886 Net::SSLeay::shutdown ($self->{tls}); 2049 Net::SSLeay::shutdown ($self->{tls});
1887 2050
1888 &_dotls; 2051 &_dotls;
1889 2052
1890# # we don't give a shit. no, we do, but we can't. no...#d# 2053# # we don't give a shit. no, we do, but we can't. no...#d#
1902 if $self->{tls} > 0; 2065 if $self->{tls} > 0;
1903 2066
1904 delete @$self{qw(_rbio _wbio _tls_wbuf _on_starttls)}; 2067 delete @$self{qw(_rbio _wbio _tls_wbuf _on_starttls)};
1905} 2068}
1906 2069
2070=item $handle->resettls
2071
2072This rarely-used method simply resets and TLS state on the handle, usually
2073causing data loss.
2074
2075One case where it may be useful is when you want to skip over the data in
2076the stream but you are not interested in interpreting it, so data loss is
2077no concern.
2078
2079=cut
2080
2081*resettls = \&_freetls;
2082
1907sub DESTROY { 2083sub DESTROY {
1908 my ($self) = @_; 2084 my ($self) = @_;
1909 2085
1910 &_freetls; 2086 &_freetls;
1911 2087
1920 push @linger, AE::io $fh, 1, sub { 2096 push @linger, AE::io $fh, 1, sub {
1921 my $len = syswrite $fh, $wbuf, length $wbuf; 2097 my $len = syswrite $fh, $wbuf, length $wbuf;
1922 2098
1923 if ($len > 0) { 2099 if ($len > 0) {
1924 substr $wbuf, 0, $len, ""; 2100 substr $wbuf, 0, $len, "";
1925 } else { 2101 } elsif (defined $len || ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK)) {
1926 @linger = (); # end 2102 @linger = (); # end
1927 } 2103 }
1928 }; 2104 };
1929 push @linger, AE::timer $linger, 0, sub { 2105 push @linger, AE::timer $linger, 0, sub {
1930 @linger = (); 2106 @linger = ();
1967 2143
1968sub AnyEvent::Handle::destroyed::AUTOLOAD { 2144sub AnyEvent::Handle::destroyed::AUTOLOAD {
1969 #nop 2145 #nop
1970} 2146}
1971 2147
2148=item $handle->destroyed
2149
2150Returns false as long as the handle hasn't been destroyed by a call to C<<
2151->destroy >>, true otherwise.
2152
2153Can be useful to decide whether the handle is still valid after some
2154callback possibly destroyed the handle. For example, C<< ->push_write >>,
2155C<< ->starttls >> and other methods can call user callbacks, which in turn
2156can destroy the handle, so work can be avoided by checking sometimes:
2157
2158 $hdl->starttls ("accept");
2159 return if $hdl->destroyed;
2160 $hdl->push_write (...
2161
2162Note that the call to C<push_write> will silently be ignored if the handle
2163has been destroyed, so often you can just ignore the possibility of the
2164handle being destroyed.
2165
2166=cut
2167
2168sub destroyed { 0 }
2169sub AnyEvent::Handle::destroyed::destroyed { 1 }
2170
1972=item AnyEvent::Handle::TLS_CTX 2171=item AnyEvent::Handle::TLS_CTX
1973 2172
1974This function creates and returns the AnyEvent::TLS object used by default 2173This function creates and returns the AnyEvent::TLS object used by default
1975for TLS mode. 2174for TLS mode.
1976 2175
2003 2202
2004It is only safe to "forget" the reference inside EOF or error callbacks, 2203It is only safe to "forget" the reference inside EOF or error callbacks,
2005from within all other callbacks, you need to explicitly call the C<< 2204from within all other callbacks, you need to explicitly call the C<<
2006->destroy >> method. 2205->destroy >> method.
2007 2206
2207=item Why is my C<on_eof> callback never called?
2208
2209Probably because your C<on_error> callback is being called instead: When
2210you have outstanding requests in your read queue, then an EOF is
2211considered an error as you clearly expected some data.
2212
2213To avoid this, make sure you have an empty read queue whenever your handle
2214is supposed to be "idle" (i.e. connection closes are O.K.). You can set
2215an C<on_read> handler that simply pushes the first read requests in the
2216queue.
2217
2218See also the next question, which explains this in a bit more detail.
2219
2220=item How can I serve requests in a loop?
2221
2222Most protocols consist of some setup phase (authentication for example)
2223followed by a request handling phase, where the server waits for requests
2224and handles them, in a loop.
2225
2226There are two important variants: The first (traditional, better) variant
2227handles requests until the server gets some QUIT command, causing it to
2228close the connection first (highly desirable for a busy TCP server). A
2229client dropping the connection is an error, which means this variant can
2230detect an unexpected detection close.
2231
2232To handle this case, always make sure you have a on-empty read queue, by
2233pushing the "read request start" handler on it:
2234
2235 # we assume a request starts with a single line
2236 my @start_request; @start_request = (line => sub {
2237 my ($hdl, $line) = @_;
2238
2239 ... handle request
2240
2241 # push next request read, possibly from a nested callback
2242 $hdl->push_read (@start_request);
2243 });
2244
2245 # auth done, now go into request handling loop
2246 # now push the first @start_request
2247 $hdl->push_read (@start_request);
2248
2249By always having an outstanding C<push_read>, the handle always expects
2250some data and raises the C<EPIPE> error when the connction is dropped
2251unexpectedly.
2252
2253The second variant is a protocol where the client can drop the connection
2254at any time. For TCP, this means that the server machine may run out of
2255sockets easier, and in general, it means you cannot distinguish a protocl
2256failure/client crash from a normal connection close. Nevertheless, these
2257kinds of protocols are common (and sometimes even the best solution to the
2258problem).
2259
2260Having an outstanding read request at all times is possible if you ignore
2261C<EPIPE> errors, but this doesn't help with when the client drops the
2262connection during a request, which would still be an error.
2263
2264A better solution is to push the initial request read in an C<on_read>
2265callback. This avoids an error, as when the server doesn't expect data
2266(i.e. is idly waiting for the next request, an EOF will not raise an
2267error, but simply result in an C<on_eof> callback. It is also a bit slower
2268and simpler:
2269
2270 # auth done, now go into request handling loop
2271 $hdl->on_read (sub {
2272 my ($hdl) = @_;
2273
2274 # called each time we receive data but the read queue is empty
2275 # simply start read the request
2276
2277 $hdl->push_read (line => sub {
2278 my ($hdl, $line) = @_;
2279
2280 ... handle request
2281
2282 # do nothing special when the request has been handled, just
2283 # let the request queue go empty.
2284 });
2285 });
2286
2008=item I get different callback invocations in TLS mode/Why can't I pause 2287=item I get different callback invocations in TLS mode/Why can't I pause
2009reading? 2288reading?
2010 2289
2011Unlike, say, TCP, TLS connections do not consist of two independent 2290Unlike, say, TCP, TLS connections do not consist of two independent
2012communication channels, one for each direction. Or put differently. The 2291communication channels, one for each direction. Or put differently, the
2013read and write directions are not independent of each other: you cannot 2292read and write directions are not independent of each other: you cannot
2014write data unless you are also prepared to read, and vice versa. 2293write data unless you are also prepared to read, and vice versa.
2015 2294
2016This can mean than, in TLS mode, you might get C<on_error> or C<on_eof> 2295This means that, in TLS mode, you might get C<on_error> or C<on_eof>
2017callback invocations when you are not expecting any read data - the reason 2296callback invocations when you are not expecting any read data - the reason
2018is that AnyEvent::Handle always reads in TLS mode. 2297is that AnyEvent::Handle always reads in TLS mode.
2019 2298
2020During the connection, you have to make sure that you always have a 2299During the connection, you have to make sure that you always have a
2021non-empty read-queue, or an C<on_read> watcher. At the end of the 2300non-empty read-queue, or an C<on_read> watcher. At the end of the
2033 $handle->on_eof (undef); 2312 $handle->on_eof (undef);
2034 $handle->on_error (sub { 2313 $handle->on_error (sub {
2035 my $data = delete $_[0]{rbuf}; 2314 my $data = delete $_[0]{rbuf};
2036 }); 2315 });
2037 2316
2317Note that this example removes the C<rbuf> member from the handle object,
2318which is not normally allowed by the API. It is expressly permitted in
2319this case only, as the handle object needs to be destroyed afterwards.
2320
2038The reason to use C<on_error> is that TCP connections, due to latencies 2321The reason to use C<on_error> is that TCP connections, due to latencies
2039and packets loss, might get closed quite violently with an error, when in 2322and packets loss, might get closed quite violently with an error, when in
2040fact, all data has been received. 2323fact all data has been received.
2041 2324
2042It is usually better to use acknowledgements when transferring data, 2325It is usually better to use acknowledgements when transferring data,
2043to make sure the other side hasn't just died and you got the data 2326to make sure the other side hasn't just died and you got the data
2044intact. This is also one reason why so many internet protocols have an 2327intact. This is also one reason why so many internet protocols have an
2045explicit QUIT command. 2328explicit QUIT command.
2052C<low_water_mark> this will be called precisely when all data has been 2335C<low_water_mark> this will be called precisely when all data has been
2053written to the socket: 2336written to the socket:
2054 2337
2055 $handle->push_write (...); 2338 $handle->push_write (...);
2056 $handle->on_drain (sub { 2339 $handle->on_drain (sub {
2057 warn "all data submitted to the kernel\n"; 2340 AE::log debug => "All data submitted to the kernel.";
2058 undef $handle; 2341 undef $handle;
2059 }); 2342 });
2060 2343
2061If you just want to queue some data and then signal EOF to the other side, 2344If you just want to queue some data and then signal EOF to the other side,
2062consider using C<< ->push_shutdown >> instead. 2345consider using C<< ->push_shutdown >> instead.
2063 2346
2064=item I want to contact a TLS/SSL server, I don't care about security. 2347=item I want to contact a TLS/SSL server, I don't care about security.
2065 2348
2066If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS, 2349If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS,
2067simply connect to it and then create the AnyEvent::Handle with the C<tls> 2350connect to it and then create the AnyEvent::Handle with the C<tls>
2068parameter: 2351parameter:
2069 2352
2070 tcp_connect $host, $port, sub { 2353 tcp_connect $host, $port, sub {
2071 my ($fh) = @_; 2354 my ($fh) = @_;
2072 2355
2146When you have intermediate CA certificates that your clients might not 2429When you have intermediate CA certificates that your clients might not
2147know about, just append them to the C<cert_file>. 2430know about, just append them to the C<cert_file>.
2148 2431
2149=back 2432=back
2150 2433
2151
2152=head1 SUBCLASSING AnyEvent::Handle 2434=head1 SUBCLASSING AnyEvent::Handle
2153 2435
2154In many cases, you might want to subclass AnyEvent::Handle. 2436In many cases, you might want to subclass AnyEvent::Handle.
2155 2437
2156To make this easier, a given version of AnyEvent::Handle uses these 2438To make this easier, a given version of AnyEvent::Handle uses these
2172 2454
2173=item * all members not documented here and not prefixed with an underscore 2455=item * all members not documented here and not prefixed with an underscore
2174are free to use in subclasses. 2456are free to use in subclasses.
2175 2457
2176Of course, new versions of AnyEvent::Handle may introduce more "public" 2458Of course, new versions of AnyEvent::Handle may introduce more "public"
2177member variables, but thats just life, at least it is documented. 2459member variables, but that's just life. At least it is documented.
2178 2460
2179=back 2461=back
2180 2462
2181=head1 AUTHOR 2463=head1 AUTHOR
2182 2464
2183Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>. 2465Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
2184 2466
2185=cut 2467=cut
2186 2468
21871; # End of AnyEvent::Handle 24691
2470

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines