1 | =head1 NAME |
1 | =head1 NAME |
2 | |
2 | |
3 | AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent |
3 | AnyEvent::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 | |
35 | This module is a helper module to make it easier to do event-based I/O on |
35 | This is a helper module to make it easier to do event-based I/O on |
36 | filehandles. |
36 | stream-based filehandles (sockets, pipes, and other stream things). |
37 | |
37 | |
38 | The L<AnyEvent::Intro> tutorial contains some well-documented |
38 | The L<AnyEvent::Intro> tutorial contains some well-documented |
39 | AnyEvent::Handle examples. |
39 | AnyEvent::Handle examples. |
40 | |
40 | |
41 | In the following, when the documentation refers to of "bytes" then this |
41 | In the following, where the documentation refers to "bytes", it means |
42 | means characters. As sysread and syswrite are used for all I/O, their |
42 | characters. As sysread and syswrite are used for all I/O, their |
43 | treatment of characters applies to this module as well. |
43 | treatment of characters applies to this module as well. |
44 | |
44 | |
45 | At the very minimum, you should specify C<fh> or C<connect>, and the |
45 | At the very minimum, you should specify C<fh> or C<connect>, and the |
46 | C<on_error> callback. |
46 | C<on_error> callback. |
47 | |
47 | |
… | |
… | |
60 | use AnyEvent (); BEGIN { AnyEvent::common_sense } |
60 | use AnyEvent (); BEGIN { AnyEvent::common_sense } |
61 | use AnyEvent::Util qw(WSAEWOULDBLOCK); |
61 | use AnyEvent::Util qw(WSAEWOULDBLOCK); |
62 | |
62 | |
63 | our $VERSION = $AnyEvent::VERSION; |
63 | our $VERSION = $AnyEvent::VERSION; |
64 | |
64 | |
|
|
65 | sub _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 | |
|
|
80 | sub 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 | |
71 | The constructor supports these arguments (all as C<< key => value >> pairs). |
88 | The 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 | |
101 | This (rarely used) callback is called before a new connection is |
118 | This (rarely used) callback is called before a new connection is |
102 | attempted, but after the file handle has been created. It could be used to |
119 | attempted, but after the file handle has been created (you can access that |
|
|
120 | file handle via C<< $handle->{fh} >>). It could be used to prepare the |
103 | prepare the file handle with parameters required for the actual connect |
121 | file 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 |
122 | settings that can be changed when the connection is already established). |
105 | established). |
|
|
106 | |
123 | |
107 | The return value of this callback should be the connect timeout value in |
124 | The return value of this callback should be the connect timeout value in |
108 | seconds (or C<0>, or C<undef>, or the empty list, to indicate the default |
125 | seconds (or C<0>, or C<undef>, or the empty list, to indicate that the |
109 | timeout is to be used). |
126 | default 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 | |
113 | This callback is called when a connection has been successfully established. |
130 | This callback is called when a connection has been successfully established. |
114 | |
131 | |
115 | The actual numeric host and port (the socket peername) are passed as |
132 | The peer's numeric host and port (the socket peername) are passed as |
116 | parameters, together with a retry callback. |
133 | parameters, together with a retry callback. At the time it is called the |
|
|
134 | read and write queues, EOF status, TLS status and similar properties of |
|
|
135 | the handle will have been reset. |
117 | |
136 | |
|
|
137 | It is not allowed to use the read or write queues while the handle object |
|
|
138 | is connecting. |
|
|
139 | |
118 | When, for some reason, the handle is not acceptable, then calling |
140 | If, for some reason, the handle is not acceptable, calling C<$retry> will |
119 | C<$retry> will continue with the next conenction target (in case of |
141 | continue with the next connection target (in case of multi-homed hosts or |
120 | multi-homed hosts or SRV records there can be multiple connection |
142 | SRV records there can be multiple connection endpoints). The C<$retry> |
121 | endpoints). When it is called then the read and write queues, eof status, |
143 | callback can be invoked after the connect callback returns, i.e. one can |
122 | tls status and similar properties of the handle are being reset. |
144 | start a handshake and then decide to retry with the next host if the |
|
|
145 | handshake fails. |
123 | |
146 | |
124 | In most cases, ignoring the C<$retry> parameter is the way to go. |
147 | In 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 | |
128 | This callback is called when the conenction could not be |
151 | This callback is called when the connection could not be |
129 | established. C<$!> will contain the relevant error code, and C<$message> a |
152 | established. C<$!> will contain the relevant error code, and C<$message> a |
130 | message describing it (usually the same as C<"$!">). |
153 | message describing it (usually the same as C<"$!">). |
131 | |
154 | |
132 | If this callback isn't specified, then C<on_error> will be called with a |
155 | If this callback isn't specified, then C<on_error> will be called with a |
133 | fatal error instead. |
156 | fatal error instead. |
… | |
… | |
136 | |
159 | |
137 | =item on_error => $cb->($handle, $fatal, $message) |
160 | =item on_error => $cb->($handle, $fatal, $message) |
138 | |
161 | |
139 | This is the error callback, which is called when, well, some error |
162 | This is the error callback, which is called when, well, some error |
140 | occured, such as not being able to resolve the hostname, failure to |
163 | occured, such as not being able to resolve the hostname, failure to |
141 | connect or a read error. |
164 | connect, or a read error. |
142 | |
165 | |
143 | Some errors are fatal (which is indicated by C<$fatal> being true). On |
166 | Some errors are fatal (which is indicated by C<$fatal> being true). On |
144 | fatal errors the handle object will be destroyed (by a call to C<< -> |
167 | fatal errors the handle object will be destroyed (by a call to C<< -> |
145 | destroy >>) after invoking the error callback (which means you are free to |
168 | destroy >>) after invoking the error callback (which means you are free to |
146 | examine the handle object). Examples of fatal errors are an EOF condition |
169 | examine the handle object). Examples of fatal errors are an EOF condition |
147 | with active (but unsatisifable) read watchers (C<EPIPE>) or I/O errors. In |
170 | with active (but unsatisfiable) read watchers (C<EPIPE>) or I/O errors. In |
148 | cases where the other side can close the connection at their will it is |
171 | cases where the other side can close the connection at will, it is |
149 | often easiest to not report C<EPIPE> errors in this callback. |
172 | often easiest to not report C<EPIPE> errors in this callback. |
150 | |
173 | |
151 | AnyEvent::Handle tries to find an appropriate error code for you to check |
174 | AnyEvent::Handle tries to find an appropriate error code for you to check |
152 | against, but in some cases (TLS errors), this does not work well. It is |
175 | against, but in some cases (TLS errors), this does not work well. It is |
153 | recommended to always output the C<$message> argument in human-readable |
176 | recommended to always output the C<$message> argument in human-readable |
154 | error messages (it's usually the same as C<"$!">). |
177 | error messages (it's usually the same as C<"$!">). |
155 | |
178 | |
156 | Non-fatal errors can be retried by simply returning, but it is recommended |
179 | Non-fatal errors can be retried by returning, but it is recommended |
157 | to simply ignore this parameter and instead abondon the handle object |
180 | to simply ignore this parameter and instead abondon the handle object |
158 | when this callback is invoked. Examples of non-fatal errors are timeouts |
181 | when this callback is invoked. Examples of non-fatal errors are timeouts |
159 | C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>). |
182 | C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>). |
160 | |
183 | |
161 | On callback entrance, the value of C<$!> contains the operating system |
184 | On entry to the callback, the value of C<$!> contains the operating |
162 | error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or |
185 | system error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or |
163 | C<EPROTO>). |
186 | C<EPROTO>). |
164 | |
187 | |
165 | While not mandatory, it is I<highly> recommended to set this callback, as |
188 | While not mandatory, it is I<highly> recommended to set this callback, as |
166 | you will not be notified of errors otherwise. The default simply calls |
189 | you will not be notified of errors otherwise. The default just calls |
167 | C<croak>. |
190 | C<croak>. |
168 | |
191 | |
169 | =item on_read => $cb->($handle) |
192 | =item on_read => $cb->($handle) |
170 | |
193 | |
171 | This sets the default read callback, which is called when data arrives |
194 | This sets the default read callback, which is called when data arrives |
… | |
… | |
176 | To access (and remove data from) the read buffer, use the C<< ->rbuf >> |
199 | To access (and remove data from) the read buffer, use the C<< ->rbuf >> |
177 | method or access the C<< $handle->{rbuf} >> member directly. Note that you |
200 | method or access the C<< $handle->{rbuf} >> member directly. Note that you |
178 | must not enlarge or modify the read buffer, you can only remove data at |
201 | must not enlarge or modify the read buffer, you can only remove data at |
179 | the beginning from it. |
202 | the beginning from it. |
180 | |
203 | |
|
|
204 | You can also call C<< ->push_read (...) >> or any other function that |
|
|
205 | modifies the read queue. Or do both. Or ... |
|
|
206 | |
181 | When an EOF condition is detected then AnyEvent::Handle will first try to |
207 | When an EOF condition is detected, AnyEvent::Handle will first try to |
182 | feed all the remaining data to the queued callbacks and C<on_read> before |
208 | feed all the remaining data to the queued callbacks and C<on_read> before |
183 | calling the C<on_eof> callback. If no progress can be made, then a fatal |
209 | calling the C<on_eof> callback. If no progress can be made, then a fatal |
184 | error will be raised (with C<$!> set to C<EPIPE>). |
210 | error will be raised (with C<$!> set to C<EPIPE>). |
185 | |
211 | |
186 | Note that, unlike requests in the read queue, an C<on_read> callback |
212 | Note that, unlike requests in the read queue, an C<on_read> callback |
… | |
… | |
204 | If an EOF condition has been detected but no C<on_eof> callback has been |
230 | If an EOF condition has been detected but no C<on_eof> callback has been |
205 | set, then a fatal error will be raised with C<$!> set to <0>. |
231 | set, 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 | |
209 | This sets the callback that is called when the write buffer becomes empty |
235 | This 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). |
236 | empty (and immediately when the handle object is created). |
211 | |
237 | |
212 | To append to the write buffer, use the C<< ->push_write >> method. |
238 | To append to the write buffer, use the C<< ->push_write >> method. |
213 | |
239 | |
214 | This callback is useful when you don't want to put all of your write data |
240 | This callback is useful when you don't want to put all of your write data |
215 | into the queue at once, for example, when you want to write the contents |
241 | into the queue at once, for example, when you want to write the contents |
… | |
… | |
227 | many seconds pass without a successful read or write on the underlying |
253 | many seconds pass without a successful read or write on the underlying |
228 | file handle (or a call to C<timeout_reset>), the C<on_timeout> callback |
254 | file handle (or a call to C<timeout_reset>), the C<on_timeout> callback |
229 | will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT> |
255 | will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT> |
230 | error will be raised). |
256 | error will be raised). |
231 | |
257 | |
232 | There are three variants of the timeouts that work fully independent |
258 | There are three variants of the timeouts that work independently of each |
233 | of each other, for both read and write, just read, and just write: |
259 | other, for both read and write (triggered when nothing was read I<OR> |
|
|
260 | written), just read (triggered when nothing was read), and just write: |
234 | C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks |
261 | C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks |
235 | C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions |
262 | C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions |
236 | C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>. |
263 | C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>. |
237 | |
264 | |
238 | Note that timeout processing is also active when you currently do not have |
265 | Note that timeout processing is active even when you do not have any |
239 | any outstanding read or write requests: If you plan to keep the connection |
266 | outstanding read or write requests: If you plan to keep the connection |
240 | idle then you should disable the timout temporarily or ignore the timeout |
267 | idle then you should disable the timeout temporarily or ignore the |
241 | in the C<on_timeout> callback, in which case AnyEvent::Handle will simply |
268 | timeout in the corresponding C<on_timeout> callback, in which case |
242 | restart the timeout. |
269 | AnyEvent::Handle will simply restart the timeout. |
243 | |
270 | |
244 | Zero (the default) disables this timeout. |
271 | Zero (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 | |
248 | Called whenever the inactivity timeout passes. If you return from this |
279 | Called whenever the inactivity timeout passes. If you return from this |
249 | callback, then the timeout will be reset as if some activity had happened, |
280 | callback, then the timeout will be reset as if some activity had happened, |
250 | so this condition is not fatal in any way. |
281 | so this condition is not fatal in any way. |
251 | |
282 | |
… | |
… | |
259 | be configured to accept only so-and-so much data that it cannot act on |
290 | be 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 |
261 | amount of data without a callback ever being called as long as the line |
292 | amount of data without a callback ever being called as long as the line |
262 | isn't finished). |
293 | isn't finished). |
263 | |
294 | |
|
|
295 | =item wbuf_max => <bytes> |
|
|
296 | |
|
|
297 | If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>) |
|
|
298 | when the write buffer ever (strictly) exceeds this size. This is useful to |
|
|
299 | avoid some forms of denial-of-service attacks. |
|
|
300 | |
|
|
301 | Although the units of this parameter is bytes, this is the I<raw> number |
|
|
302 | of bytes not yet accepted by the kernel. This can make a difference when |
|
|
303 | you e.g. use TLS, as TLS typically makes your write data larger (but it |
|
|
304 | can also make it smaller due to compression). |
|
|
305 | |
|
|
306 | As an example of when this limit is useful, take a chat server that sends |
|
|
307 | chat messages to a client. If the client does not read those in a timely |
|
|
308 | manner then the send buffer in the server would grow unbounded. |
|
|
309 | |
264 | =item autocork => <boolean> |
310 | =item autocork => <boolean> |
265 | |
311 | |
266 | When disabled (the default), then C<push_write> will try to immediately |
312 | When disabled (the default), C<push_write> will try to immediately |
267 | write the data to the handle, if possible. This avoids having to register |
313 | write the data to the handle if possible. This avoids having to register |
268 | a write watcher and wait for the next event loop iteration, but can |
314 | a write watcher and wait for the next event loop iteration, but can |
269 | be inefficient if you write multiple small chunks (on the wire, this |
315 | be inefficient if you write multiple small chunks (on the wire, this |
270 | disadvantage is usually avoided by your kernel's nagle algorithm, see |
316 | disadvantage is usually avoided by your kernel's nagle algorithm, see |
271 | C<no_delay>, but this option can save costly syscalls). |
317 | C<no_delay>, but this option can save costly syscalls). |
272 | |
318 | |
273 | When enabled, then writes will always be queued till the next event loop |
319 | When enabled, writes will always be queued till the next event loop |
274 | iteration. This is efficient when you do many small writes per iteration, |
320 | iteration. This is efficient when you do many small writes per iteration, |
275 | but less efficient when you do a single write only per iteration (or when |
321 | but less efficient when you do a single write only per iteration (or when |
276 | the write buffer often is full). It also increases write latency. |
322 | the write buffer often is full). It also increases write latency. |
277 | |
323 | |
278 | =item no_delay => <boolean> |
324 | =item no_delay => <boolean> |
… | |
… | |
282 | the Nagle algorithm, and usually it is beneficial. |
328 | the Nagle algorithm, and usually it is beneficial. |
283 | |
329 | |
284 | In some situations you want as low a delay as possible, which can be |
330 | In some situations you want as low a delay as possible, which can be |
285 | accomplishd by setting this option to a true value. |
331 | accomplishd by setting this option to a true value. |
286 | |
332 | |
287 | The default is your opertaing system's default behaviour (most likely |
333 | The default is your operating system's default behaviour (most likely |
288 | enabled), this option explicitly enables or disables it, if possible. |
334 | enabled). This option explicitly enables or disables it, if possible. |
289 | |
335 | |
290 | =item keepalive => <boolean> |
336 | =item keepalive => <boolean> |
291 | |
337 | |
292 | Enables (default disable) the SO_KEEPALIVE option on the stream socket: |
338 | Enables (default disable) the SO_KEEPALIVE option on the stream socket: |
293 | normally, TCP connections have no time-out once established, so TCP |
339 | normally, TCP connections have no time-out once established, so TCP |
294 | conenctions, once established, can stay alive forever even when the other |
340 | connections, once established, can stay alive forever even when the other |
295 | side has long gone. TCP keepalives are a cheap way to take down long-lived |
341 | side has long gone. TCP keepalives are a cheap way to take down long-lived |
296 | TCP connections whent he other side becomes unreachable. While the default |
342 | TCP connections when the other side becomes unreachable. While the default |
297 | is OS-dependent, TCP keepalives usually kick in after around two hours, |
343 | is OS-dependent, TCP keepalives usually kick in after around two hours, |
298 | and, if the other side doesn't reply, take down the TCP connection some 10 |
344 | and, if the other side doesn't reply, take down the TCP connection some 10 |
299 | to 15 minutes later. |
345 | to 15 minutes later. |
300 | |
346 | |
301 | It is harmless to specify this option for file handles that do not support |
347 | It is harmless to specify this option for file handles that do not support |
… | |
… | |
312 | is enabled) gives you the most portable way of getting urgent data, by |
358 | is enabled) gives you the most portable way of getting urgent data, by |
313 | putting it into the stream. |
359 | putting it into the stream. |
314 | |
360 | |
315 | Since BSD emulation of OOB data on top of TCP's urgent data can have |
361 | Since BSD emulation of OOB data on top of TCP's urgent data can have |
316 | security implications, AnyEvent::Handle sets this flag automatically |
362 | security implications, AnyEvent::Handle sets this flag automatically |
317 | unless explicitly specified. |
363 | unless explicitly specified. Note that setting this flag after |
|
|
364 | establishing a connection I<may> be a bit too late (data loss could |
|
|
365 | already have occured on BSD systems), but at least it will protect you |
|
|
366 | from most attacks. |
318 | |
367 | |
319 | =item read_size => <bytes> |
368 | =item read_size => <bytes> |
320 | |
369 | |
321 | The default read block size (the amount of bytes this module will |
370 | The initial read block size, the number of bytes this module will try |
322 | try to read during each loop iteration, which affects memory |
371 | to read during each loop iteration. Each handle object will consume |
323 | requirements). Default: C<8192>. |
372 | at least this amount of memory for the read buffer as well, so when |
|
|
373 | handling many connections watch out for memory requirements). See also |
|
|
374 | C<max_read_size>. Default: C<2048>. |
|
|
375 | |
|
|
376 | =item max_read_size => <bytes> |
|
|
377 | |
|
|
378 | The maximum read buffer size used by the dynamic adjustment |
|
|
379 | algorithm: Each time AnyEvent::Handle can read C<read_size> bytes in |
|
|
380 | one go it will double C<read_size> up to the maximum given by this |
|
|
381 | option. 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 | |
327 | Sets the amount of bytes (default: C<0>) that make up an "empty" write |
385 | Sets the number of bytes (default: C<0>) that make up an "empty" write |
328 | buffer: If the write reaches this size or gets even samller it is |
386 | buffer: If the buffer reaches this size or gets even samller it is |
329 | considered empty. |
387 | considered empty. |
330 | |
388 | |
331 | Sometimes it can be beneficial (for performance reasons) to add data to |
389 | Sometimes it can be beneficial (for performance reasons) to add data to |
332 | the write buffer before it is fully drained, but this is a rare case, as |
390 | the write buffer before it is fully drained, but this is a rare case, as |
333 | the operating system kernel usually buffers data as well, so the default |
391 | the operating system kernel usually buffers data as well, so the default |
334 | is good in almost all cases. |
392 | is good in almost all cases. |
335 | |
393 | |
336 | =item linger => <seconds> |
394 | =item linger => <seconds> |
337 | |
395 | |
338 | If non-zero (default: C<3600>), then the destructor of the |
396 | If this is non-zero (default: C<3600>), the destructor of the |
339 | AnyEvent::Handle object will check whether there is still outstanding |
397 | AnyEvent::Handle object will check whether there is still outstanding |
340 | write data and will install a watcher that will write this data to the |
398 | write data and will install a watcher that will write this data to the |
341 | socket. No errors will be reported (this mostly matches how the operating |
399 | socket. No errors will be reported (this mostly matches how the operating |
342 | system treats outstanding data at socket close time). |
400 | system treats outstanding data at socket close time). |
343 | |
401 | |
… | |
… | |
350 | A string used to identify the remote site - usually the DNS hostname |
408 | A 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 | |
353 | Apart from being useful in error messages, this string is also used in TLS |
411 | Apart from being useful in error messages, this string is also used in TLS |
354 | peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This |
412 | peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This |
355 | verification will be skipped when C<peername> is not specified or |
413 | verification will be skipped when C<peername> is not specified or is |
356 | C<undef>. |
414 | C<undef>. |
357 | |
415 | |
358 | =item tls => "accept" | "connect" | Net::SSLeay::SSL object |
416 | =item tls => "accept" | "connect" | Net::SSLeay::SSL object |
359 | |
417 | |
360 | When this parameter is given, it enables TLS (SSL) mode, that means |
418 | When this parameter is given, it enables TLS (SSL) mode, that means |
361 | AnyEvent will start a TLS handshake as soon as the conenction has been |
419 | AnyEvent will start a TLS handshake as soon as the connection has been |
362 | established and will transparently encrypt/decrypt data afterwards. |
420 | established and will transparently encrypt/decrypt data afterwards. |
363 | |
421 | |
364 | All TLS protocol errors will be signalled as C<EPROTO>, with an |
422 | All TLS protocol errors will be signalled as C<EPROTO>, with an |
365 | appropriate error message. |
423 | appropriate error message. |
366 | |
424 | |
… | |
… | |
386 | B<IMPORTANT:> since Net::SSLeay "objects" are really only integers, |
444 | B<IMPORTANT:> since Net::SSLeay "objects" are really only integers, |
387 | passing in the wrong integer will lead to certain crash. This most often |
445 | passing in the wrong integer will lead to certain crash. This most often |
388 | happens when one uses a stylish C<< tls => 1 >> and is surprised about the |
446 | happens when one uses a stylish C<< tls => 1 >> and is surprised about the |
389 | segmentation fault. |
447 | segmentation fault. |
390 | |
448 | |
391 | See the C<< ->starttls >> method for when need to start TLS negotiation later. |
449 | Use 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 | |
395 | Use the given C<AnyEvent::TLS> object to create the new TLS connection |
453 | Use 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 |
397 | missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>. |
455 | parameter is missing (or C<undef>), then AnyEvent::Handle will use |
|
|
456 | C<AnyEvent::Handle::TLS_CTX>. |
398 | |
457 | |
399 | Instead of an object, you can also specify a hash reference with C<< key |
458 | Instead 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 |
401 | new TLS context object. |
460 | new TLS context object. |
402 | |
461 | |
… | |
… | |
411 | |
470 | |
412 | TLS handshake failures will not cause C<on_error> to be invoked when this |
471 | TLS handshake failures will not cause C<on_error> to be invoked when this |
413 | callback is in effect, instead, the error message will be passed to C<on_starttls>. |
472 | callback is in effect, instead, the error message will be passed to C<on_starttls>. |
414 | |
473 | |
415 | Without this callback, handshake failures lead to C<on_error> being |
474 | Without this callback, handshake failures lead to C<on_error> being |
416 | called, as normal. |
475 | called as usual. |
417 | |
476 | |
418 | Note that you cannot call C<starttls> right again in this callback. If you |
477 | Note that you cannot just call C<starttls> again in this callback. If you |
419 | need to do that, start an zero-second timer instead whose callback can |
478 | need to do that, start an zero-second timer instead whose callback can |
420 | then call C<< ->starttls >> again. |
479 | then 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 | |
515 | sub _start { |
576 | sub _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 | |
619 | sub no_delay { |
690 | sub 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 | |
631 | Enables or disables the C<keepalive> setting (see constructor argument of |
699 | Enables or disables the C<keepalive> setting (see constructor argument of |
… | |
… | |
691 | |
759 | |
692 | Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument). |
760 | Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument). |
693 | |
761 | |
694 | =cut |
762 | =cut |
695 | |
763 | |
696 | sub on_starttls { |
764 | sub 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 | |
702 | Configures the C<rbuf_max> setting (C<undef> disables it). |
770 | Configures the C<rbuf_max> setting (C<undef> disables it). |
|
|
771 | |
|
|
772 | =item $handle->wbuf_max ($max_octets) |
|
|
773 | |
|
|
774 | Configures the C<wbuf_max> setting (C<undef> disables it). |
703 | |
775 | |
704 | =cut |
776 | =cut |
705 | |
777 | |
706 | sub rbuf_max { |
778 | sub rbuf_max { |
707 | $_[0]{rbuf_max} = $_[1]; |
779 | $_[0]{rbuf_max} = $_[1]; |
708 | } |
780 | } |
709 | |
781 | |
|
|
782 | sub 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 | |
718 | Configures (or disables) the inactivity timeout. |
794 | Configures (or disables) the inactivity timeout. |
|
|
795 | |
|
|
796 | The timeout will be checked instantly, so this method might destroy the |
|
|
797 | handle 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 | |
805 | The write queue is very simple: you can add data to its end, and |
887 | The write queue is very simple: you can add data to its end, and |
806 | AnyEvent::Handle will automatically try to get rid of it for you. |
888 | AnyEvent::Handle will automatically try to get rid of it for you. |
807 | |
889 | |
808 | When data could be written and the write buffer is shorter then the low |
890 | When data could be written and the write buffer is shorter then the low |
809 | water mark, the C<on_drain> callback will be invoked. |
891 | water 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 | |
815 | Sets the C<on_drain> callback or clears it (see the description of |
897 | Sets the C<on_drain> callback or clears it (see the description of |
816 | C<on_drain> in the constructor). |
898 | C<on_drain> in the constructor). |
817 | |
899 | |
|
|
900 | This method may invoke callbacks (and therefore the handle might be |
|
|
901 | destroyed after it returns). |
|
|
902 | |
818 | =cut |
903 | =cut |
819 | |
904 | |
820 | sub on_drain { |
905 | sub 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 | |
831 | Queues the given scalar to be written. You can push as much data as you |
916 | Queues the given scalar to be written. You can push as much data as |
832 | want (only limited by the available memory), as C<AnyEvent::Handle> |
917 | you want (only limited by the available memory and C<wbuf_max>), as |
833 | buffers it independently of the kernel. |
918 | C<AnyEvent::Handle> buffers it independently of the kernel. |
|
|
919 | |
|
|
920 | This method may invoke callbacks (and therefore the handle might be |
|
|
921 | destroyed after it returns). |
834 | |
922 | |
835 | =cut |
923 | =cut |
836 | |
924 | |
837 | sub _drain_wbuf { |
925 | sub _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 | |
871 | our %WH; |
966 | our %WH; |
872 | |
967 | |
|
|
968 | # deprecated |
873 | sub register_write_type($$) { |
969 | sub register_write_type($$) { |
874 | $WH{$_[0]} = $_[1]; |
970 | $WH{$_[0]} = $_[1]; |
875 | } |
971 | } |
876 | |
972 | |
877 | sub push_write { |
973 | sub 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 | |
898 | Instead of formatting your data yourself, you can also let this module do |
998 | Instead of formatting your data yourself, you can also let this module |
899 | the job by specifying a type and type-specific arguments. |
999 | do the job by specifying a type and type-specific arguments. You |
|
|
1000 | can also specify the (fully qualified) name of a package, in which |
|
|
1001 | case AnyEvent tries to load the package and then expects to find the |
|
|
1002 | C<anyevent_write_type> function inside (see "custom write types", below). |
900 | |
1003 | |
901 | Predefined types are (if you have ideas for additional types, feel free to |
1004 | Predefined types are (if you have ideas for additional types, feel free to |
902 | drop by and tell us): |
1005 | drop by and tell us): |
903 | |
1006 | |
904 | =over 4 |
1007 | =over 4 |
… | |
… | |
984 | =cut |
1087 | =cut |
985 | |
1088 | |
986 | register_write_type storable => sub { |
1089 | register_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 |
… | |
… | |
999 | before it was actually written. One way to do that is to replace your |
1102 | before it was actually written. One way to do that is to replace your |
1000 | C<on_drain> handler by a callback that shuts down the socket (and set |
1103 | C<on_drain> handler by a callback that shuts down the socket (and set |
1001 | C<low_water_mark> to C<0>). This method is a shorthand for just that, and |
1104 | C<low_water_mark> to C<0>). This method is a shorthand for just that, and |
1002 | replaces the C<on_drain> callback with: |
1105 | replaces 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 | |
1006 | This simply shuts down the write side and signals an EOF condition to the |
1109 | This simply shuts down the write side and signals an EOF condition to the |
1007 | the peer. |
1110 | the peer. |
1008 | |
1111 | |
1009 | You can rely on the normal read queue and C<on_eof> handling |
1112 | You can rely on the normal read queue and C<on_eof> handling |
1010 | afterwards. This is the cleanest way to close a connection. |
1113 | afterwards. This is the cleanest way to close a connection. |
1011 | |
1114 | |
|
|
1115 | This method may invoke callbacks (and therefore the handle might be |
|
|
1116 | destroyed after it returns). |
|
|
1117 | |
1012 | =cut |
1118 | =cut |
1013 | |
1119 | |
1014 | sub push_shutdown { |
1120 | sub 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 | |
1023 | This function (not method) lets you add your own types to C<push_write>. |
1129 | Instead of one of the predefined types, you can also specify the name of |
|
|
1130 | a package. AnyEvent will try to load the package and then expects to find |
|
|
1131 | a function named C<anyevent_write_type> inside. If it isn't found, it |
|
|
1132 | progressively tries to load the parent package until it either finds the |
|
|
1133 | function (good) or runs out of packages (bad). |
|
|
1134 | |
1024 | Whenever the given C<type> is used, C<push_write> will invoke the code |
1135 | Whenever the given C<type> is used, C<push_write> will the function with |
1025 | reference with the handle object and the remaining arguments. |
1136 | the handle object and the remaining arguments. |
1026 | |
1137 | |
1027 | The code reference is supposed to return a single octet string that will |
1138 | The function is supposed to return a single octet string that will be |
1028 | be appended to the write buffer. |
1139 | appended to the write buffer, so you can mentally treat this function as a |
|
|
1140 | "arguments to on-the-wire-format" converter. |
1029 | |
1141 | |
1030 | Note that this is a function, and all types registered this way will be |
1142 | Example: implement a custom write type C<join> that joins the remaining |
1031 | global, so try to use unique names. |
1143 | arguments 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 | |
… | |
… | |
1045 | ways, the "simple" way, using only C<on_read> and the "complex" way, using |
1171 | ways, the "simple" way, using only C<on_read> and the "complex" way, using |
1046 | a queue. |
1172 | a queue. |
1047 | |
1173 | |
1048 | In the simple case, you just install an C<on_read> callback and whenever |
1174 | In the simple case, you just install an C<on_read> callback and whenever |
1049 | new data arrives, it will be called. You can then remove some data (if |
1175 | new data arrives, it will be called. You can then remove some data (if |
1050 | enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna |
1176 | enough is there) from the read buffer (C<< $handle->rbuf >>). Or you can |
1051 | leave the data there if you want to accumulate more (e.g. when only a |
1177 | leave the data there if you want to accumulate more (e.g. when only a |
1052 | partial message has been received so far). |
1178 | partial message has been received so far), or change the read queue with |
|
|
1179 | e.g. C<push_read>. |
1053 | |
1180 | |
1054 | In the more complex case, you want to queue multiple callbacks. In this |
1181 | In the more complex case, you want to queue multiple callbacks. In this |
1055 | case, AnyEvent::Handle will call the first queued callback each time new |
1182 | case, AnyEvent::Handle will call the first queued callback each time new |
1056 | data arrives (also the first time it is queued) and removes it when it has |
1183 | data arrives (also the first time it is queued) and remove it when it has |
1057 | done its job (see C<push_read>, below). |
1184 | done its job (see C<push_read>, below). |
1058 | |
1185 | |
1059 | This way you can, for example, push three line-reads, followed by reading |
1186 | This way you can, for example, push three line-reads, followed by reading |
1060 | a chunk of data, and AnyEvent::Handle will execute them in order. |
1187 | a chunk of data, and AnyEvent::Handle will execute them in order. |
1061 | |
1188 | |
… | |
… | |
1192 | |
1319 | |
1193 | This replaces the currently set C<on_read> callback, or clears it (when |
1320 | This replaces the currently set C<on_read> callback, or clears it (when |
1194 | the new callback is C<undef>). See the description of C<on_read> in the |
1321 | the new callback is C<undef>). See the description of C<on_read> in the |
1195 | constructor. |
1322 | constructor. |
1196 | |
1323 | |
|
|
1324 | This method may invoke callbacks (and therefore the handle might be |
|
|
1325 | destroyed after it returns). |
|
|
1326 | |
1197 | =cut |
1327 | =cut |
1198 | |
1328 | |
1199 | sub on_read { |
1329 | sub 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 | |
1208 | Returns the read buffer (as a modifiable lvalue). |
1338 | Returns the read buffer (as a modifiable lvalue). You can also access the |
|
|
1339 | read buffer directly as the C<< ->{rbuf} >> member, if you want (this is |
|
|
1340 | much faster, and no less clean). |
1209 | |
1341 | |
1210 | You can access the read buffer directly as the C<< ->{rbuf} >> |
1342 | The only operation allowed on the read buffer (apart from looking at it) |
1211 | member, if you want. However, the only operation allowed on the |
1343 | is removing data from its beginning. Otherwise modifying or appending to |
1212 | read buffer (apart from looking at it) is removing data from its |
1344 | it is not allowed and will lead to hard-to-track-down bugs. |
1213 | beginning. Otherwise modifying or appending to it is not allowed and will |
|
|
1214 | lead to hard-to-track-down bugs. |
|
|
1215 | |
1345 | |
1216 | NOTE: The read buffer should only be used or modified if the C<on_read>, |
1346 | NOTE: The read buffer should only be used or modified in the C<on_read> |
1217 | C<push_read> or C<unshift_read> methods are used. The other read methods |
1347 | callback or when C<push_read> or C<unshift_read> are used with a single |
1218 | automatically manage the read buffer. |
1348 | callback (i.e. untyped). Typed C<push_read> and C<unshift_read> methods |
|
|
1349 | will manage the read buffer on their own. |
1219 | |
1350 | |
1220 | =cut |
1351 | =cut |
1221 | |
1352 | |
1222 | sub rbuf : lvalue { |
1353 | sub rbuf : lvalue { |
1223 | $_[0]{rbuf} |
1354 | $_[0]{rbuf} |
… | |
… | |
1240 | |
1371 | |
1241 | If enough data was available, then the callback must remove all data it is |
1372 | If enough data was available, then the callback must remove all data it is |
1242 | interested in (which can be none at all) and return a true value. After returning |
1373 | interested in (which can be none at all) and return a true value. After returning |
1243 | true, it will be removed from the queue. |
1374 | true, it will be removed from the queue. |
1244 | |
1375 | |
|
|
1376 | These methods may invoke callbacks (and therefore the handle might be |
|
|
1377 | destroyed after it returns). |
|
|
1378 | |
1245 | =cut |
1379 | =cut |
1246 | |
1380 | |
1247 | our %RH; |
1381 | our %RH; |
1248 | |
1382 | |
1249 | sub register_read_type($$) { |
1383 | sub 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 | |
1287 | Instead of providing a callback that parses the data itself you can chose |
1423 | Instead of providing a callback that parses the data itself you can chose |
1288 | between a number of predefined parsing formats, for chunks of data, lines |
1424 | between a number of predefined parsing formats, for chunks of data, lines |
1289 | etc. |
1425 | etc. You can also specify the (fully qualified) name of a package, in |
|
|
1426 | which case AnyEvent tries to load the package and then expects to find the |
|
|
1427 | C<anyevent_read_type> function inside (see "custom read types", below). |
1290 | |
1428 | |
1291 | Predefined types are (if you have ideas for additional types, feel free to |
1429 | Predefined types are (if you have ideas for additional types, feel free to |
1292 | drop by and tell us): |
1430 | drop by and tell us): |
1293 | |
1431 | |
1294 | =over 4 |
1432 | =over 4 |
… | |
… | |
1300 | data. |
1438 | data. |
1301 | |
1439 | |
1302 | Example: read 2 bytes. |
1440 | Example: 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 | |
1310 | register_read_type chunk => sub { |
1448 | register_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 | |
… | |
… | |
1386 | the receive buffer when neither C<$accept> nor C<$reject> match, |
1524 | the receive buffer when neither C<$accept> nor C<$reject> match, |
1387 | and everything preceding and including the match will be accepted |
1525 | and everything preceding and including the match will be accepted |
1388 | unconditionally. This is useful to skip large amounts of data that you |
1526 | unconditionally. This is useful to skip large amounts of data that you |
1389 | know cannot be matched, so that the C<$accept> or C<$reject> regex do not |
1527 | know cannot be matched, so that the C<$accept> or C<$reject> regex do not |
1390 | have to start matching from the beginning. This is purely an optimisation |
1528 | have to start matching from the beginning. This is purely an optimisation |
1391 | and is usually worth only when you expect more than a few kilobytes. |
1529 | and is usually worth it only when you expect more than a few kilobytes. |
1392 | |
1530 | |
1393 | Example: expect a http header, which ends at C<\015\012\015\012>. Since we |
1531 | Example: expect a http header, which ends at C<\015\012\015\012>. Since we |
1394 | expect the header to be very large (it isn't in practise, but...), we use |
1532 | expect the header to be very large (it isn't in practice, but...), we use |
1395 | a skip regex to skip initial portions. The skip regex is tricky in that |
1533 | a skip regex to skip initial portions. The skip regex is tricky in that |
1396 | it only accepts something not ending in either \015 or \012, as these are |
1534 | it only accepts something not ending in either \015 or \012, as these are |
1397 | required for the accept regex. |
1535 | required 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 | |
1581 | register_read_type storable => sub { |
1719 | register_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 | |
1620 | This function (not method) lets you add your own types to C<push_read>. |
1757 | Instead of one of the predefined types, you can also specify the name |
|
|
1758 | of a package. AnyEvent will try to load the package and then expects to |
|
|
1759 | find a function named C<anyevent_read_type> inside. If it isn't found, it |
|
|
1760 | progressively tries to load the parent package until it either finds the |
|
|
1761 | function (good) or runs out of packages (bad). |
1621 | |
1762 | |
1622 | Whenever the given C<type> is used, C<push_read> will invoke the code |
1763 | Whenever this type is used, C<push_read> will invoke the function with the |
1623 | reference with the handle object, the callback and the remaining |
1764 | handle object, the original callback and the remaining arguments. |
1624 | arguments. |
|
|
1625 | |
1765 | |
1626 | The code reference is supposed to return a callback (usually a closure) |
1766 | The function is supposed to return a callback (usually a closure) that |
1627 | that works as a plain read callback (see C<< ->push_read ($cb) >>). |
1767 | works as a plain read callback (see C<< ->push_read ($cb) >>), so you can |
|
|
1768 | mentally treat the function as a "configurable read type to read callback" |
|
|
1769 | converter. |
1628 | |
1770 | |
1629 | It should invoke the passed callback when it is done reading (remember to |
1771 | It should invoke the original callback when it is done reading (remember |
1630 | pass C<$handle> as first argument as all other callbacks do that). |
1772 | to pass C<$handle> as first argument as all other callbacks do that, |
|
|
1773 | although there is no strict requirement on this). |
1631 | |
1774 | |
1632 | Note that this is a function, and all types registered this way will be |
|
|
1633 | global, so try to use unique names. |
|
|
1634 | |
|
|
1635 | For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, |
1775 | For examples, see the source of this module (F<perldoc -m |
1636 | search for C<register_read_type>)). |
1776 | AnyEvent::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 | |
… | |
… | |
1647 | Note that AnyEvent::Handle will automatically C<start_read> for you when |
1787 | Note that AnyEvent::Handle will automatically C<start_read> for you when |
1648 | you change the C<on_read> callback or push/unshift a read callback, and it |
1788 | you change the C<on_read> callback or push/unshift a read callback, and it |
1649 | will automatically C<stop_read> for you when neither C<on_read> is set nor |
1789 | will automatically C<stop_read> for you when neither C<on_read> is set nor |
1650 | there are any read requests in the queue. |
1790 | there are any read requests in the queue. |
1651 | |
1791 | |
1652 | These methods will have no effect when in TLS mode (as TLS doesn't support |
1792 | In older versions of this module (<= 5.3), these methods had no effect, |
1653 | half-duplex connections). |
1793 | as TLS does not support half-duplex connections. In current versions they |
|
|
1794 | work as expected, as this behaviour is required to avoid certain resource |
|
|
1795 | attacks, where the program would be forced to read (and buffer) arbitrary |
|
|
1796 | amounts of data before being able to send some data. The drawback is that |
|
|
1797 | some readings of the the SSL/TLS specifications basically require this |
|
|
1798 | attack to be working, as SSL/TLS implementations might stall sending data |
|
|
1799 | during a rehandshake. |
|
|
1800 | |
|
|
1801 | As a guideline, during the initial handshake, you should not stop reading, |
|
|
1802 | and as a client, it might cause problems, depending on your application. |
1654 | |
1803 | |
1655 | =cut |
1804 | =cut |
1656 | |
1805 | |
1657 | sub stop_read { |
1806 | sub 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 | |
1663 | sub start_read { |
1812 | sub 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"); |
… | |
… | |
1795 | context in C<< $handle->{tls_ctx} >> after this call and can be used or |
1951 | context in C<< $handle->{tls_ctx} >> after this call and can be used or |
1796 | changed to your liking. Note that the handshake might have already started |
1952 | changed to your liking. Note that the handshake might have already started |
1797 | when this function returns. |
1953 | when this function returns. |
1798 | |
1954 | |
1799 | Due to bugs in OpenSSL, it might or might not be possible to do multiple |
1955 | Due to bugs in OpenSSL, it might or might not be possible to do multiple |
1800 | handshakes on the same stream. Best do not attempt to use the stream after |
1956 | handshakes on the same stream. It is best to not attempt to use the |
1801 | stopping TLS. |
1957 | stream after stopping TLS. |
|
|
1958 | |
|
|
1959 | This method may invoke callbacks (and therefore the handle might be |
|
|
1960 | destroyed after it returns). |
1802 | |
1961 | |
1803 | =cut |
1962 | =cut |
1804 | |
1963 | |
1805 | our %TLS_CACHE; #TODO not yet documented, should we? |
1964 | our %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 | |
1875 | Shuts down the SSL connection - this makes a proper EOF handshake by |
2035 | Shuts down the SSL connection - this makes a proper EOF handshake by |
1876 | sending a close notify to the other side, but since OpenSSL doesn't |
2036 | sending a close notify to the other side, but since OpenSSL doesn't |
1877 | support non-blocking shut downs, it is not guarenteed that you can re-use |
2037 | support non-blocking shut downs, it is not guaranteed that you can re-use |
1878 | the stream afterwards. |
2038 | the stream afterwards. |
|
|
2039 | |
|
|
2040 | This method may invoke callbacks (and therefore the handle might be |
|
|
2041 | destroyed after it returns). |
1879 | |
2042 | |
1880 | =cut |
2043 | =cut |
1881 | |
2044 | |
1882 | sub stoptls { |
2045 | sub 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 | |
|
|
2072 | This rarely-used method simply resets and TLS state on the handle, usually |
|
|
2073 | causing data loss. |
|
|
2074 | |
|
|
2075 | One case where it may be useful is when you want to skip over the data in |
|
|
2076 | the stream but you are not interested in interpreting it, so data loss is |
|
|
2077 | no concern. |
|
|
2078 | |
|
|
2079 | =cut |
|
|
2080 | |
|
|
2081 | *resettls = \&_freetls; |
|
|
2082 | |
1907 | sub DESTROY { |
2083 | sub 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 | |
1968 | sub AnyEvent::Handle::destroyed::AUTOLOAD { |
2144 | sub AnyEvent::Handle::destroyed::AUTOLOAD { |
1969 | #nop |
2145 | #nop |
1970 | } |
2146 | } |
1971 | |
2147 | |
|
|
2148 | =item $handle->destroyed |
|
|
2149 | |
|
|
2150 | Returns false as long as the handle hasn't been destroyed by a call to C<< |
|
|
2151 | ->destroy >>, true otherwise. |
|
|
2152 | |
|
|
2153 | Can be useful to decide whether the handle is still valid after some |
|
|
2154 | callback possibly destroyed the handle. For example, C<< ->push_write >>, |
|
|
2155 | C<< ->starttls >> and other methods can call user callbacks, which in turn |
|
|
2156 | can 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 | |
|
|
2162 | Note that the call to C<push_write> will silently be ignored if the handle |
|
|
2163 | has been destroyed, so often you can just ignore the possibility of the |
|
|
2164 | handle being destroyed. |
|
|
2165 | |
|
|
2166 | =cut |
|
|
2167 | |
|
|
2168 | sub destroyed { 0 } |
|
|
2169 | sub AnyEvent::Handle::destroyed::destroyed { 1 } |
|
|
2170 | |
1972 | =item AnyEvent::Handle::TLS_CTX |
2171 | =item AnyEvent::Handle::TLS_CTX |
1973 | |
2172 | |
1974 | This function creates and returns the AnyEvent::TLS object used by default |
2173 | This function creates and returns the AnyEvent::TLS object used by default |
1975 | for TLS mode. |
2174 | for TLS mode. |
1976 | |
2175 | |
… | |
… | |
2003 | |
2202 | |
2004 | It is only safe to "forget" the reference inside EOF or error callbacks, |
2203 | It is only safe to "forget" the reference inside EOF or error callbacks, |
2005 | from within all other callbacks, you need to explicitly call the C<< |
2204 | from 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 | |
|
|
2209 | Probably because your C<on_error> callback is being called instead: When |
|
|
2210 | you have outstanding requests in your read queue, then an EOF is |
|
|
2211 | considered an error as you clearly expected some data. |
|
|
2212 | |
|
|
2213 | To avoid this, make sure you have an empty read queue whenever your handle |
|
|
2214 | is supposed to be "idle" (i.e. connection closes are O.K.). You can set |
|
|
2215 | an C<on_read> handler that simply pushes the first read requests in the |
|
|
2216 | queue. |
|
|
2217 | |
|
|
2218 | See also the next question, which explains this in a bit more detail. |
|
|
2219 | |
|
|
2220 | =item How can I serve requests in a loop? |
|
|
2221 | |
|
|
2222 | Most protocols consist of some setup phase (authentication for example) |
|
|
2223 | followed by a request handling phase, where the server waits for requests |
|
|
2224 | and handles them, in a loop. |
|
|
2225 | |
|
|
2226 | There are two important variants: The first (traditional, better) variant |
|
|
2227 | handles requests until the server gets some QUIT command, causing it to |
|
|
2228 | close the connection first (highly desirable for a busy TCP server). A |
|
|
2229 | client dropping the connection is an error, which means this variant can |
|
|
2230 | detect an unexpected detection close. |
|
|
2231 | |
|
|
2232 | To handle this case, always make sure you have a on-empty read queue, by |
|
|
2233 | pushing 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 | |
|
|
2249 | By always having an outstanding C<push_read>, the handle always expects |
|
|
2250 | some data and raises the C<EPIPE> error when the connction is dropped |
|
|
2251 | unexpectedly. |
|
|
2252 | |
|
|
2253 | The second variant is a protocol where the client can drop the connection |
|
|
2254 | at any time. For TCP, this means that the server machine may run out of |
|
|
2255 | sockets easier, and in general, it means you cannot distinguish a protocl |
|
|
2256 | failure/client crash from a normal connection close. Nevertheless, these |
|
|
2257 | kinds of protocols are common (and sometimes even the best solution to the |
|
|
2258 | problem). |
|
|
2259 | |
|
|
2260 | Having an outstanding read request at all times is possible if you ignore |
|
|
2261 | C<EPIPE> errors, but this doesn't help with when the client drops the |
|
|
2262 | connection during a request, which would still be an error. |
|
|
2263 | |
|
|
2264 | A better solution is to push the initial request read in an C<on_read> |
|
|
2265 | callback. 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 |
|
|
2267 | error, but simply result in an C<on_eof> callback. It is also a bit slower |
|
|
2268 | and 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 |
2009 | reading? |
2288 | reading? |
2010 | |
2289 | |
2011 | Unlike, say, TCP, TLS connections do not consist of two independent |
2290 | Unlike, say, TCP, TLS connections do not consist of two independent |
2012 | communication channels, one for each direction. Or put differently. The |
2291 | communication channels, one for each direction. Or put differently, the |
2013 | read and write directions are not independent of each other: you cannot |
2292 | read and write directions are not independent of each other: you cannot |
2014 | write data unless you are also prepared to read, and vice versa. |
2293 | write data unless you are also prepared to read, and vice versa. |
2015 | |
2294 | |
2016 | This can mean than, in TLS mode, you might get C<on_error> or C<on_eof> |
2295 | This means that, in TLS mode, you might get C<on_error> or C<on_eof> |
2017 | callback invocations when you are not expecting any read data - the reason |
2296 | callback invocations when you are not expecting any read data - the reason |
2018 | is that AnyEvent::Handle always reads in TLS mode. |
2297 | is that AnyEvent::Handle always reads in TLS mode. |
2019 | |
2298 | |
2020 | During the connection, you have to make sure that you always have a |
2299 | During the connection, you have to make sure that you always have a |
2021 | non-empty read-queue, or an C<on_read> watcher. At the end of the |
2300 | non-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 | |
|
|
2317 | Note that this example removes the C<rbuf> member from the handle object, |
|
|
2318 | which is not normally allowed by the API. It is expressly permitted in |
|
|
2319 | this case only, as the handle object needs to be destroyed afterwards. |
|
|
2320 | |
2038 | The reason to use C<on_error> is that TCP connections, due to latencies |
2321 | The reason to use C<on_error> is that TCP connections, due to latencies |
2039 | and packets loss, might get closed quite violently with an error, when in |
2322 | and packets loss, might get closed quite violently with an error, when in |
2040 | fact, all data has been received. |
2323 | fact all data has been received. |
2041 | |
2324 | |
2042 | It is usually better to use acknowledgements when transferring data, |
2325 | It is usually better to use acknowledgements when transferring data, |
2043 | to make sure the other side hasn't just died and you got the data |
2326 | to make sure the other side hasn't just died and you got the data |
2044 | intact. This is also one reason why so many internet protocols have an |
2327 | intact. This is also one reason why so many internet protocols have an |
2045 | explicit QUIT command. |
2328 | explicit QUIT command. |
… | |
… | |
2052 | C<low_water_mark> this will be called precisely when all data has been |
2335 | C<low_water_mark> this will be called precisely when all data has been |
2053 | written to the socket: |
2336 | written 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 | |
2061 | If you just want to queue some data and then signal EOF to the other side, |
2344 | If you just want to queue some data and then signal EOF to the other side, |
2062 | consider using C<< ->push_shutdown >> instead. |
2345 | consider 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 | |
2066 | If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS, |
2349 | If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS, |
2067 | simply connect to it and then create the AnyEvent::Handle with the C<tls> |
2350 | connect to it and then create the AnyEvent::Handle with the C<tls> |
2068 | parameter: |
2351 | parameter: |
2069 | |
2352 | |
2070 | tcp_connect $host, $port, sub { |
2353 | tcp_connect $host, $port, sub { |
2071 | my ($fh) = @_; |
2354 | my ($fh) = @_; |
2072 | |
2355 | |
… | |
… | |
2146 | When you have intermediate CA certificates that your clients might not |
2429 | When you have intermediate CA certificates that your clients might not |
2147 | know about, just append them to the C<cert_file>. |
2430 | know 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 | |
2154 | In many cases, you might want to subclass AnyEvent::Handle. |
2436 | In many cases, you might want to subclass AnyEvent::Handle. |
2155 | |
2437 | |
2156 | To make this easier, a given version of AnyEvent::Handle uses these |
2438 | To 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 |
2174 | are free to use in subclasses. |
2456 | are free to use in subclasses. |
2175 | |
2457 | |
2176 | Of course, new versions of AnyEvent::Handle may introduce more "public" |
2458 | Of course, new versions of AnyEvent::Handle may introduce more "public" |
2177 | member variables, but thats just life, at least it is documented. |
2459 | member 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 | |
2183 | Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>. |
2465 | Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>. |
2184 | |
2466 | |
2185 | =cut |
2467 | =cut |
2186 | |
2468 | |
2187 | 1; # End of AnyEvent::Handle |
2469 | 1 |
|
|
2470 | |