ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Handle.pm
Revision: 1.159
Committed: Fri Jul 24 12:35:58 2009 UTC (14 years, 10 months ago) by root
Branch: MAIN
Changes since 1.158: +143 -39 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 package AnyEvent::Handle;
2
3 use Scalar::Util ();
4 use Carp ();
5 use Errno qw(EAGAIN EINTR);
6
7 use AnyEvent (); BEGIN { AnyEvent::common_sense }
8 use AnyEvent::Util qw(WSAEWOULDBLOCK);
9
10 =head1 NAME
11
12 AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
13
14 =cut
15
16 our $VERSION = 4.86;
17
18 =head1 SYNOPSIS
19
20 use AnyEvent;
21 use AnyEvent::Handle;
22
23 my $cv = AnyEvent->condvar;
24
25 my $hdl; $hdl = new AnyEvent::Handle
26 fh => \*STDIN,
27 on_error => sub {
28 my ($hdl, $fatal, $msg) = @_;
29 warn "got error $msg\n";
30 $hdl->destroy;
31 $cv->send;
32 );
33
34 # send some request line
35 $hdl->push_write ("getinfo\015\012");
36
37 # read the response line
38 $hdl->push_read (line => sub {
39 my ($hdl, $line) = @_;
40 warn "got line <$line>\n";
41 $cv->send;
42 });
43
44 $cv->recv;
45
46 =head1 DESCRIPTION
47
48 This module is a helper module to make it easier to do event-based I/O on
49 filehandles.
50
51 The L<AnyEvent::Intro> tutorial contains some well-documented
52 AnyEvent::Handle examples.
53
54 In the following, when the documentation refers to of "bytes" then this
55 means characters. As sysread and syswrite are used for all I/O, their
56 treatment of characters applies to this module as well.
57
58 At the very minimum, you should specify C<fh> or C<connect>, and the
59 C<on_error> callback.
60
61 All callbacks will be invoked with the handle object as their first
62 argument.
63
64 =head1 METHODS
65
66 =over 4
67
68 =item $handle = B<new> AnyEvent::TLS fh => $filehandle, key => value...
69
70 The constructor supports these arguments (all as C<< key => value >> pairs).
71
72 =over 4
73
74 =item fh => $filehandle [C<fh> or C<connect> MANDATORY]
75
76 The filehandle this L<AnyEvent::Handle> object will operate on.
77 NOTE: The filehandle will be set to non-blocking mode (using
78 C<AnyEvent::Util::fh_nonblocking>) by the constructor and needs to stay in
79 that mode.
80
81 =item connect => [$host, $service] [C<fh> or C<connect> MANDATORY]
82
83 Try to connect to the specified host and service (port), using
84 C<AnyEvent::Socket::tcp_connect>. The C<$host> additionally becomes the
85 default C<peername>.
86
87 You have to specify either this parameter, or C<fh>, above.
88
89 When this parameter is specified, then the C<on_prepare>,
90 C<on_connect_error> and C<on_connect> callbacks will be called under the
91 appropriate circumstances:
92
93 =over 4
94
95 =item on_prepare => $cb->($handle)
96
97 This (rarely used) callback is called before a new connection is
98 attempted, but after the file handle has been created. It could be used to
99 prepare the file handle with parameters required for the actual connect
100 (as opposed to settings that can be changed when the connection is already
101 established).
102
103 =item on_connect => $cb->($handle, $host, $port, $retry->())
104
105 This callback is called when a connection has been successfully established.
106
107 The actual numeric host and port (the socket peername) are passed as
108 parameters, together with a retry callback.
109
110 When, for some reason, the handle is not acceptable, then calling
111 C<$retry> will continue with the next conenction target (in case of
112 multi-homed hosts or SRV records there can be multiple connection
113 endpoints). When it is called then the read and write queues, eof status,
114 tls status and similar properties of the handle are being reset.
115
116 In most cases, ignoring the C<$retry> parameter is the way to go.
117
118 =item on_connect_error => $cb->($handle, $message)
119
120 This callback is called when the conenction could not be
121 established. C<$!> will contain the relevant error code, and C<$message> a
122 message describing it (usually the same as C<"$!">).
123
124 If this callback isn't specified, then C<on_error> will be called with a
125 fatal error instead.
126
127 =back
128
129 =item on_error => $cb->($handle, $fatal, $message)
130
131 This is the error callback, which is called when, well, some error
132 occured, such as not being able to resolve the hostname, failure to
133 connect or a read error.
134
135 Some errors are fatal (which is indicated by C<$fatal> being true). On
136 fatal errors the handle object will be destroyed (by a call to C<< ->
137 destroy >>) after invoking the error callback (which means you are free to
138 examine the handle object). Examples of fatal errors are an EOF condition
139 with active (but unsatisifable) read watchers (C<EPIPE>) or I/O errors. In
140 cases where the other side can close the connection at their will it is
141 often easiest to not report C<EPIPE> errors in this callback.
142
143 AnyEvent::Handle tries to find an appropriate error code for you to check
144 against, but in some cases (TLS errors), this does not work well. It is
145 recommended to always output the C<$message> argument in human-readable
146 error messages (it's usually the same as C<"$!">).
147
148 Non-fatal errors can be retried by simply returning, but it is recommended
149 to simply ignore this parameter and instead abondon the handle object
150 when this callback is invoked. Examples of non-fatal errors are timeouts
151 C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>).
152
153 On callback entrance, the value of C<$!> contains the operating system
154 error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or
155 C<EPROTO>).
156
157 While not mandatory, it is I<highly> recommended to set this callback, as
158 you will not be notified of errors otherwise. The default simply calls
159 C<croak>.
160
161 =item on_read => $cb->($handle)
162
163 This sets the default read callback, which is called when data arrives
164 and no read request is in the queue (unlike read queue callbacks, this
165 callback will only be called when at least one octet of data is in the
166 read buffer).
167
168 To access (and remove data from) the read buffer, use the C<< ->rbuf >>
169 method or access the C<< $handle->{rbuf} >> member directly. Note that you
170 must not enlarge or modify the read buffer, you can only remove data at
171 the beginning from it.
172
173 When an EOF condition is detected then AnyEvent::Handle will first try to
174 feed all the remaining data to the queued callbacks and C<on_read> before
175 calling the C<on_eof> callback. If no progress can be made, then a fatal
176 error will be raised (with C<$!> set to C<EPIPE>).
177
178 Note that, unlike requests in the read queue, an C<on_read> callback
179 doesn't mean you I<require> some data: if there is an EOF and there
180 are outstanding read requests then an error will be flagged. With an
181 C<on_read> callback, the C<on_eof> callback will be invoked.
182
183 =item on_eof => $cb->($handle)
184
185 Set the callback to be called when an end-of-file condition is detected,
186 i.e. in the case of a socket, when the other side has closed the
187 connection cleanly, and there are no outstanding read requests in the
188 queue (if there are read requests, then an EOF counts as an unexpected
189 connection close and will be flagged as an error).
190
191 For sockets, this just means that the other side has stopped sending data,
192 you can still try to write data, and, in fact, one can return from the EOF
193 callback and continue writing data, as only the read part has been shut
194 down.
195
196 If an EOF condition has been detected but no C<on_eof> callback has been
197 set, then a fatal error will be raised with C<$!> set to <0>.
198
199 =item on_drain => $cb->($handle)
200
201 This sets the callback that is called when the write buffer becomes empty
202 (or when the callback is set and the buffer is empty already).
203
204 To append to the write buffer, use the C<< ->push_write >> method.
205
206 This callback is useful when you don't want to put all of your write data
207 into the queue at once, for example, when you want to write the contents
208 of some file to the socket you might not want to read the whole file into
209 memory and push it into the queue, but instead only read more data from
210 the file when the write queue becomes empty.
211
212 =item timeout => $fractional_seconds
213
214 If non-zero, then this enables an "inactivity" timeout: whenever this many
215 seconds pass without a successful read or write on the underlying file
216 handle, the C<on_timeout> callback will be invoked (and if that one is
217 missing, a non-fatal C<ETIMEDOUT> error will be raised).
218
219 Note that timeout processing is also active when you currently do not have
220 any outstanding read or write requests: If you plan to keep the connection
221 idle then you should disable the timout temporarily or ignore the timeout
222 in the C<on_timeout> callback, in which case AnyEvent::Handle will simply
223 restart the timeout.
224
225 Zero (the default) disables this timeout.
226
227 =item on_timeout => $cb->($handle)
228
229 Called whenever the inactivity timeout passes. If you return from this
230 callback, then the timeout will be reset as if some activity had happened,
231 so this condition is not fatal in any way.
232
233 =item rbuf_max => <bytes>
234
235 If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
236 when the read buffer ever (strictly) exceeds this size. This is useful to
237 avoid some forms of denial-of-service attacks.
238
239 For example, a server accepting connections from untrusted sources should
240 be configured to accept only so-and-so much data that it cannot act on
241 (for example, when expecting a line, an attacker could send an unlimited
242 amount of data without a callback ever being called as long as the line
243 isn't finished).
244
245 =item autocork => <boolean>
246
247 When disabled (the default), then C<push_write> will try to immediately
248 write the data to the handle, if possible. This avoids having to register
249 a write watcher and wait for the next event loop iteration, but can
250 be inefficient if you write multiple small chunks (on the wire, this
251 disadvantage is usually avoided by your kernel's nagle algorithm, see
252 C<no_delay>, but this option can save costly syscalls).
253
254 When enabled, then writes will always be queued till the next event loop
255 iteration. This is efficient when you do many small writes per iteration,
256 but less efficient when you do a single write only per iteration (or when
257 the write buffer often is full). It also increases write latency.
258
259 =item no_delay => <boolean>
260
261 When doing small writes on sockets, your operating system kernel might
262 wait a bit for more data before actually sending it out. This is called
263 the Nagle algorithm, and usually it is beneficial.
264
265 In some situations you want as low a delay as possible, which can be
266 accomplishd by setting this option to a true value.
267
268 The default is your opertaing system's default behaviour (most likely
269 enabled), this option explicitly enables or disables it, if possible.
270
271 =item read_size => <bytes>
272
273 The default read block size (the amount of bytes this module will
274 try to read during each loop iteration, which affects memory
275 requirements). Default: C<8192>.
276
277 =item low_water_mark => <bytes>
278
279 Sets the amount of bytes (default: C<0>) that make up an "empty" write
280 buffer: If the write reaches this size or gets even samller it is
281 considered empty.
282
283 Sometimes it can be beneficial (for performance reasons) to add data to
284 the write buffer before it is fully drained, but this is a rare case, as
285 the operating system kernel usually buffers data as well, so the default
286 is good in almost all cases.
287
288 =item linger => <seconds>
289
290 If non-zero (default: C<3600>), then the destructor of the
291 AnyEvent::Handle object will check whether there is still outstanding
292 write data and will install a watcher that will write this data to the
293 socket. No errors will be reported (this mostly matches how the operating
294 system treats outstanding data at socket close time).
295
296 This will not work for partial TLS data that could not be encoded
297 yet. This data will be lost. Calling the C<stoptls> method in time might
298 help.
299
300 =item peername => $string
301
302 A string used to identify the remote site - usually the DNS hostname
303 (I<not> IDN!) used to create the connection, rarely the IP address.
304
305 Apart from being useful in error messages, this string is also used in TLS
306 peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This
307 verification will be skipped when C<peername> is not specified or
308 C<undef>.
309
310 =item tls => "accept" | "connect" | Net::SSLeay::SSL object
311
312 When this parameter is given, it enables TLS (SSL) mode, that means
313 AnyEvent will start a TLS handshake as soon as the conenction has been
314 established and will transparently encrypt/decrypt data afterwards.
315
316 All TLS protocol errors will be signalled as C<EPROTO>, with an
317 appropriate error message.
318
319 TLS mode requires Net::SSLeay to be installed (it will be loaded
320 automatically when you try to create a TLS handle): this module doesn't
321 have a dependency on that module, so if your module requires it, you have
322 to add the dependency yourself.
323
324 Unlike TCP, TLS has a server and client side: for the TLS server side, use
325 C<accept>, and for the TLS client side of a connection, use C<connect>
326 mode.
327
328 You can also provide your own TLS connection object, but you have
329 to make sure that you call either C<Net::SSLeay::set_connect_state>
330 or C<Net::SSLeay::set_accept_state> on it before you pass it to
331 AnyEvent::Handle. Also, this module will take ownership of this connection
332 object.
333
334 At some future point, AnyEvent::Handle might switch to another TLS
335 implementation, then the option to use your own session object will go
336 away.
337
338 B<IMPORTANT:> since Net::SSLeay "objects" are really only integers,
339 passing in the wrong integer will lead to certain crash. This most often
340 happens when one uses a stylish C<< tls => 1 >> and is surprised about the
341 segmentation fault.
342
343 See the C<< ->starttls >> method for when need to start TLS negotiation later.
344
345 =item tls_ctx => $anyevent_tls
346
347 Use the given C<AnyEvent::TLS> object to create the new TLS connection
348 (unless a connection object was specified directly). If this parameter is
349 missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>.
350
351 Instead of an object, you can also specify a hash reference with C<< key
352 => value >> pairs. Those will be passed to L<AnyEvent::TLS> to create a
353 new TLS context object.
354
355 =item on_starttls => $cb->($handle, $success[, $error_message])
356
357 This callback will be invoked when the TLS/SSL handshake has finished. If
358 C<$success> is true, then the TLS handshake succeeded, otherwise it failed
359 (C<on_stoptls> will not be called in this case).
360
361 The session in C<< $handle->{tls} >> can still be examined in this
362 callback, even when the handshake was not successful.
363
364 TLS handshake failures will not cause C<on_error> to be invoked when this
365 callback is in effect, instead, the error message will be passed to C<on_starttls>.
366
367 Without this callback, handshake failures lead to C<on_error> being
368 called, as normal.
369
370 Note that you cannot call C<starttls> right again in this callback. If you
371 need to do that, start an zero-second timer instead whose callback can
372 then call C<< ->starttls >> again.
373
374 =item on_stoptls => $cb->($handle)
375
376 When a SSLv3/TLS shutdown/close notify/EOF is detected and this callback is
377 set, then it will be invoked after freeing the TLS session. If it is not,
378 then a TLS shutdown condition will be treated like a normal EOF condition
379 on the handle.
380
381 The session in C<< $handle->{tls} >> can still be examined in this
382 callback.
383
384 This callback will only be called on TLS shutdowns, not when the
385 underlying handle signals EOF.
386
387 =item json => JSON or JSON::XS object
388
389 This is the json coder object used by the C<json> read and write types.
390
391 If you don't supply it, then AnyEvent::Handle will create and use a
392 suitable one (on demand), which will write and expect UTF-8 encoded JSON
393 texts.
394
395 Note that you are responsible to depend on the JSON module if you want to
396 use this functionality, as AnyEvent does not have a dependency itself.
397
398 =back
399
400 =cut
401
402 sub new {
403 my $class = shift;
404 my $self = bless { @_ }, $class;
405
406 if ($self->{fh}) {
407 $self->_start;
408 return unless $self->{fh}; # could be gone by now
409
410 } elsif ($self->{connect}) {
411 require AnyEvent::Socket;
412
413 $self->{peername} = $self->{connect}[0]
414 unless exists $self->{peername};
415
416 $self->{_skip_drain_rbuf} = 1;
417
418 {
419 Scalar::Util::weaken (my $self = $self);
420
421 $self->{_connect} =
422 AnyEvent::Socket::tcp_connect (
423 $self->{connect}[0],
424 $self->{connect}[1],
425 sub {
426 my ($fh, $host, $port, $retry) = @_;
427
428 if ($fh) {
429 $self->{fh} = $fh;
430
431 delete $self->{_skip_drain_rbuf};
432 $self->_start;
433
434 $self->{on_connect}
435 and $self->{on_connect}($self, $host, $port, sub {
436 delete @$self{qw(fh _tw _ww _rw _eof _queue rbuf _wbuf tls _tls_rbuf _tls_wbuf)};
437 $self->{_skip_drain_rbuf} = 1;
438 &$retry;
439 });
440
441 } else {
442 if ($self->{on_connect_error}) {
443 $self->{on_connect_error}($self, "$!");
444 $self->destroy;
445 } else {
446 $self->fatal ($!, 1);
447 }
448 }
449 },
450 sub {
451 local $self->{fh} = $_[0];
452
453 $self->{on_prepare}->($self)
454 if $self->{on_prepare};
455 }
456 );
457 }
458
459 } else {
460 Carp::croak "AnyEvent::Handle: either an existing fh or the connect parameter must be specified";
461 }
462
463 $self
464 }
465
466 sub _start {
467 my ($self) = @_;
468
469 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
470
471 $self->{_activity} = AnyEvent->now;
472 $self->_timeout;
473
474 $self->no_delay (delete $self->{no_delay}) if exists $self->{no_delay};
475
476 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
477 if $self->{tls};
478
479 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
480
481 $self->start_read
482 if $self->{on_read} || @{ $self->{_queue} };
483 }
484
485 #sub _shutdown {
486 # my ($self) = @_;
487 #
488 # delete @$self{qw(_tw _rw _ww fh wbuf on_read _queue)};
489 # $self->{_eof} = 1; # tell starttls et. al to stop trying
490 #
491 # &_freetls;
492 #}
493
494 sub _error {
495 my ($self, $errno, $fatal, $message) = @_;
496
497 $! = $errno;
498 $message ||= "$!";
499
500 if ($self->{on_error}) {
501 $self->{on_error}($self, $fatal, $message);
502 $self->destroy if $fatal;
503 } elsif ($self->{fh}) {
504 $self->destroy;
505 Carp::croak "AnyEvent::Handle uncaught error: $message";
506 }
507 }
508
509 =item $fh = $handle->fh
510
511 This method returns the file handle used to create the L<AnyEvent::Handle> object.
512
513 =cut
514
515 sub fh { $_[0]{fh} }
516
517 =item $handle->on_error ($cb)
518
519 Replace the current C<on_error> callback (see the C<on_error> constructor argument).
520
521 =cut
522
523 sub on_error {
524 $_[0]{on_error} = $_[1];
525 }
526
527 =item $handle->on_eof ($cb)
528
529 Replace the current C<on_eof> callback (see the C<on_eof> constructor argument).
530
531 =cut
532
533 sub on_eof {
534 $_[0]{on_eof} = $_[1];
535 }
536
537 =item $handle->on_timeout ($cb)
538
539 Replace the current C<on_timeout> callback, or disables the callback (but
540 not the timeout) if C<$cb> = C<undef>. See the C<timeout> constructor
541 argument and method.
542
543 =cut
544
545 sub on_timeout {
546 $_[0]{on_timeout} = $_[1];
547 }
548
549 =item $handle->autocork ($boolean)
550
551 Enables or disables the current autocork behaviour (see C<autocork>
552 constructor argument). Changes will only take effect on the next write.
553
554 =cut
555
556 sub autocork {
557 $_[0]{autocork} = $_[1];
558 }
559
560 =item $handle->no_delay ($boolean)
561
562 Enables or disables the C<no_delay> setting (see constructor argument of
563 the same name for details).
564
565 =cut
566
567 sub no_delay {
568 $_[0]{no_delay} = $_[1];
569
570 eval {
571 local $SIG{__DIE__};
572 setsockopt $_[0]{fh}, &Socket::IPPROTO_TCP, &Socket::TCP_NODELAY, int $_[1]
573 if $_[0]{fh};
574 };
575 }
576
577 =item $handle->on_starttls ($cb)
578
579 Replace the current C<on_starttls> callback (see the C<on_starttls> constructor argument).
580
581 =cut
582
583 sub on_starttls {
584 $_[0]{on_starttls} = $_[1];
585 }
586
587 =item $handle->on_stoptls ($cb)
588
589 Replace the current C<on_stoptls> callback (see the C<on_stoptls> constructor argument).
590
591 =cut
592
593 sub on_starttls {
594 $_[0]{on_stoptls} = $_[1];
595 }
596
597 #############################################################################
598
599 =item $handle->timeout ($seconds)
600
601 Configures (or disables) the inactivity timeout.
602
603 =cut
604
605 sub timeout {
606 my ($self, $timeout) = @_;
607
608 $self->{timeout} = $timeout;
609 $self->_timeout;
610 }
611
612 # reset the timeout watcher, as neccessary
613 # also check for time-outs
614 sub _timeout {
615 my ($self) = @_;
616
617 if ($self->{timeout} && $self->{fh}) {
618 my $NOW = AnyEvent->now;
619
620 # when would the timeout trigger?
621 my $after = $self->{_activity} + $self->{timeout} - $NOW;
622
623 # now or in the past already?
624 if ($after <= 0) {
625 $self->{_activity} = $NOW;
626
627 if ($self->{on_timeout}) {
628 $self->{on_timeout}($self);
629 } else {
630 $self->_error (Errno::ETIMEDOUT);
631 }
632
633 # callback could have changed timeout value, optimise
634 return unless $self->{timeout};
635
636 # calculate new after
637 $after = $self->{timeout};
638 }
639
640 Scalar::Util::weaken $self;
641 return unless $self; # ->error could have destroyed $self
642
643 $self->{_tw} ||= AnyEvent->timer (after => $after, cb => sub {
644 delete $self->{_tw};
645 $self->_timeout;
646 });
647 } else {
648 delete $self->{_tw};
649 }
650 }
651
652 #############################################################################
653
654 =back
655
656 =head2 WRITE QUEUE
657
658 AnyEvent::Handle manages two queues per handle, one for writing and one
659 for reading.
660
661 The write queue is very simple: you can add data to its end, and
662 AnyEvent::Handle will automatically try to get rid of it for you.
663
664 When data could be written and the write buffer is shorter then the low
665 water mark, the C<on_drain> callback will be invoked.
666
667 =over 4
668
669 =item $handle->on_drain ($cb)
670
671 Sets the C<on_drain> callback or clears it (see the description of
672 C<on_drain> in the constructor).
673
674 =cut
675
676 sub on_drain {
677 my ($self, $cb) = @_;
678
679 $self->{on_drain} = $cb;
680
681 $cb->($self)
682 if $cb && $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf});
683 }
684
685 =item $handle->push_write ($data)
686
687 Queues the given scalar to be written. You can push as much data as you
688 want (only limited by the available memory), as C<AnyEvent::Handle>
689 buffers it independently of the kernel.
690
691 =cut
692
693 sub _drain_wbuf {
694 my ($self) = @_;
695
696 if (!$self->{_ww} && length $self->{wbuf}) {
697
698 Scalar::Util::weaken $self;
699
700 my $cb = sub {
701 my $len = syswrite $self->{fh}, $self->{wbuf};
702
703 if (defined $len) {
704 substr $self->{wbuf}, 0, $len, "";
705
706 $self->{_activity} = AnyEvent->now;
707
708 $self->{on_drain}($self)
709 if $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf})
710 && $self->{on_drain};
711
712 delete $self->{_ww} unless length $self->{wbuf};
713 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
714 $self->_error ($!, 1);
715 }
716 };
717
718 # try to write data immediately
719 $cb->() unless $self->{autocork};
720
721 # if still data left in wbuf, we need to poll
722 $self->{_ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb)
723 if length $self->{wbuf};
724 };
725 }
726
727 our %WH;
728
729 sub register_write_type($$) {
730 $WH{$_[0]} = $_[1];
731 }
732
733 sub push_write {
734 my $self = shift;
735
736 if (@_ > 1) {
737 my $type = shift;
738
739 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write")
740 ->($self, @_);
741 }
742
743 if ($self->{tls}) {
744 $self->{_tls_wbuf} .= $_[0];
745
746 &_dotls ($self);
747 } else {
748 $self->{wbuf} .= $_[0];
749 $self->_drain_wbuf if $self->{fh};
750 }
751 }
752
753 =item $handle->push_write (type => @args)
754
755 Instead of formatting your data yourself, you can also let this module do
756 the job by specifying a type and type-specific arguments.
757
758 Predefined types are (if you have ideas for additional types, feel free to
759 drop by and tell us):
760
761 =over 4
762
763 =item netstring => $string
764
765 Formats the given value as netstring
766 (http://cr.yp.to/proto/netstrings.txt, this is not a recommendation to use them).
767
768 =cut
769
770 register_write_type netstring => sub {
771 my ($self, $string) = @_;
772
773 (length $string) . ":$string,"
774 };
775
776 =item packstring => $format, $data
777
778 An octet string prefixed with an encoded length. The encoding C<$format>
779 uses the same format as a Perl C<pack> format, but must specify a single
780 integer only (only one of C<cCsSlLqQiInNvVjJw> is allowed, plus an
781 optional C<!>, C<< < >> or C<< > >> modifier).
782
783 =cut
784
785 register_write_type packstring => sub {
786 my ($self, $format, $string) = @_;
787
788 pack "$format/a*", $string
789 };
790
791 =item json => $array_or_hashref
792
793 Encodes the given hash or array reference into a JSON object. Unless you
794 provide your own JSON object, this means it will be encoded to JSON text
795 in UTF-8.
796
797 JSON objects (and arrays) are self-delimiting, so you can write JSON at
798 one end of a handle and read them at the other end without using any
799 additional framing.
800
801 The generated JSON text is guaranteed not to contain any newlines: While
802 this module doesn't need delimiters after or between JSON texts to be
803 able to read them, many other languages depend on that.
804
805 A simple RPC protocol that interoperates easily with others is to send
806 JSON arrays (or objects, although arrays are usually the better choice as
807 they mimic how function argument passing works) and a newline after each
808 JSON text:
809
810 $handle->push_write (json => ["method", "arg1", "arg2"]); # whatever
811 $handle->push_write ("\012");
812
813 An AnyEvent::Handle receiver would simply use the C<json> read type and
814 rely on the fact that the newline will be skipped as leading whitespace:
815
816 $handle->push_read (json => sub { my $array = $_[1]; ... });
817
818 Other languages could read single lines terminated by a newline and pass
819 this line into their JSON decoder of choice.
820
821 =cut
822
823 register_write_type json => sub {
824 my ($self, $ref) = @_;
825
826 require JSON;
827
828 $self->{json} ? $self->{json}->encode ($ref)
829 : JSON::encode_json ($ref)
830 };
831
832 =item storable => $reference
833
834 Freezes the given reference using L<Storable> and writes it to the
835 handle. Uses the C<nfreeze> format.
836
837 =cut
838
839 register_write_type storable => sub {
840 my ($self, $ref) = @_;
841
842 require Storable;
843
844 pack "w/a*", Storable::nfreeze ($ref)
845 };
846
847 =back
848
849 =item $handle->push_shutdown
850
851 Sometimes you know you want to close the socket after writing your data
852 before it was actually written. One way to do that is to replace your
853 C<on_drain> handler by a callback that shuts down the socket (and set
854 C<low_water_mark> to C<0>). This method is a shorthand for just that, and
855 replaces the C<on_drain> callback with:
856
857 sub { shutdown $_[0]{fh}, 1 } # for push_shutdown
858
859 This simply shuts down the write side and signals an EOF condition to the
860 the peer.
861
862 You can rely on the normal read queue and C<on_eof> handling
863 afterwards. This is the cleanest way to close a connection.
864
865 =cut
866
867 sub push_shutdown {
868 my ($self) = @_;
869
870 delete $self->{low_water_mark};
871 $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
872 }
873
874 =item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args)
875
876 This function (not method) lets you add your own types to C<push_write>.
877 Whenever the given C<type> is used, C<push_write> will invoke the code
878 reference with the handle object and the remaining arguments.
879
880 The code reference is supposed to return a single octet string that will
881 be appended to the write buffer.
882
883 Note that this is a function, and all types registered this way will be
884 global, so try to use unique names.
885
886 =cut
887
888 #############################################################################
889
890 =back
891
892 =head2 READ QUEUE
893
894 AnyEvent::Handle manages two queues per handle, one for writing and one
895 for reading.
896
897 The read queue is more complex than the write queue. It can be used in two
898 ways, the "simple" way, using only C<on_read> and the "complex" way, using
899 a queue.
900
901 In the simple case, you just install an C<on_read> callback and whenever
902 new data arrives, it will be called. You can then remove some data (if
903 enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna
904 leave the data there if you want to accumulate more (e.g. when only a
905 partial message has been received so far).
906
907 In the more complex case, you want to queue multiple callbacks. In this
908 case, AnyEvent::Handle will call the first queued callback each time new
909 data arrives (also the first time it is queued) and removes it when it has
910 done its job (see C<push_read>, below).
911
912 This way you can, for example, push three line-reads, followed by reading
913 a chunk of data, and AnyEvent::Handle will execute them in order.
914
915 Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
916 the specified number of bytes which give an XML datagram.
917
918 # in the default state, expect some header bytes
919 $handle->on_read (sub {
920 # some data is here, now queue the length-header-read (4 octets)
921 shift->unshift_read (chunk => 4, sub {
922 # header arrived, decode
923 my $len = unpack "N", $_[1];
924
925 # now read the payload
926 shift->unshift_read (chunk => $len, sub {
927 my $xml = $_[1];
928 # handle xml
929 });
930 });
931 });
932
933 Example 2: Implement a client for a protocol that replies either with "OK"
934 and another line or "ERROR" for the first request that is sent, and 64
935 bytes for the second request. Due to the availability of a queue, we can
936 just pipeline sending both requests and manipulate the queue as necessary
937 in the callbacks.
938
939 When the first callback is called and sees an "OK" response, it will
940 C<unshift> another line-read. This line-read will be queued I<before> the
941 64-byte chunk callback.
942
943 # request one, returns either "OK + extra line" or "ERROR"
944 $handle->push_write ("request 1\015\012");
945
946 # we expect "ERROR" or "OK" as response, so push a line read
947 $handle->push_read (line => sub {
948 # if we got an "OK", we have to _prepend_ another line,
949 # so it will be read before the second request reads its 64 bytes
950 # which are already in the queue when this callback is called
951 # we don't do this in case we got an error
952 if ($_[1] eq "OK") {
953 $_[0]->unshift_read (line => sub {
954 my $response = $_[1];
955 ...
956 });
957 }
958 });
959
960 # request two, simply returns 64 octets
961 $handle->push_write ("request 2\015\012");
962
963 # simply read 64 bytes, always
964 $handle->push_read (chunk => 64, sub {
965 my $response = $_[1];
966 ...
967 });
968
969 =over 4
970
971 =cut
972
973 sub _drain_rbuf {
974 my ($self) = @_;
975
976 # avoid recursion
977 return if exists $self->{_skip_drain_rbuf};
978 local $self->{_skip_drain_rbuf} = 1;
979
980 if (
981 defined $self->{rbuf_max}
982 && $self->{rbuf_max} < length $self->{rbuf}
983 ) {
984 $self->_error (Errno::ENOSPC, 1), return;
985 }
986
987 while () {
988 # we need to use a separate tls read buffer, as we must not receive data while
989 # we are draining the buffer, and this can only happen with TLS.
990 $self->{rbuf} .= delete $self->{_tls_rbuf} if exists $self->{_tls_rbuf};
991
992 my $len = length $self->{rbuf};
993
994 if (my $cb = shift @{ $self->{_queue} }) {
995 unless ($cb->($self)) {
996 if ($self->{_eof}) {
997 # no progress can be made (not enough data and no data forthcoming)
998 $self->_error (Errno::EPIPE, 1), return;
999 }
1000
1001 unshift @{ $self->{_queue} }, $cb;
1002 last;
1003 }
1004 } elsif ($self->{on_read}) {
1005 last unless $len;
1006
1007 $self->{on_read}($self);
1008
1009 if (
1010 $len == length $self->{rbuf} # if no data has been consumed
1011 && !@{ $self->{_queue} } # and the queue is still empty
1012 && $self->{on_read} # but we still have on_read
1013 ) {
1014 # no further data will arrive
1015 # so no progress can be made
1016 $self->_error (Errno::EPIPE, 1), return
1017 if $self->{_eof};
1018
1019 last; # more data might arrive
1020 }
1021 } else {
1022 # read side becomes idle
1023 delete $self->{_rw} unless $self->{tls};
1024 last;
1025 }
1026 }
1027
1028 if ($self->{_eof}) {
1029 if ($self->{on_eof}) {
1030 $self->{on_eof}($self)
1031 } else {
1032 $self->_error (0, 1, "Unexpected end-of-file");
1033 }
1034 }
1035
1036 # may need to restart read watcher
1037 unless ($self->{_rw}) {
1038 $self->start_read
1039 if $self->{on_read} || @{ $self->{_queue} };
1040 }
1041 }
1042
1043 =item $handle->on_read ($cb)
1044
1045 This replaces the currently set C<on_read> callback, or clears it (when
1046 the new callback is C<undef>). See the description of C<on_read> in the
1047 constructor.
1048
1049 =cut
1050
1051 sub on_read {
1052 my ($self, $cb) = @_;
1053
1054 $self->{on_read} = $cb;
1055 $self->_drain_rbuf if $cb;
1056 }
1057
1058 =item $handle->rbuf
1059
1060 Returns the read buffer (as a modifiable lvalue).
1061
1062 You can access the read buffer directly as the C<< ->{rbuf} >>
1063 member, if you want. However, the only operation allowed on the
1064 read buffer (apart from looking at it) is removing data from its
1065 beginning. Otherwise modifying or appending to it is not allowed and will
1066 lead to hard-to-track-down bugs.
1067
1068 NOTE: The read buffer should only be used or modified if the C<on_read>,
1069 C<push_read> or C<unshift_read> methods are used. The other read methods
1070 automatically manage the read buffer.
1071
1072 =cut
1073
1074 sub rbuf : lvalue {
1075 $_[0]{rbuf}
1076 }
1077
1078 =item $handle->push_read ($cb)
1079
1080 =item $handle->unshift_read ($cb)
1081
1082 Append the given callback to the end of the queue (C<push_read>) or
1083 prepend it (C<unshift_read>).
1084
1085 The callback is called each time some additional read data arrives.
1086
1087 It must check whether enough data is in the read buffer already.
1088
1089 If not enough data is available, it must return the empty list or a false
1090 value, in which case it will be called repeatedly until enough data is
1091 available (or an error condition is detected).
1092
1093 If enough data was available, then the callback must remove all data it is
1094 interested in (which can be none at all) and return a true value. After returning
1095 true, it will be removed from the queue.
1096
1097 =cut
1098
1099 our %RH;
1100
1101 sub register_read_type($$) {
1102 $RH{$_[0]} = $_[1];
1103 }
1104
1105 sub push_read {
1106 my $self = shift;
1107 my $cb = pop;
1108
1109 if (@_) {
1110 my $type = shift;
1111
1112 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read")
1113 ->($self, $cb, @_);
1114 }
1115
1116 push @{ $self->{_queue} }, $cb;
1117 $self->_drain_rbuf;
1118 }
1119
1120 sub unshift_read {
1121 my $self = shift;
1122 my $cb = pop;
1123
1124 if (@_) {
1125 my $type = shift;
1126
1127 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
1128 ->($self, $cb, @_);
1129 }
1130
1131
1132 unshift @{ $self->{_queue} }, $cb;
1133 $self->_drain_rbuf;
1134 }
1135
1136 =item $handle->push_read (type => @args, $cb)
1137
1138 =item $handle->unshift_read (type => @args, $cb)
1139
1140 Instead of providing a callback that parses the data itself you can chose
1141 between a number of predefined parsing formats, for chunks of data, lines
1142 etc.
1143
1144 Predefined types are (if you have ideas for additional types, feel free to
1145 drop by and tell us):
1146
1147 =over 4
1148
1149 =item chunk => $octets, $cb->($handle, $data)
1150
1151 Invoke the callback only once C<$octets> bytes have been read. Pass the
1152 data read to the callback. The callback will never be called with less
1153 data.
1154
1155 Example: read 2 bytes.
1156
1157 $handle->push_read (chunk => 2, sub {
1158 warn "yay ", unpack "H*", $_[1];
1159 });
1160
1161 =cut
1162
1163 register_read_type chunk => sub {
1164 my ($self, $cb, $len) = @_;
1165
1166 sub {
1167 $len <= length $_[0]{rbuf} or return;
1168 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
1169 1
1170 }
1171 };
1172
1173 =item line => [$eol, ]$cb->($handle, $line, $eol)
1174
1175 The callback will be called only once a full line (including the end of
1176 line marker, C<$eol>) has been read. This line (excluding the end of line
1177 marker) will be passed to the callback as second argument (C<$line>), and
1178 the end of line marker as the third argument (C<$eol>).
1179
1180 The end of line marker, C<$eol>, can be either a string, in which case it
1181 will be interpreted as a fixed record end marker, or it can be a regex
1182 object (e.g. created by C<qr>), in which case it is interpreted as a
1183 regular expression.
1184
1185 The end of line marker argument C<$eol> is optional, if it is missing (NOT
1186 undef), then C<qr|\015?\012|> is used (which is good for most internet
1187 protocols).
1188
1189 Partial lines at the end of the stream will never be returned, as they are
1190 not marked by the end of line marker.
1191
1192 =cut
1193
1194 register_read_type line => sub {
1195 my ($self, $cb, $eol) = @_;
1196
1197 if (@_ < 3) {
1198 # this is more than twice as fast as the generic code below
1199 sub {
1200 $_[0]{rbuf} =~ s/^([^\015\012]*)(\015?\012)// or return;
1201
1202 $cb->($_[0], $1, $2);
1203 1
1204 }
1205 } else {
1206 $eol = quotemeta $eol unless ref $eol;
1207 $eol = qr|^(.*?)($eol)|s;
1208
1209 sub {
1210 $_[0]{rbuf} =~ s/$eol// or return;
1211
1212 $cb->($_[0], $1, $2);
1213 1
1214 }
1215 }
1216 };
1217
1218 =item regex => $accept[, $reject[, $skip], $cb->($handle, $data)
1219
1220 Makes a regex match against the regex object C<$accept> and returns
1221 everything up to and including the match.
1222
1223 Example: read a single line terminated by '\n'.
1224
1225 $handle->push_read (regex => qr<\n>, sub { ... });
1226
1227 If C<$reject> is given and not undef, then it determines when the data is
1228 to be rejected: it is matched against the data when the C<$accept> regex
1229 does not match and generates an C<EBADMSG> error when it matches. This is
1230 useful to quickly reject wrong data (to avoid waiting for a timeout or a
1231 receive buffer overflow).
1232
1233 Example: expect a single decimal number followed by whitespace, reject
1234 anything else (not the use of an anchor).
1235
1236 $handle->push_read (regex => qr<^[0-9]+\s>, qr<[^0-9]>, sub { ... });
1237
1238 If C<$skip> is given and not C<undef>, then it will be matched against
1239 the receive buffer when neither C<$accept> nor C<$reject> match,
1240 and everything preceding and including the match will be accepted
1241 unconditionally. This is useful to skip large amounts of data that you
1242 know cannot be matched, so that the C<$accept> or C<$reject> regex do not
1243 have to start matching from the beginning. This is purely an optimisation
1244 and is usually worth only when you expect more than a few kilobytes.
1245
1246 Example: expect a http header, which ends at C<\015\012\015\012>. Since we
1247 expect the header to be very large (it isn't in practise, but...), we use
1248 a skip regex to skip initial portions. The skip regex is tricky in that
1249 it only accepts something not ending in either \015 or \012, as these are
1250 required for the accept regex.
1251
1252 $handle->push_read (regex =>
1253 qr<\015\012\015\012>,
1254 undef, # no reject
1255 qr<^.*[^\015\012]>,
1256 sub { ... });
1257
1258 =cut
1259
1260 register_read_type regex => sub {
1261 my ($self, $cb, $accept, $reject, $skip) = @_;
1262
1263 my $data;
1264 my $rbuf = \$self->{rbuf};
1265
1266 sub {
1267 # accept
1268 if ($$rbuf =~ $accept) {
1269 $data .= substr $$rbuf, 0, $+[0], "";
1270 $cb->($self, $data);
1271 return 1;
1272 }
1273
1274 # reject
1275 if ($reject && $$rbuf =~ $reject) {
1276 $self->_error (Errno::EBADMSG);
1277 }
1278
1279 # skip
1280 if ($skip && $$rbuf =~ $skip) {
1281 $data .= substr $$rbuf, 0, $+[0], "";
1282 }
1283
1284 ()
1285 }
1286 };
1287
1288 =item netstring => $cb->($handle, $string)
1289
1290 A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
1291
1292 Throws an error with C<$!> set to EBADMSG on format violations.
1293
1294 =cut
1295
1296 register_read_type netstring => sub {
1297 my ($self, $cb) = @_;
1298
1299 sub {
1300 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
1301 if ($_[0]{rbuf} =~ /[^0-9]/) {
1302 $self->_error (Errno::EBADMSG);
1303 }
1304 return;
1305 }
1306
1307 my $len = $1;
1308
1309 $self->unshift_read (chunk => $len, sub {
1310 my $string = $_[1];
1311 $_[0]->unshift_read (chunk => 1, sub {
1312 if ($_[1] eq ",") {
1313 $cb->($_[0], $string);
1314 } else {
1315 $self->_error (Errno::EBADMSG);
1316 }
1317 });
1318 });
1319
1320 1
1321 }
1322 };
1323
1324 =item packstring => $format, $cb->($handle, $string)
1325
1326 An octet string prefixed with an encoded length. The encoding C<$format>
1327 uses the same format as a Perl C<pack> format, but must specify a single
1328 integer only (only one of C<cCsSlLqQiInNvVjJw> is allowed, plus an
1329 optional C<!>, C<< < >> or C<< > >> modifier).
1330
1331 For example, DNS over TCP uses a prefix of C<n> (2 octet network order),
1332 EPP uses a prefix of C<N> (4 octtes).
1333
1334 Example: read a block of data prefixed by its length in BER-encoded
1335 format (very efficient).
1336
1337 $handle->push_read (packstring => "w", sub {
1338 my ($handle, $data) = @_;
1339 });
1340
1341 =cut
1342
1343 register_read_type packstring => sub {
1344 my ($self, $cb, $format) = @_;
1345
1346 sub {
1347 # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method
1348 defined (my $len = eval { unpack $format, $_[0]{rbuf} })
1349 or return;
1350
1351 $format = length pack $format, $len;
1352
1353 # bypass unshift if we already have the remaining chunk
1354 if ($format + $len <= length $_[0]{rbuf}) {
1355 my $data = substr $_[0]{rbuf}, $format, $len;
1356 substr $_[0]{rbuf}, 0, $format + $len, "";
1357 $cb->($_[0], $data);
1358 } else {
1359 # remove prefix
1360 substr $_[0]{rbuf}, 0, $format, "";
1361
1362 # read remaining chunk
1363 $_[0]->unshift_read (chunk => $len, $cb);
1364 }
1365
1366 1
1367 }
1368 };
1369
1370 =item json => $cb->($handle, $hash_or_arrayref)
1371
1372 Reads a JSON object or array, decodes it and passes it to the
1373 callback. When a parse error occurs, an C<EBADMSG> error will be raised.
1374
1375 If a C<json> object was passed to the constructor, then that will be used
1376 for the final decode, otherwise it will create a JSON coder expecting UTF-8.
1377
1378 This read type uses the incremental parser available with JSON version
1379 2.09 (and JSON::XS version 2.2) and above. You have to provide a
1380 dependency on your own: this module will load the JSON module, but
1381 AnyEvent does not depend on it itself.
1382
1383 Since JSON texts are fully self-delimiting, the C<json> read and write
1384 types are an ideal simple RPC protocol: just exchange JSON datagrams. See
1385 the C<json> write type description, above, for an actual example.
1386
1387 =cut
1388
1389 register_read_type json => sub {
1390 my ($self, $cb) = @_;
1391
1392 my $json = $self->{json} ||=
1393 eval { require JSON::XS; JSON::XS->new->utf8 }
1394 || do { require JSON; JSON->new->utf8 };
1395
1396 my $data;
1397 my $rbuf = \$self->{rbuf};
1398
1399 sub {
1400 my $ref = eval { $json->incr_parse ($self->{rbuf}) };
1401
1402 if ($ref) {
1403 $self->{rbuf} = $json->incr_text;
1404 $json->incr_text = "";
1405 $cb->($self, $ref);
1406
1407 1
1408 } elsif ($@) {
1409 # error case
1410 $json->incr_skip;
1411
1412 $self->{rbuf} = $json->incr_text;
1413 $json->incr_text = "";
1414
1415 $self->_error (Errno::EBADMSG);
1416
1417 ()
1418 } else {
1419 $self->{rbuf} = "";
1420
1421 ()
1422 }
1423 }
1424 };
1425
1426 =item storable => $cb->($handle, $ref)
1427
1428 Deserialises a L<Storable> frozen representation as written by the
1429 C<storable> write type (BER-encoded length prefix followed by nfreeze'd
1430 data).
1431
1432 Raises C<EBADMSG> error if the data could not be decoded.
1433
1434 =cut
1435
1436 register_read_type storable => sub {
1437 my ($self, $cb) = @_;
1438
1439 require Storable;
1440
1441 sub {
1442 # when we can use 5.10 we can use ".", but for 5.8 we use the re-pack method
1443 defined (my $len = eval { unpack "w", $_[0]{rbuf} })
1444 or return;
1445
1446 my $format = length pack "w", $len;
1447
1448 # bypass unshift if we already have the remaining chunk
1449 if ($format + $len <= length $_[0]{rbuf}) {
1450 my $data = substr $_[0]{rbuf}, $format, $len;
1451 substr $_[0]{rbuf}, 0, $format + $len, "";
1452 $cb->($_[0], Storable::thaw ($data));
1453 } else {
1454 # remove prefix
1455 substr $_[0]{rbuf}, 0, $format, "";
1456
1457 # read remaining chunk
1458 $_[0]->unshift_read (chunk => $len, sub {
1459 if (my $ref = eval { Storable::thaw ($_[1]) }) {
1460 $cb->($_[0], $ref);
1461 } else {
1462 $self->_error (Errno::EBADMSG);
1463 }
1464 });
1465 }
1466
1467 1
1468 }
1469 };
1470
1471 =back
1472
1473 =item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args)
1474
1475 This function (not method) lets you add your own types to C<push_read>.
1476
1477 Whenever the given C<type> is used, C<push_read> will invoke the code
1478 reference with the handle object, the callback and the remaining
1479 arguments.
1480
1481 The code reference is supposed to return a callback (usually a closure)
1482 that works as a plain read callback (see C<< ->push_read ($cb) >>).
1483
1484 It should invoke the passed callback when it is done reading (remember to
1485 pass C<$handle> as first argument as all other callbacks do that).
1486
1487 Note that this is a function, and all types registered this way will be
1488 global, so try to use unique names.
1489
1490 For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>,
1491 search for C<register_read_type>)).
1492
1493 =item $handle->stop_read
1494
1495 =item $handle->start_read
1496
1497 In rare cases you actually do not want to read anything from the
1498 socket. In this case you can call C<stop_read>. Neither C<on_read> nor
1499 any queued callbacks will be executed then. To start reading again, call
1500 C<start_read>.
1501
1502 Note that AnyEvent::Handle will automatically C<start_read> for you when
1503 you change the C<on_read> callback or push/unshift a read callback, and it
1504 will automatically C<stop_read> for you when neither C<on_read> is set nor
1505 there are any read requests in the queue.
1506
1507 These methods will have no effect when in TLS mode (as TLS doesn't support
1508 half-duplex connections).
1509
1510 =cut
1511
1512 sub stop_read {
1513 my ($self) = @_;
1514
1515 delete $self->{_rw} unless $self->{tls};
1516 }
1517
1518 sub start_read {
1519 my ($self) = @_;
1520
1521 unless ($self->{_rw} || $self->{_eof}) {
1522 Scalar::Util::weaken $self;
1523
1524 $self->{_rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
1525 my $rbuf = \($self->{tls} ? my $buf : $self->{rbuf});
1526 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
1527
1528 if ($len > 0) {
1529 $self->{_activity} = AnyEvent->now;
1530
1531 if ($self->{tls}) {
1532 Net::SSLeay::BIO_write ($self->{_rbio}, $$rbuf);
1533
1534 &_dotls ($self);
1535 } else {
1536 $self->_drain_rbuf;
1537 }
1538
1539 } elsif (defined $len) {
1540 delete $self->{_rw};
1541 $self->{_eof} = 1;
1542 $self->_drain_rbuf;
1543
1544 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
1545 return $self->_error ($!, 1);
1546 }
1547 });
1548 }
1549 }
1550
1551 our $ERROR_SYSCALL;
1552 our $ERROR_WANT_READ;
1553
1554 sub _tls_error {
1555 my ($self, $err) = @_;
1556
1557 return $self->_error ($!, 1)
1558 if $err == Net::SSLeay::ERROR_SYSCALL ();
1559
1560 my $err =Net::SSLeay::ERR_error_string (Net::SSLeay::ERR_get_error ());
1561
1562 # reduce error string to look less scary
1563 $err =~ s/^error:[0-9a-fA-F]{8}:[^:]+:([^:]+):/\L$1: /;
1564
1565 if ($self->{_on_starttls}) {
1566 (delete $self->{_on_starttls})->($self, undef, $err);
1567 &_freetls;
1568 } else {
1569 &_freetls;
1570 $self->_error (Errno::EPROTO, 1, $err);
1571 }
1572 }
1573
1574 # poll the write BIO and send the data if applicable
1575 # also decode read data if possible
1576 # this is basiclaly our TLS state machine
1577 # more efficient implementations are possible with openssl,
1578 # but not with the buggy and incomplete Net::SSLeay.
1579 sub _dotls {
1580 my ($self) = @_;
1581
1582 my $tmp;
1583
1584 if (length $self->{_tls_wbuf}) {
1585 while (($tmp = Net::SSLeay::write ($self->{tls}, $self->{_tls_wbuf})) > 0) {
1586 substr $self->{_tls_wbuf}, 0, $tmp, "";
1587 }
1588
1589 $tmp = Net::SSLeay::get_error ($self->{tls}, $tmp);
1590 return $self->_tls_error ($tmp)
1591 if $tmp != $ERROR_WANT_READ
1592 && ($tmp != $ERROR_SYSCALL || $!);
1593 }
1594
1595 while (defined ($tmp = Net::SSLeay::read ($self->{tls}))) {
1596 unless (length $tmp) {
1597 $self->{_on_starttls}
1598 and (delete $self->{_on_starttls})->($self, undef, "EOF during handshake"); # ???
1599 &_freetls;
1600
1601 if ($self->{on_stoptls}) {
1602 $self->{on_stoptls}($self);
1603 return;
1604 } else {
1605 # let's treat SSL-eof as we treat normal EOF
1606 delete $self->{_rw};
1607 $self->{_eof} = 1;
1608 }
1609 }
1610
1611 $self->{_tls_rbuf} .= $tmp;
1612 $self->_drain_rbuf;
1613 $self->{tls} or return; # tls session might have gone away in callback
1614 }
1615
1616 $tmp = Net::SSLeay::get_error ($self->{tls}, -1);
1617 return $self->_tls_error ($tmp)
1618 if $tmp != $ERROR_WANT_READ
1619 && ($tmp != $ERROR_SYSCALL || $!);
1620
1621 while (length ($tmp = Net::SSLeay::BIO_read ($self->{_wbio}))) {
1622 $self->{wbuf} .= $tmp;
1623 $self->_drain_wbuf;
1624 }
1625
1626 $self->{_on_starttls}
1627 and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
1628 and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
1629 }
1630
1631 =item $handle->starttls ($tls[, $tls_ctx])
1632
1633 Instead of starting TLS negotiation immediately when the AnyEvent::Handle
1634 object is created, you can also do that at a later time by calling
1635 C<starttls>.
1636
1637 Starting TLS is currently an asynchronous operation - when you push some
1638 write data and then call C<< ->starttls >> then TLS negotiation will start
1639 immediately, after which the queued write data is then sent.
1640
1641 The first argument is the same as the C<tls> constructor argument (either
1642 C<"connect">, C<"accept"> or an existing Net::SSLeay object).
1643
1644 The second argument is the optional C<AnyEvent::TLS> object that is used
1645 when AnyEvent::Handle has to create its own TLS connection object, or
1646 a hash reference with C<< key => value >> pairs that will be used to
1647 construct a new context.
1648
1649 The TLS connection object will end up in C<< $handle->{tls} >>, the TLS
1650 context in C<< $handle->{tls_ctx} >> after this call and can be used or
1651 changed to your liking. Note that the handshake might have already started
1652 when this function returns.
1653
1654 If it an error to start a TLS handshake more than once per
1655 AnyEvent::Handle object (this is due to bugs in OpenSSL).
1656
1657 =cut
1658
1659 our %TLS_CACHE; #TODO not yet documented, should we?
1660
1661 sub starttls {
1662 my ($self, $ssl, $ctx) = @_;
1663
1664 require Net::SSLeay;
1665
1666 Carp::croak "it is an error to call starttls more than once on an AnyEvent::Handle object"
1667 if $self->{tls};
1668
1669 $ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL ();
1670 $ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ ();
1671
1672 $ctx ||= $self->{tls_ctx};
1673
1674 local $Carp::CarpLevel = 1; # skip ourselves when creating a new context or session
1675
1676 if ("HASH" eq ref $ctx) {
1677 require AnyEvent::TLS;
1678
1679 if ($ctx->{cache}) {
1680 my $key = $ctx+0;
1681 $ctx = $TLS_CACHE{$key} ||= new AnyEvent::TLS %$ctx;
1682 } else {
1683 $ctx = new AnyEvent::TLS %$ctx;
1684 }
1685 }
1686
1687 $self->{tls_ctx} = $ctx || TLS_CTX ();
1688 $self->{tls} = $ssl = $self->{tls_ctx}->_get_session ($ssl, $self, $self->{peername});
1689
1690 # basically, this is deep magic (because SSL_read should have the same issues)
1691 # but the openssl maintainers basically said: "trust us, it just works".
1692 # (unfortunately, we have to hardcode constants because the abysmally misdesigned
1693 # and mismaintained ssleay-module doesn't even offer them).
1694 # http://www.mail-archive.com/openssl-dev@openssl.org/msg22420.html
1695 #
1696 # in short: this is a mess.
1697 #
1698 # note that we do not try to keep the length constant between writes as we are required to do.
1699 # we assume that most (but not all) of this insanity only applies to non-blocking cases,
1700 # and we drive openssl fully in blocking mode here. Or maybe we don't - openssl seems to
1701 # have identity issues in that area.
1702 # Net::SSLeay::CTX_set_mode ($ssl,
1703 # (eval { local $SIG{__DIE__}; Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1)
1704 # | (eval { local $SIG{__DIE__}; Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2));
1705 Net::SSLeay::CTX_set_mode ($ssl, 1|2);
1706
1707 $self->{_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
1708 $self->{_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
1709
1710 Net::SSLeay::set_bio ($ssl, $self->{_rbio}, $self->{_wbio});
1711
1712 $self->{_on_starttls} = sub { $_[0]{on_starttls}(@_) }
1713 if $self->{on_starttls};
1714
1715 &_dotls; # need to trigger the initial handshake
1716 $self->start_read; # make sure we actually do read
1717 }
1718
1719 =item $handle->stoptls
1720
1721 Shuts down the SSL connection - this makes a proper EOF handshake by
1722 sending a close notify to the other side, but since OpenSSL doesn't
1723 support non-blocking shut downs, it is not possible to re-use the stream
1724 afterwards.
1725
1726 =cut
1727
1728 sub stoptls {
1729 my ($self) = @_;
1730
1731 if ($self->{tls}) {
1732 Net::SSLeay::shutdown ($self->{tls});
1733
1734 &_dotls;
1735
1736 # # we don't give a shit. no, we do, but we can't. no...#d#
1737 # # we, we... have to use openssl :/#d#
1738 # &_freetls;#d#
1739 }
1740 }
1741
1742 sub _freetls {
1743 my ($self) = @_;
1744
1745 return unless $self->{tls};
1746
1747 $self->{tls_ctx}->_put_session (delete $self->{tls});
1748
1749 delete @$self{qw(_rbio _wbio _tls_wbuf _on_starttls)};
1750 }
1751
1752 sub DESTROY {
1753 my ($self) = @_;
1754
1755 &_freetls;
1756
1757 my $linger = exists $self->{linger} ? $self->{linger} : 3600;
1758
1759 if ($linger && length $self->{wbuf} && $self->{fh}) {
1760 my $fh = delete $self->{fh};
1761 my $wbuf = delete $self->{wbuf};
1762
1763 my @linger;
1764
1765 push @linger, AnyEvent->io (fh => $fh, poll => "w", cb => sub {
1766 my $len = syswrite $fh, $wbuf, length $wbuf;
1767
1768 if ($len > 0) {
1769 substr $wbuf, 0, $len, "";
1770 } else {
1771 @linger = (); # end
1772 }
1773 });
1774 push @linger, AnyEvent->timer (after => $linger, cb => sub {
1775 @linger = ();
1776 });
1777 }
1778 }
1779
1780 =item $handle->destroy
1781
1782 Shuts down the handle object as much as possible - this call ensures that
1783 no further callbacks will be invoked and as many resources as possible
1784 will be freed. You must not call any methods on the object afterwards.
1785
1786 Normally, you can just "forget" any references to an AnyEvent::Handle
1787 object and it will simply shut down. This works in fatal error and EOF
1788 callbacks, as well as code outside. It does I<NOT> work in a read or write
1789 callback, so when you want to destroy the AnyEvent::Handle object from
1790 within such an callback. You I<MUST> call C<< ->destroy >> explicitly in
1791 that case.
1792
1793 Destroying the handle object in this way has the advantage that callbacks
1794 will be removed as well, so if those are the only reference holders (as
1795 is common), then one doesn't need to do anything special to break any
1796 reference cycles.
1797
1798 The handle might still linger in the background and write out remaining
1799 data, as specified by the C<linger> option, however.
1800
1801 =cut
1802
1803 sub destroy {
1804 my ($self) = @_;
1805
1806 $self->DESTROY;
1807 %$self = ();
1808 }
1809
1810 =item AnyEvent::Handle::TLS_CTX
1811
1812 This function creates and returns the AnyEvent::TLS object used by default
1813 for TLS mode.
1814
1815 The context is created by calling L<AnyEvent::TLS> without any arguments.
1816
1817 =cut
1818
1819 our $TLS_CTX;
1820
1821 sub TLS_CTX() {
1822 $TLS_CTX ||= do {
1823 require AnyEvent::TLS;
1824
1825 new AnyEvent::TLS
1826 }
1827 }
1828
1829 =back
1830
1831
1832 =head1 NONFREQUENTLY ASKED QUESTIONS
1833
1834 =over 4
1835
1836 =item I C<undef> the AnyEvent::Handle reference inside my callback and
1837 still get further invocations!
1838
1839 That's because AnyEvent::Handle keeps a reference to itself when handling
1840 read or write callbacks.
1841
1842 It is only safe to "forget" the reference inside EOF or error callbacks,
1843 from within all other callbacks, you need to explicitly call the C<<
1844 ->destroy >> method.
1845
1846 =item I get different callback invocations in TLS mode/Why can't I pause
1847 reading?
1848
1849 Unlike, say, TCP, TLS connections do not consist of two independent
1850 communication channels, one for each direction. Or put differently. The
1851 read and write directions are not independent of each other: you cannot
1852 write data unless you are also prepared to read, and vice versa.
1853
1854 This can mean than, in TLS mode, you might get C<on_error> or C<on_eof>
1855 callback invocations when you are not expecting any read data - the reason
1856 is that AnyEvent::Handle always reads in TLS mode.
1857
1858 During the connection, you have to make sure that you always have a
1859 non-empty read-queue, or an C<on_read> watcher. At the end of the
1860 connection (or when you no longer want to use it) you can call the
1861 C<destroy> method.
1862
1863 =item How do I read data until the other side closes the connection?
1864
1865 If you just want to read your data into a perl scalar, the easiest way
1866 to achieve this is by setting an C<on_read> callback that does nothing,
1867 clearing the C<on_eof> callback and in the C<on_error> callback, the data
1868 will be in C<$_[0]{rbuf}>:
1869
1870 $handle->on_read (sub { });
1871 $handle->on_eof (undef);
1872 $handle->on_error (sub {
1873 my $data = delete $_[0]{rbuf};
1874 });
1875
1876 The reason to use C<on_error> is that TCP connections, due to latencies
1877 and packets loss, might get closed quite violently with an error, when in
1878 fact, all data has been received.
1879
1880 It is usually better to use acknowledgements when transferring data,
1881 to make sure the other side hasn't just died and you got the data
1882 intact. This is also one reason why so many internet protocols have an
1883 explicit QUIT command.
1884
1885 =item I don't want to destroy the handle too early - how do I wait until
1886 all data has been written?
1887
1888 After writing your last bits of data, set the C<on_drain> callback
1889 and destroy the handle in there - with the default setting of
1890 C<low_water_mark> this will be called precisely when all data has been
1891 written to the socket:
1892
1893 $handle->push_write (...);
1894 $handle->on_drain (sub {
1895 warn "all data submitted to the kernel\n";
1896 undef $handle;
1897 });
1898
1899 If you just want to queue some data and then signal EOF to the other side,
1900 consider using C<< ->push_shutdown >> instead.
1901
1902 =item I want to contact a TLS/SSL server, I don't care about security.
1903
1904 If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS,
1905 simply connect to it and then create the AnyEvent::Handle with the C<tls>
1906 parameter:
1907
1908 tcp_connect $host, $port, sub {
1909 my ($fh) = @_;
1910
1911 my $handle = new AnyEvent::Handle
1912 fh => $fh,
1913 tls => "connect",
1914 on_error => sub { ... };
1915
1916 $handle->push_write (...);
1917 };
1918
1919 =item I want to contact a TLS/SSL server, I do care about security.
1920
1921 Then you should additionally enable certificate verification, including
1922 peername verification, if the protocol you use supports it (see
1923 L<AnyEvent::TLS>, C<verify_peername>).
1924
1925 E.g. for HTTPS:
1926
1927 tcp_connect $host, $port, sub {
1928 my ($fh) = @_;
1929
1930 my $handle = new AnyEvent::Handle
1931 fh => $fh,
1932 peername => $host,
1933 tls => "connect",
1934 tls_ctx => { verify => 1, verify_peername => "https" },
1935 ...
1936
1937 Note that you must specify the hostname you connected to (or whatever
1938 "peername" the protocol needs) as the C<peername> argument, otherwise no
1939 peername verification will be done.
1940
1941 The above will use the system-dependent default set of trusted CA
1942 certificates. If you want to check against a specific CA, add the
1943 C<ca_file> (or C<ca_cert>) arguments to C<tls_ctx>:
1944
1945 tls_ctx => {
1946 verify => 1,
1947 verify_peername => "https",
1948 ca_file => "my-ca-cert.pem",
1949 },
1950
1951 =item I want to create a TLS/SSL server, how do I do that?
1952
1953 Well, you first need to get a server certificate and key. You have
1954 three options: a) ask a CA (buy one, use cacert.org etc.) b) create a
1955 self-signed certificate (cheap. check the search engine of your choice,
1956 there are many tutorials on the net) or c) make your own CA (tinyca2 is a
1957 nice program for that purpose).
1958
1959 Then create a file with your private key (in PEM format, see
1960 L<AnyEvent::TLS>), followed by the certificate (also in PEM format). The
1961 file should then look like this:
1962
1963 -----BEGIN RSA PRIVATE KEY-----
1964 ...header data
1965 ... lots of base64'y-stuff
1966 -----END RSA PRIVATE KEY-----
1967
1968 -----BEGIN CERTIFICATE-----
1969 ... lots of base64'y-stuff
1970 -----END CERTIFICATE-----
1971
1972 The important bits are the "PRIVATE KEY" and "CERTIFICATE" parts. Then
1973 specify this file as C<cert_file>:
1974
1975 tcp_server undef, $port, sub {
1976 my ($fh) = @_;
1977
1978 my $handle = new AnyEvent::Handle
1979 fh => $fh,
1980 tls => "accept",
1981 tls_ctx => { cert_file => "my-server-keycert.pem" },
1982 ...
1983
1984 When you have intermediate CA certificates that your clients might not
1985 know about, just append them to the C<cert_file>.
1986
1987 =back
1988
1989
1990 =head1 SUBCLASSING AnyEvent::Handle
1991
1992 In many cases, you might want to subclass AnyEvent::Handle.
1993
1994 To make this easier, a given version of AnyEvent::Handle uses these
1995 conventions:
1996
1997 =over 4
1998
1999 =item * all constructor arguments become object members.
2000
2001 At least initially, when you pass a C<tls>-argument to the constructor it
2002 will end up in C<< $handle->{tls} >>. Those members might be changed or
2003 mutated later on (for example C<tls> will hold the TLS connection object).
2004
2005 =item * other object member names are prefixed with an C<_>.
2006
2007 All object members not explicitly documented (internal use) are prefixed
2008 with an underscore character, so the remaining non-C<_>-namespace is free
2009 for use for subclasses.
2010
2011 =item * all members not documented here and not prefixed with an underscore
2012 are free to use in subclasses.
2013
2014 Of course, new versions of AnyEvent::Handle may introduce more "public"
2015 member variables, but thats just life, at least it is documented.
2016
2017 =back
2018
2019 =head1 AUTHOR
2020
2021 Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
2022
2023 =cut
2024
2025 1; # End of AnyEvent::Handle