ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Handle.pm
(Generate patch)

Comparing AnyEvent/lib/AnyEvent/Handle.pm (file contents):
Revision 1.4 by elmex, Sun Apr 27 20:20:20 2008 UTC vs.
Revision 1.30 by root, Sat May 24 23:56:26 2008 UTC

1package AnyEvent::Handle; 1package AnyEvent::Handle;
2 2
3use warnings; 3no warnings;
4use strict; 4use strict;
5 5
6use AnyEvent; 6use AnyEvent ();
7use IO::Handle; 7use AnyEvent::Util ();
8use Scalar::Util ();
9use Carp ();
10use Fcntl ();
8use Errno qw/EAGAIN EINTR/; 11use Errno qw/EAGAIN EINTR/;
9 12
10=head1 NAME 13=head1 NAME
11 14
12AnyEvent::Handle - non-blocking I/O on filehandles via AnyEvent 15AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
13 16
14=head1 VERSION 17This module is experimental.
15 18
16Version 0.01
17
18=cut 19=cut
19 20
20our $VERSION = '0.01'; 21our $VERSION = '0.04';
21 22
22=head1 SYNOPSIS 23=head1 SYNOPSIS
23 24
24 use AnyEvent; 25 use AnyEvent;
25 use AnyEvent::Handle; 26 use AnyEvent::Handle;
26 27
27 my $cv = AnyEvent->condvar; 28 my $cv = AnyEvent->condvar;
28 29
29 my $ae_fh = AnyEvent::Handle->new (fh => \*STDIN); 30 my $ae_fh = AnyEvent::Handle->new (fh => \*STDIN);
30 31
31 $ae_fh->on_eof (sub { $cv->broadcast }); 32 #TODO
32
33 $ae_fh->readlines (sub {
34 my ($ae_fh, @lines) = @_;
35 for (@lines) {
36 chomp;
37 print "Line: $_";
38 }
39 });
40 33
41 # or use the constructor to pass the callback: 34 # or use the constructor to pass the callback:
42 35
43 my $ae_fh2 = 36 my $ae_fh2 =
44 AnyEvent::Handle->new ( 37 AnyEvent::Handle->new (
45 fh => \*STDIN, 38 fh => \*STDIN,
46 on_eof => sub { 39 on_eof => sub {
47 $cv->broadcast; 40 $cv->broadcast;
48 }, 41 },
49 on_readline => sub { 42 #TODO
50 my ($ae_fh, @lines) = @_; 43 );
51 for (@lines) { 44
52 chomp; 45 $cv->wait;
53 print "Line: $_"; 46
47=head1 DESCRIPTION
48
49This module is a helper module to make it easier to do event-based I/O on
50filehandles. For utility functions for doing non-blocking connects and accepts
51on sockets see L<AnyEvent::Util>.
52
53In the following, when the documentation refers to of "bytes" then this
54means characters. As sysread and syswrite are used for all I/O, their
55treatment of characters applies to this module as well.
56
57All callbacks will be invoked with the handle object as their first
58argument.
59
60=head1 METHODS
61
62=over 4
63
64=item B<new (%args)>
65
66The constructor supports these arguments (all as key => value pairs).
67
68=over 4
69
70=item fh => $filehandle [MANDATORY]
71
72The filehandle this L<AnyEvent::Handle> object will operate on.
73
74NOTE: The filehandle will be set to non-blocking (using
75AnyEvent::Util::fh_nonblocking).
76
77=item on_eof => $cb->($self)
78
79Set the callback to be called on EOF.
80
81While not mandatory, it is highly recommended to set an eof callback,
82otherwise you might end up with a closed socket while you are still
83waiting for data.
84
85=item on_error => $cb->($self)
86
87This is the fatal error callback, that is called when, well, a fatal error
88occurs, such as not being able to resolve the hostname, failure to connect
89or a read error.
90
91The object will not be in a usable state when this callback has been
92called.
93
94On callback entrance, the value of C<$!> contains the operating system
95error (or C<ENOSPC>, C<EPIPE> or C<EBADMSG>).
96
97While not mandatory, it is I<highly> recommended to set this callback, as
98you will not be notified of errors otherwise. The default simply calls
99die.
100
101=item on_read => $cb->($self)
102
103This sets the default read callback, which is called when data arrives
104and no read request is in the queue.
105
106To access (and remove data from) the read buffer, use the C<< ->rbuf >>
107method or access the C<$self->{rbuf}> member directly.
108
109When an EOF condition is detected then AnyEvent::Handle will first try to
110feed all the remaining data to the queued callbacks and C<on_read> before
111calling the C<on_eof> callback. If no progress can be made, then a fatal
112error will be raised (with C<$!> set to C<EPIPE>).
113
114=item on_drain => $cb->()
115
116This sets the callback that is called when the write buffer becomes empty
117(or when the callback is set and the buffer is empty already).
118
119To append to the write buffer, use the C<< ->push_write >> method.
120
121=item rbuf_max => <bytes>
122
123If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
124when the read buffer ever (strictly) exceeds this size. This is useful to
125avoid denial-of-service attacks.
126
127For example, a server accepting connections from untrusted sources should
128be configured to accept only so-and-so much data that it cannot act on
129(for example, when expecting a line, an attacker could send an unlimited
130amount of data without a callback ever being called as long as the line
131isn't finished).
132
133=item read_size => <bytes>
134
135The default read block size (the amount of bytes this module will try to read
136on each [loop iteration). Default: C<4096>.
137
138=item low_water_mark => <bytes>
139
140Sets the amount of bytes (default: C<0>) that make up an "empty" write
141buffer: If the write reaches this size or gets even samller it is
142considered empty.
143
144=item tls => "accept" | "connect" | Net::SSLeay::SSL object
145
146When this parameter is given, it enables TLS (SSL) mode, that means it
147will start making tls handshake and will transparently encrypt/decrypt
148data.
149
150TLS mode requires Net::SSLeay to be installed (it will be loaded
151automatically when you try to create a TLS handle).
152
153For the TLS server side, use C<accept>, and for the TLS client side of a
154connection, use C<connect> mode.
155
156You can also provide your own TLS connection object, but you have
157to make sure that you call either C<Net::SSLeay::set_connect_state>
158or C<Net::SSLeay::set_accept_state> on it before you pass it to
159AnyEvent::Handle.
160
161See the C<starttls> method if you need to start TLs negotiation later.
162
163=item tls_ctx => $ssl_ctx
164
165Use the given Net::SSLeay::CTX object to create the new TLS connection
166(unless a connection object was specified directly). If this parameter is
167missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>.
168
169=back
170
171=cut
172
173sub new {
174 my $class = shift;
175
176 my $self = bless { @_ }, $class;
177
178 $self->{fh} or Carp::croak "mandatory argument fh is missing";
179
180 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
181
182 if ($self->{tls}) {
183 require Net::SSLeay;
184 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
185 }
186
187 $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof};
188 $self->on_error (delete $self->{on_error}) if $self->{on_error};
189 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
190 $self->on_read (delete $self->{on_read} ) if $self->{on_read};
191
192 $self->start_read;
193
194 $self
195}
196
197sub _shutdown {
198 my ($self) = @_;
199
200 delete $self->{rw};
201 delete $self->{ww};
202 delete $self->{fh};
203}
204
205sub error {
206 my ($self) = @_;
207
208 {
209 local $!;
210 $self->_shutdown;
211 }
212
213 if ($self->{on_error}) {
214 $self->{on_error}($self);
215 } else {
216 Carp::croak "AnyEvent::Handle uncaught fatal error: $!";
217 }
218}
219
220=item $fh = $handle->fh
221
222This method returns the file handle of the L<AnyEvent::Handle> object.
223
224=cut
225
226sub fh { $_[0]->{fh} }
227
228=item $handle->on_error ($cb)
229
230Replace the current C<on_error> callback (see the C<on_error> constructor argument).
231
232=cut
233
234sub on_error {
235 $_[0]{on_error} = $_[1];
236}
237
238=item $handle->on_eof ($cb)
239
240Replace the current C<on_eof> callback (see the C<on_eof> constructor argument).
241
242=cut
243
244sub on_eof {
245 $_[0]{on_eof} = $_[1];
246}
247
248#############################################################################
249
250=back
251
252=head2 WRITE QUEUE
253
254AnyEvent::Handle manages two queues per handle, one for writing and one
255for reading.
256
257The write queue is very simple: you can add data to its end, and
258AnyEvent::Handle will automatically try to get rid of it for you.
259
260When data could be written and the write buffer is shorter then the low
261water mark, the C<on_drain> callback will be invoked.
262
263=over 4
264
265=item $handle->on_drain ($cb)
266
267Sets the C<on_drain> callback or clears it (see the description of
268C<on_drain> in the constructor).
269
270=cut
271
272sub on_drain {
273 my ($self, $cb) = @_;
274
275 $self->{on_drain} = $cb;
276
277 $cb->($self)
278 if $cb && $self->{low_water_mark} >= length $self->{wbuf};
279}
280
281=item $handle->push_write ($data)
282
283Queues the given scalar to be written. You can push as much data as you
284want (only limited by the available memory), as C<AnyEvent::Handle>
285buffers it independently of the kernel.
286
287=cut
288
289sub _drain_wbuf {
290 my ($self) = @_;
291
292 if (!$self->{ww} && length $self->{wbuf}) {
293 Scalar::Util::weaken $self;
294 my $cb = sub {
295 my $len = syswrite $self->{fh}, $self->{wbuf};
296
297 if ($len >= 0) {
298 substr $self->{wbuf}, 0, $len, "";
299
300 $self->{on_drain}($self)
301 if $self->{low_water_mark} >= length $self->{wbuf}
302 && $self->{on_drain};
303
304 delete $self->{ww} unless length $self->{wbuf};
305 } elsif ($! != EAGAIN && $! != EINTR) {
306 $self->error;
307 }
308 };
309
310 $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb);
311
312 $cb->($self);
313 };
314}
315
316our %WH;
317
318sub register_write_type($$) {
319 $WH{$_[0]} = $_[1];
320}
321
322sub push_write {
323 my $self = shift;
324
325 if (@_ > 1) {
326 my $type = shift;
327
328 @_ = ($WH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_write")
329 ->($self, @_);
330 }
331
332 if ($self->{filter_w}) {
333 $self->{filter_w}->($self, \$_[0]);
334 } else {
335 $self->{wbuf} .= $_[0];
336 $self->_drain_wbuf;
337 }
338}
339
340=item $handle->push_write (type => @args)
341
342=item $handle->unshift_write (type => @args)
343
344Instead of formatting your data yourself, you can also let this module do
345the job by specifying a type and type-specific arguments.
346
347Predefined types are (if you have ideas for additional types, feel free to
348drop by and tell us):
349
350=over 4
351
352=item netstring => $string
353
354Formats the given value as netstring
355(http://cr.yp.to/proto/netstrings.txt, this is not a recommendation to use them).
356
357=back
358
359=cut
360
361register_write_type netstring => sub {
362 my ($self, $string) = @_;
363
364 sprintf "%d:%s,", (length $string), $string
365};
366
367=item AnyEvent::Handle::register_write_type type => $coderef->($self, @args)
368
369This function (not method) lets you add your own types to C<push_write>.
370Whenever the given C<type> is used, C<push_write> will invoke the code
371reference with the handle object and the remaining arguments.
372
373The code reference is supposed to return a single octet string that will
374be appended to the write buffer.
375
376Note that this is a function, and all types registered this way will be
377global, so try to use unique names.
378
379=cut
380
381#############################################################################
382
383=back
384
385=head2 READ QUEUE
386
387AnyEvent::Handle manages two queues per handle, one for writing and one
388for reading.
389
390The read queue is more complex than the write queue. It can be used in two
391ways, the "simple" way, using only C<on_read> and the "complex" way, using
392a queue.
393
394In the simple case, you just install an C<on_read> callback and whenever
395new data arrives, it will be called. You can then remove some data (if
396enough is there) from the read buffer (C<< $handle->rbuf >>) if you want
397or not.
398
399In the more complex case, you want to queue multiple callbacks. In this
400case, AnyEvent::Handle will call the first queued callback each time new
401data arrives and removes it when it has done its job (see C<push_read>,
402below).
403
404This way you can, for example, push three line-reads, followed by reading
405a chunk of data, and AnyEvent::Handle will execute them in order.
406
407Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
408the specified number of bytes which give an XML datagram.
409
410 # in the default state, expect some header bytes
411 $handle->on_read (sub {
412 # some data is here, now queue the length-header-read (4 octets)
413 shift->unshift_read_chunk (4, sub {
414 # header arrived, decode
415 my $len = unpack "N", $_[1];
416
417 # now read the payload
418 shift->unshift_read_chunk ($len, sub {
419 my $xml = $_[1];
420 # handle xml
421 });
422 });
423 });
424
425Example 2: Implement a client for a protocol that replies either with
426"OK" and another line or "ERROR" for one request, and 64 bytes for the
427second request. Due tot he availability of a full queue, we can just
428pipeline sending both requests and manipulate the queue as necessary in
429the callbacks:
430
431 # request one
432 $handle->push_write ("request 1\015\012");
433
434 # we expect "ERROR" or "OK" as response, so push a line read
435 $handle->push_read_line (sub {
436 # if we got an "OK", we have to _prepend_ another line,
437 # so it will be read before the second request reads its 64 bytes
438 # which are already in the queue when this callback is called
439 # we don't do this in case we got an error
440 if ($_[1] eq "OK") {
441 $_[0]->unshift_read_line (sub {
442 my $response = $_[1];
443 ...
444 });
445 }
446 });
447
448 # request two
449 $handle->push_write ("request 2\015\012");
450
451 # simply read 64 bytes, always
452 $handle->push_read_chunk (64, sub {
453 my $response = $_[1];
454 ...
455 });
456
457=over 4
458
459=cut
460
461sub _drain_rbuf {
462 my ($self) = @_;
463
464 if (
465 defined $self->{rbuf_max}
466 && $self->{rbuf_max} < length $self->{rbuf}
467 ) {
468 $! = &Errno::ENOSPC; return $self->error;
469 }
470
471 return if $self->{in_drain};
472 local $self->{in_drain} = 1;
473
474 while (my $len = length $self->{rbuf}) {
475 no strict 'refs';
476 if (my $cb = shift @{ $self->{queue} }) {
477 unless ($cb->($self)) {
478 if ($self->{eof}) {
479 # no progress can be made (not enough data and no data forthcoming)
480 $! = &Errno::EPIPE; return $self->error;
54 } 481 }
482
483 unshift @{ $self->{queue} }, $cb;
484 return;
55 } 485 }
56 );
57
58 $cv->wait;
59
60=head1 DESCRIPTION
61
62This module is a helper module to make it easier to do non-blocking I/O
63on filehandles (and sockets, see L<AnyEvent::Socket>).
64
65The event loop is provided by L<AnyEvent>.
66
67=head1 METHODS
68
69=over 4
70
71=item B<new (%args)>
72
73The constructor has these arguments:
74
75=over 4
76
77=item fh => $filehandle
78
79The filehandle this L<AnyEvent::Handle> object will operate on.
80
81NOTE: The filehandle will be set to non-blocking.
82
83=item read_block_size => $size
84
85The default read block size use for reads via the C<on_read>
86method.
87
88=item on_read => $cb
89
90=item on_eof => $cb
91
92=item on_error => $cb
93
94These are shortcuts, that will call the corresponding method and set the callback to C<$cb>.
95
96=item on_readline => $cb
97
98The C<readlines> method is called with the default seperator and C<$cb> as callback
99for you.
100
101=back
102
103=cut
104
105sub new {
106 my $this = shift;
107 my $class = ref($this) || $this;
108 my $self = {
109 read_block_size => 4096,
110 rbuf => '',
111 @_
112 };
113 bless $self, $class;
114
115 $self->{fh}->blocking (0) if $self->{fh};
116
117 if ($self->{on_read}) {
118 $self->on_read ($self->{on_read});
119
120 } elsif ($self->{on_readline}) { 486 } elsif ($self->{on_read}) {
121 $self->readlines ($self->{on_readline}); 487 $self->{on_read}($self);
122 488
489 if (
490 $self->{eof} # if no further data will arrive
491 && $len == length $self->{rbuf} # and no data has been consumed
492 && !@{ $self->{queue} } # and the queue is still empty
493 && $self->{on_read} # and we still want to read data
494 ) {
495 # then no progress can be made
496 $! = &Errno::EPIPE; return $self->error;
497 }
498 } else {
499 # read side becomes idle
500 delete $self->{rw};
501 return;
502 }
503 }
504
123 } elsif ($self->{on_eof}) { 505 if ($self->{eof}) {
124 $self->on_eof ($self->{on_eof}); 506 $self->_shutdown;
125 507 $self->{on_eof}($self)
126 } elsif ($self->{on_error}) { 508 if $self->{on_eof};
127 $self->on_eof ($self->{on_error});
128 } 509 }
129
130 return $self
131} 510}
132 511
133=item B<fh> 512=item $handle->on_read ($cb)
134 513
135This method returns the filehandle of the L<AnyEvent::Handle> object. 514This replaces the currently set C<on_read> callback, or clears it (when
136 515the new callback is C<undef>). See the description of C<on_read> in the
137=cut 516constructor.
138
139sub fh { $_[0]->{fh} }
140
141=item B<on_read ($callback)>
142
143This method installs a C<$callback> that will be called
144when new data arrived. You can access the read buffer via the C<rbuf>
145method (see below).
146
147The first argument of the C<$callback> will be the L<AnyEvent::Handle> object.
148 517
149=cut 518=cut
150 519
151sub on_read { 520sub on_read {
152 my ($self, $cb) = @_; 521 my ($self, $cb) = @_;
522
153 $self->{on_read} = $cb; 523 $self->{on_read} = $cb;
524}
154 525
155 unless (defined $self->{on_read}) { 526=item $handle->rbuf
156 delete $self->{on_read_w}; 527
157 return; 528Returns the read buffer (as a modifiable lvalue).
529
530You can access the read buffer directly as the C<< ->{rbuf} >> member, if
531you want.
532
533NOTE: The read buffer should only be used or modified if the C<on_read>,
534C<push_read> or C<unshift_read> methods are used. The other read methods
535automatically manage the read buffer.
536
537=cut
538
539sub rbuf : lvalue {
540 $_[0]{rbuf}
541}
542
543=item $handle->push_read ($cb)
544
545=item $handle->unshift_read ($cb)
546
547Append the given callback to the end of the queue (C<push_read>) or
548prepend it (C<unshift_read>).
549
550The callback is called each time some additional read data arrives.
551
552It must check whether enough data is in the read buffer already.
553
554If not enough data is available, it must return the empty list or a false
555value, in which case it will be called repeatedly until enough data is
556available (or an error condition is detected).
557
558If enough data was available, then the callback must remove all data it is
559interested in (which can be none at all) and return a true value. After returning
560true, it will be removed from the queue.
561
562=cut
563
564our %RH;
565
566sub register_read_type($$) {
567 $RH{$_[0]} = $_[1];
568}
569
570sub push_read {
571 my $self = shift;
572 my $cb = pop;
573
574 if (@_) {
575 my $type = shift;
576
577 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read")
578 ->($self, $cb, @_);
579 }
580
581 push @{ $self->{queue} }, $cb;
582 $self->_drain_rbuf;
583}
584
585sub unshift_read {
586 my $self = shift;
587 my $cb = pop;
588
589 if (@_) {
590 my $type = shift;
591
592 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
593 ->($self, $cb, @_);
594 }
595
596
597 unshift @{ $self->{queue} }, $cb;
598 $self->_drain_rbuf;
599}
600
601=item $handle->push_read (type => @args, $cb)
602
603=item $handle->unshift_read (type => @args, $cb)
604
605Instead of providing a callback that parses the data itself you can chose
606between a number of predefined parsing formats, for chunks of data, lines
607etc.
608
609Predefined types are (if you have ideas for additional types, feel free to
610drop by and tell us):
611
612=over 4
613
614=item chunk => $octets, $cb->($self, $data)
615
616Invoke the callback only once C<$octets> bytes have been read. Pass the
617data read to the callback. The callback will never be called with less
618data.
619
620Example: read 2 bytes.
621
622 $handle->push_read (chunk => 2, sub {
623 warn "yay ", unpack "H*", $_[1];
158 } 624 });
159 625
160 $self->{on_read_w} = 626=cut
161 AnyEvent->io (poll => 'r', fh => $self->{fh}, cb => sub { 627
162 #d# warn "READ:[$self->{read_size}] $self->{read_block_size} : ".length ($self->{rbuf})."\n"; 628register_read_type chunk => sub {
163 my $rbuf_len = length $self->{rbuf}; 629 my ($self, $cb, $len) = @_;
164 my $l; 630
165 if (defined $self->{read_size}) { 631 sub {
166 $l = sysread $self->{fh}, $self->{rbuf}, 632 $len <= length $_[0]{rbuf} or return;
167 ($self->{read_size} - $rbuf_len), $rbuf_len; 633 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
168 } else { 634 1
169 $l = sysread $self->{fh}, $self->{rbuf}, $self->{read_block_size}, $rbuf_len; 635 }
636};
637
638# compatibility with older API
639sub push_read_chunk {
640 $_[0]->push_read (chunk => $_[1], $_[2]);
641}
642
643sub unshift_read_chunk {
644 $_[0]->unshift_read (chunk => $_[1], $_[2]);
645}
646
647=item line => [$eol, ]$cb->($self, $line, $eol)
648
649The callback will be called only once a full line (including the end of
650line marker, C<$eol>) has been read. This line (excluding the end of line
651marker) will be passed to the callback as second argument (C<$line>), and
652the end of line marker as the third argument (C<$eol>).
653
654The end of line marker, C<$eol>, can be either a string, in which case it
655will be interpreted as a fixed record end marker, or it can be a regex
656object (e.g. created by C<qr>), in which case it is interpreted as a
657regular expression.
658
659The end of line marker argument C<$eol> is optional, if it is missing (NOT
660undef), then C<qr|\015?\012|> is used (which is good for most internet
661protocols).
662
663Partial lines at the end of the stream will never be returned, as they are
664not marked by the end of line marker.
665
666=cut
667
668register_read_type line => sub {
669 my ($self, $cb, $eol) = @_;
670
671 $eol = qr|(\015?\012)| if @_ < 3;
672 $eol = quotemeta $eol unless ref $eol;
673 $eol = qr|^(.*?)($eol)|s;
674
675 sub {
676 $_[0]{rbuf} =~ s/$eol// or return;
677
678 $cb->($_[0], $1, $2);
679 1
680 }
681};
682
683# compatibility with older API
684sub push_read_line {
685 my $self = shift;
686 $self->push_read (line => @_);
687}
688
689sub unshift_read_line {
690 my $self = shift;
691 $self->unshift_read (line => @_);
692}
693
694=item netstring => $cb->($string)
695
696A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
697
698Throws an error with C<$!> set to EBADMSG on format violations.
699
700=cut
701
702register_read_type netstring => sub {
703 my ($self, $cb) = @_;
704
705 sub {
706 unless ($_[0]{rbuf} =~ s/^(0|[1-9][0-9]*)://) {
707 if ($_[0]{rbuf} =~ /[^0-9]/) {
708 $! = &Errno::EBADMSG;
709 $self->error;
170 } 710 }
171 #d# warn "READL $l [$self->{rbuf}]\n"; 711 return;
712 }
172 713
173 if (not defined $l) { 714 my $len = $1;
174 return if $! == EAGAIN || $! == EINTR;
175 $self->{on_error}->($self) if $self->{on_error};
176 delete $self->{on_read_w};
177 715
178 } elsif ($l == 0) { 716 $self->unshift_read (chunk => $len, sub {
179 $self->{on_eof}->($self) if $self->{on_eof}; 717 my $string = $_[1];
180 delete $self->{on_read_w}; 718 $_[0]->unshift_read (chunk => 1, sub {
181 719 if ($_[1] eq ",") {
720 $cb->($_[0], $string);
182 } else { 721 } else {
183 $self->{on_read}->($self); 722 $! = &Errno::EBADMSG;
723 $self->error;
724 }
725 });
726 });
727
728 1
729 }
730};
731
732=back
733
734=item AnyEvent::Handle::register_read_type type => $coderef->($self, $cb, @args)
735
736This function (not method) lets you add your own types to C<push_read>.
737
738Whenever the given C<type> is used, C<push_read> will invoke the code
739reference with the handle object, the callback and the remaining
740arguments.
741
742The code reference is supposed to return a callback (usually a closure)
743that works as a plain read callback (see C<< ->push_read ($cb) >>).
744
745It should invoke the passed callback when it is done reading (remember to
746pass C<$self> as first argument as all other callbacks do that).
747
748Note that this is a function, and all types registered this way will be
749global, so try to use unique names.
750
751For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>,
752search for C<register_read_type>)).
753
754=item $handle->stop_read
755
756=item $handle->start_read
757
758In rare cases you actually do not want to read anything from the
759socket. In this case you can call C<stop_read>. Neither C<on_read> no
760any queued callbacks will be executed then. To start reading again, call
761C<start_read>.
762
763=cut
764
765sub stop_read {
766 my ($self) = @_;
767
768 delete $self->{rw};
769}
770
771sub start_read {
772 my ($self) = @_;
773
774 unless ($self->{rw} || $self->{eof}) {
775 Scalar::Util::weaken $self;
776
777 $self->{rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
778 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf};
779 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
780
781 if ($len > 0) {
782 $self->{filter_r}
783 ? $self->{filter_r}->($self, $rbuf)
784 : $self->_drain_rbuf;
785
786 } elsif (defined $len) {
787 delete $self->{rw};
788 $self->{eof} = 1;
789 $self->_drain_rbuf;
790
791 } elsif ($! != EAGAIN && $! != EINTR) {
792 return $self->error;
184 } 793 }
185 }); 794 });
795 }
186} 796}
187 797
188=item B<on_error ($callback)> 798sub _dotls {
189
190Whenever a read or write operation resulted in an error the C<$callback>
191will be called.
192
193The first argument of C<$callback> will be the L<AnyEvent::Handle> object itself.
194The error is given as errno in C<$!>.
195
196=cut
197
198sub on_error {
199 $_[0]->{on_error} = $_[1];
200}
201
202=item B<on_eof ($callback)>
203
204Installs the C<$callback> that will be called when the end of file is
205encountered in a read operation this C<$callback> will be called. The first
206argument will be the L<AnyEvent::Handle> object itself.
207
208=cut
209
210sub on_eof {
211 $_[0]->{on_eof} = $_[1];
212}
213
214=item B<rbuf>
215
216Returns a reference to the read buffer.
217
218NOTE: The read buffer should only be used or modified if the C<on_read>
219method is used directly. The C<read> and C<readlines> methods will provide
220the read data to their callbacks.
221
222=cut
223
224sub rbuf : lvalue {
225 $_[0]->{rbuf}
226}
227
228=item B<read ($len, $callback)>
229
230Will read exactly C<$len> bytes from the filehandle and call the C<$callback>
231if done so. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
232object itself and the second argument the read data.
233
234NOTE: This method will override any callbacks installed via the C<on_read> method.
235
236=cut
237
238sub read {
239 my ($self, $len, $cb) = @_; 799 my ($self) = @_;
240 800
241 $self->{read_cb} = $cb; 801 if (length $self->{tls_wbuf}) {
242 my $old_blk_size = $self->{read_block_size}; 802 while ((my $len = Net::SSLeay::write ($self->{tls}, $self->{tls_wbuf})) > 0) {
243 $self->{read_block_size} = $len; 803 substr $self->{tls_wbuf}, 0, $len, "";
244
245 $self->on_read (sub {
246 #d# warn "OFOFO $len || ".length($_[0]->{rbuf})."||\n";
247
248 if ($len == length $_[0]->{rbuf}) {
249 $_[0]->{read_block_size} = $old_blk_size;
250 $_[0]->on_read (undef);
251 $_[0]->{read_cb}->($_[0], (substr $self->{rbuf}, 0, $len, ''));
252 } 804 }
805 }
806
807 if (defined (my $buf = Net::SSLeay::BIO_read ($self->{tls_wbio}))) {
808 $self->{wbuf} .= $buf;
809 $self->_drain_wbuf;
810 }
811
812 while (defined (my $buf = Net::SSLeay::read ($self->{tls}))) {
813 $self->{rbuf} .= $buf;
814 $self->_drain_rbuf;
815 }
816
817 my $err = Net::SSLeay::get_error ($self->{tls}, -1);
818
819 if ($err!= Net::SSLeay::ERROR_WANT_READ ()) {
820 if ($err == Net::SSLeay::ERROR_SYSCALL ()) {
821 $self->error;
822 } elsif ($err == Net::SSLeay::ERROR_SSL ()) {
823 $! = &Errno::EIO;
824 $self->error;
825 }
826
827 # all others are fine for our purposes
828 }
829}
830
831=item $handle->starttls ($tls[, $tls_ctx])
832
833Instead of starting TLS negotiation immediately when the AnyEvent::Handle
834object is created, you can also do that at a later time by calling
835C<starttls>.
836
837The first argument is the same as the C<tls> constructor argument (either
838C<"connect">, C<"accept"> or an existing Net::SSLeay object).
839
840The second argument is the optional C<Net::SSLeay::CTX> object that is
841used when AnyEvent::Handle has to create its own TLS connection object.
842
843=cut
844
845# TODO: maybe document...
846sub starttls {
847 my ($self, $ssl, $ctx) = @_;
848
849 $self->stoptls;
850
851 if ($ssl eq "accept") {
852 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
853 Net::SSLeay::set_accept_state ($ssl);
854 } elsif ($ssl eq "connect") {
855 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
856 Net::SSLeay::set_connect_state ($ssl);
857 }
858
859 $self->{tls} = $ssl;
860
861 # basically, this is deep magic (because SSL_read should have the same issues)
862 # but the openssl maintainers basically said: "trust us, it just works".
863 # (unfortunately, we have to hardcode constants because the abysmally misdesigned
864 # and mismaintained ssleay-module doesn't even offer them).
865 # http://www.mail-archive.com/openssl-dev@openssl.org/msg22420.html
866 Net::SSLeay::CTX_set_mode ($self->{tls},
867 (eval { Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1)
868 | (eval { Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2));
869
870 $self->{tls_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
871 $self->{tls_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
872
873 Net::SSLeay::set_bio ($ssl, $self->{tls_rbio}, $self->{tls_wbio});
874
875 $self->{filter_w} = sub {
876 $_[0]{tls_wbuf} .= ${$_[1]};
877 &_dotls;
253 }); 878 };
254} 879 $self->{filter_r} = sub {
255 880 Net::SSLeay::BIO_write ($_[0]{tls_rbio}, ${$_[1]});
256=item B<readlines ($callback)> 881 &_dotls;
257
258=item B<readlines ($sep, $callback)>
259
260This method will read lines from the filehandle, seperated by C<$sep> or C<"\n">
261if C<$sep> is not provided. C<$sep> will be used as part of a regex, so it can be
262a regex itself and won't be quoted!
263
264The C<$callback> will be called when at least one
265line could be read. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
266object itself and the rest of the arguments will be the read lines.
267
268NOTE: This method will override any callbacks installed via the C<on_read> method.
269
270=cut
271
272sub readlines {
273 my ($self, $NL, $cb) = @_;
274
275 if (ref $NL) {
276 $cb = $NL;
277 $NL = "\n";
278 }
279
280 $self->{on_readline} = $cb;
281
282 $self->on_read (sub {
283 my @lines;
284 push @lines, $1 while $_[0]->{rbuf} =~ s/(.*)$NL//;
285 $self->{on_readline}->($_[0], @lines);
286 }); 882 };
287} 883}
288 884
289=item B<write ($data)> 885=item $handle->stoptls
290 886
291=item B<write ($callback)> 887Destroys the SSL connection, if any. Partial read or write data will be
888lost.
292 889
293=item B<write ($data, $callback)>
294
295This method will write C<$data> to the filehandle and call the C<$callback>
296afterwards. If only C<$callback> is provided it will be called when the
297write buffer becomes empty the next time (or immediately if it already is empty).
298
299=cut 890=cut
300 891
301sub write { 892sub stoptls {
302 my ($self, $data, $cb) = @_;
303 if (ref $data) { $cb = $data; undef $data }
304 push @{$self->{write_bufs}}, [$data, $cb];
305 $self->_check_writer;
306}
307
308sub _check_writer {
309 my ($self) = @_; 893 my ($self) = @_;
310 894
311 if ($self->{write_w}) { 895 Net::SSLeay::free (delete $self->{tls}) if $self->{tls};
312 unless ($self->{write_cb}) { 896 delete $self->{tls_rbio};
313 while (@{$self->{write_bufs}} && not defined $self->{write_bufs}->[0]->[1]) { 897 delete $self->{tls_wbio};
314 my $wba = shift @{$self->{write_bufs}}; 898 delete $self->{tls_wbuf};
315 $self->{wbuf} .= $wba->[0]; 899 delete $self->{filter_r};
316 }
317 }
318 return;
319 }
320
321 my $wba = shift @{$self->{write_bufs}}
322 or return;
323
324 unless (defined $wba->[0]) {
325 $wba->[1]->($self) if $wba->[1];
326 $self->_check_writer;
327 return;
328 }
329
330 $self->{wbuf} = $wba->[0];
331 $self->{write_cb} = $wba->[1];
332
333 $self->{write_w} =
334 AnyEvent->io (poll => 'w', fh => $self->{fh}, cb => sub {
335 my $l = syswrite $self->{fh}, $self->{wbuf}, length $self->{wbuf};
336
337 if (not defined $l) {
338 return if $! == EAGAIN || $! == EINTR;
339 delete $self->{write_w}; 900 delete $self->{filter_w};
340 $self->{on_error}->($self) if $self->{on_error}; 901}
341 902
342 } else { 903sub DESTROY {
343 substr $self->{wbuf}, 0, $l, ''; 904 my $self = shift;
344 905
345 if (length ($self->{wbuf}) == 0) { 906 $self->stoptls;
346 $self->{write_cb}->($self) if $self->{write_cb}; 907}
347 908
348 delete $self->{write_w}; 909=item AnyEvent::Handle::TLS_CTX
349 delete $self->{wbuf};
350 delete $self->{write_cb};
351 910
352 $self->_check_writer; 911This function creates and returns the Net::SSLeay::CTX object used by
353 } 912default for TLS mode.
354 } 913
355 }); 914The context is created like this:
915
916 Net::SSLeay::load_error_strings;
917 Net::SSLeay::SSLeay_add_ssl_algorithms;
918 Net::SSLeay::randomize;
919
920 my $CTX = Net::SSLeay::CTX_new;
921
922 Net::SSLeay::CTX_set_options $CTX, Net::SSLeay::OP_ALL
923
924=cut
925
926our $TLS_CTX;
927
928sub TLS_CTX() {
929 $TLS_CTX || do {
930 require Net::SSLeay;
931
932 Net::SSLeay::load_error_strings ();
933 Net::SSLeay::SSLeay_add_ssl_algorithms ();
934 Net::SSLeay::randomize ();
935
936 $TLS_CTX = Net::SSLeay::CTX_new ();
937
938 Net::SSLeay::CTX_set_options ($TLS_CTX, Net::SSLeay::OP_ALL ());
939
940 $TLS_CTX
941 }
356} 942}
357 943
358=back 944=back
359 945
360=head1 AUTHOR 946=head1 AUTHOR
361 947
362Robin Redeker, C<< <elmex at ta-sa.org> >> 948Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
363 949
364=cut 950=cut
365 951
3661; # End of AnyEvent::Handle 9521; # End of AnyEvent::Handle

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines