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.6 by elmex, Mon Apr 28 09:27:47 2008 UTC vs.
Revision 1.28 by root, Sat May 24 22:27:11 2008 UTC

1package AnyEvent::Handle; 1package AnyEvent::Handle;
2 2
3no 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> or C<EPIPE>).
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
173our (%RH, %WH);
174
175sub register_read_type($$) {
176 $RH{$_[0]} = $_[1];
177}
178
179sub register_write_type($$) {
180 $WH{$_[0]} = $_[1];
181}
182
183sub new {
184 my $class = shift;
185
186 my $self = bless { @_ }, $class;
187
188 $self->{fh} or Carp::croak "mandatory argument fh is missing";
189
190 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
191
192 if ($self->{tls}) {
193 require Net::SSLeay;
194 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
195 }
196
197 $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof};
198 $self->on_error (delete $self->{on_error}) if $self->{on_error};
199 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
200 $self->on_read (delete $self->{on_read} ) if $self->{on_read};
201
202 $self->start_read;
203
204 $self
205}
206
207sub _shutdown {
208 my ($self) = @_;
209
210 delete $self->{rw};
211 delete $self->{ww};
212 delete $self->{fh};
213}
214
215sub error {
216 my ($self) = @_;
217
218 {
219 local $!;
220 $self->_shutdown;
221 }
222
223 if ($self->{on_error}) {
224 $self->{on_error}($self);
225 } else {
226 die "AnyEvent::Handle uncaught fatal error: $!";
227 }
228}
229
230=item $fh = $handle->fh
231
232This method returns the file handle of the L<AnyEvent::Handle> object.
233
234=cut
235
236sub fh { $_[0]->{fh} }
237
238=item $handle->on_error ($cb)
239
240Replace the current C<on_error> callback (see the C<on_error> constructor argument).
241
242=cut
243
244sub on_error {
245 $_[0]{on_error} = $_[1];
246}
247
248=item $handle->on_eof ($cb)
249
250Replace the current C<on_eof> callback (see the C<on_eof> constructor argument).
251
252=cut
253
254sub on_eof {
255 $_[0]{on_eof} = $_[1];
256}
257
258#############################################################################
259
260=back
261
262=head2 WRITE QUEUE
263
264AnyEvent::Handle manages two queues per handle, one for writing and one
265for reading.
266
267The write queue is very simple: you can add data to its end, and
268AnyEvent::Handle will automatically try to get rid of it for you.
269
270When data could be written and the write buffer is shorter then the low
271water mark, the C<on_drain> callback will be invoked.
272
273=over 4
274
275=item $handle->on_drain ($cb)
276
277Sets the C<on_drain> callback or clears it (see the description of
278C<on_drain> in the constructor).
279
280=cut
281
282sub on_drain {
283 my ($self, $cb) = @_;
284
285 $self->{on_drain} = $cb;
286
287 $cb->($self)
288 if $cb && $self->{low_water_mark} >= length $self->{wbuf};
289}
290
291=item $handle->push_write ($data)
292
293Queues the given scalar to be written. You can push as much data as you
294want (only limited by the available memory), as C<AnyEvent::Handle>
295buffers it independently of the kernel.
296
297=cut
298
299sub _drain_wbuf {
300 my ($self) = @_;
301
302 unless ($self->{ww}) {
303 Scalar::Util::weaken $self;
304 my $cb = sub {
305 my $len = syswrite $self->{fh}, $self->{wbuf};
306
307 if ($len > 0) {
308 substr $self->{wbuf}, 0, $len, "";
309
310 $self->{on_drain}($self)
311 if $self->{low_water_mark} >= length $self->{wbuf}
312 && $self->{on_drain};
313
314 delete $self->{ww} unless length $self->{wbuf};
315 } elsif ($! != EAGAIN && $! != EINTR) {
316 $self->error;
317 }
318 };
319
320 $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb);
321
322 $cb->($self);
323 };
324}
325
326sub push_write {
327 my $self = shift;
328
329 if ($self->{filter_w}) {
330 $self->{filter_w}->($self, \$_[0]);
331 } else {
332 $self->{wbuf} .= $_[0];
333 $self->_drain_wbuf;
334 }
335}
336
337#############################################################################
338
339=back
340
341=head2 READ QUEUE
342
343AnyEvent::Handle manages two queues per handle, one for writing and one
344for reading.
345
346The read queue is more complex than the write queue. It can be used in two
347ways, the "simple" way, using only C<on_read> and the "complex" way, using
348a queue.
349
350In the simple case, you just install an C<on_read> callback and whenever
351new data arrives, it will be called. You can then remove some data (if
352enough is there) from the read buffer (C<< $handle->rbuf >>) if you want
353or not.
354
355In the more complex case, you want to queue multiple callbacks. In this
356case, AnyEvent::Handle will call the first queued callback each time new
357data arrives and removes it when it has done its job (see C<push_read>,
358below).
359
360This way you can, for example, push three line-reads, followed by reading
361a chunk of data, and AnyEvent::Handle will execute them in order.
362
363Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
364the specified number of bytes which give an XML datagram.
365
366 # in the default state, expect some header bytes
367 $handle->on_read (sub {
368 # some data is here, now queue the length-header-read (4 octets)
369 shift->unshift_read_chunk (4, sub {
370 # header arrived, decode
371 my $len = unpack "N", $_[1];
372
373 # now read the payload
374 shift->unshift_read_chunk ($len, sub {
375 my $xml = $_[1];
376 # handle xml
377 });
378 });
379 });
380
381Example 2: Implement a client for a protocol that replies either with
382"OK" and another line or "ERROR" for one request, and 64 bytes for the
383second request. Due tot he availability of a full queue, we can just
384pipeline sending both requests and manipulate the queue as necessary in
385the callbacks:
386
387 # request one
388 $handle->push_write ("request 1\015\012");
389
390 # we expect "ERROR" or "OK" as response, so push a line read
391 $handle->push_read_line (sub {
392 # if we got an "OK", we have to _prepend_ another line,
393 # so it will be read before the second request reads its 64 bytes
394 # which are already in the queue when this callback is called
395 # we don't do this in case we got an error
396 if ($_[1] eq "OK") {
397 $_[0]->unshift_read_line (sub {
398 my $response = $_[1];
399 ...
400 });
401 }
402 });
403
404 # request two
405 $handle->push_write ("request 2\015\012");
406
407 # simply read 64 bytes, always
408 $handle->push_read_chunk (64, sub {
409 my $response = $_[1];
410 ...
411 });
412
413=over 4
414
415=cut
416
417sub _drain_rbuf {
418 my ($self) = @_;
419
420 if (
421 defined $self->{rbuf_max}
422 && $self->{rbuf_max} < length $self->{rbuf}
423 ) {
424 $! = &Errno::ENOSPC; return $self->error;
425 }
426
427 return if $self->{in_drain};
428 local $self->{in_drain} = 1;
429
430 while (my $len = length $self->{rbuf}) {
431 no strict 'refs';
432 if (my $cb = shift @{ $self->{queue} }) {
433 if (!$cb->($self)) {
434 if ($self->{eof}) {
435 # no progress can be made (not enough data and no data forthcoming)
436 $! = &Errno::EPIPE; return $self->error;
54 } 437 }
438
439 unshift @{ $self->{queue} }, $cb;
440 return;
55 } 441 }
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}) { 442 } elsif ($self->{on_read}) {
121 $self->readlines ($self->{on_readline}); 443 $self->{on_read}($self);
122 444
445 if (
446 $self->{eof} # if no further data will arrive
447 && $len == length $self->{rbuf} # and no data has been consumed
448 && !@{ $self->{queue} } # and the queue is still empty
449 && $self->{on_read} # and we still want to read data
450 ) {
451 # then no progress can be made
452 $! = &Errno::EPIPE; return $self->error;
453 }
454 } else {
455 # read side becomes idle
456 delete $self->{rw};
457 return;
458 }
459 }
460
123 } elsif ($self->{on_eof}) { 461 if ($self->{eof}) {
124 $self->on_eof ($self->{on_eof}); 462 $self->_shutdown;
125 463 $self->{on_eof}($self)
126 } elsif ($self->{on_error}) { 464 if $self->{on_eof};
127 $self->on_eof ($self->{on_error});
128 } 465 }
129
130 return $self
131} 466}
132 467
133=item B<fh> 468=item $handle->on_read ($cb)
134 469
135This method returns the filehandle of the L<AnyEvent::Handle> object. 470This replaces the currently set C<on_read> callback, or clears it (when
136 471the new callback is C<undef>). See the description of C<on_read> in the
137=cut 472constructor.
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 473
149=cut 474=cut
150 475
151sub on_read { 476sub on_read {
152 my ($self, $cb) = @_; 477 my ($self, $cb) = @_;
478
153 $self->{on_read} = $cb; 479 $self->{on_read} = $cb;
480}
154 481
155 unless (defined $self->{on_read}) { 482=item $handle->rbuf
483
484Returns the read buffer (as a modifiable lvalue).
485
486You can access the read buffer directly as the C<< ->{rbuf} >> member, if
487you want.
488
489NOTE: The read buffer should only be used or modified if the C<on_read>,
490C<push_read> or C<unshift_read> methods are used. The other read methods
491automatically manage the read buffer.
492
493=cut
494
495sub rbuf : lvalue {
496 $_[0]{rbuf}
497}
498
499=item $handle->push_read ($cb)
500
501=item $handle->unshift_read ($cb)
502
503Append the given callback to the end of the queue (C<push_read>) or
504prepend it (C<unshift_read>).
505
506The callback is called each time some additional read data arrives.
507
508It must check whether enough data is in the read buffer already.
509
510If not enough data is available, it must return the empty list or a false
511value, in which case it will be called repeatedly until enough data is
512available (or an error condition is detected).
513
514If enough data was available, then the callback must remove all data it is
515interested in (which can be none at all) and return a true value. After returning
516true, it will be removed from the queue.
517
518=cut
519
520sub push_read {
521 my $self = shift;
522 my $cb = pop;
523
524 if (@_) {
525 my $type = shift;
526
527 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::push_read")
528 ->($self, $cb, @_);
529 }
530
531 push @{ $self->{queue} }, $cb;
532 $self->_drain_rbuf;
533}
534
535sub unshift_read {
536 my $self = shift;
537 my $cb = pop;
538
539 if (@_) {
540 my $type = shift;
541
542 $cb = ($RH{$type} or Carp::croak "unsupported type passed to AnyEvent::Handle::unshift_read")
543 ->($self, $cb, @_);
544 }
545
546
547 unshift @{ $self->{queue} }, $cb;
548 $self->_drain_rbuf;
549}
550
551=item $handle->push_read (type => @args, $cb)
552
553=item $handle->unshift_read (type => @args, $cb)
554
555Instead of providing a callback that parses the data itself you can chose
556between a number of predefined parsing formats, for chunks of data, lines
557etc.
558
559The types currently supported are:
560
561=over 4
562
563=item chunk => $octets, $cb->($self, $data)
564
565Invoke the callback only once C<$octets> bytes have been read. Pass the
566data read to the callback. The callback will never be called with less
567data.
568
569Example: read 2 bytes.
570
571 $handle->push_read (chunk => 2, sub {
572 warn "yay ", unpack "H*", $_[1];
573 });
574
575=cut
576
577register_read_type chunk => sub {
578 my ($self, $cb, $len) = @_;
579
580 sub {
581 $len <= length $_[0]{rbuf} or return;
582 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
583 1
584 }
585};
586
587# compatibility with older API
588sub push_read_chunk {
589 $_[0]->push_read (chunk => $_[1], $_[2]);
590}
591
592sub unshift_read_chunk {
593 $_[0]->unshift_read (chunk => $_[1], $_[2]);
594}
595
596=item line => [$eol, ]$cb->($self, $line, $eol)
597
598The callback will be called only once a full line (including the end of
599line marker, C<$eol>) has been read. This line (excluding the end of line
600marker) will be passed to the callback as second argument (C<$line>), and
601the end of line marker as the third argument (C<$eol>).
602
603The end of line marker, C<$eol>, can be either a string, in which case it
604will be interpreted as a fixed record end marker, or it can be a regex
605object (e.g. created by C<qr>), in which case it is interpreted as a
606regular expression.
607
608The end of line marker argument C<$eol> is optional, if it is missing (NOT
609undef), then C<qr|\015?\012|> is used (which is good for most internet
610protocols).
611
612Partial lines at the end of the stream will never be returned, as they are
613not marked by the end of line marker.
614
615=cut
616
617register_read_type line => sub {
618 my ($self, $cb, $eol) = @_;
619
620 $eol = qr|(\015?\012)| if @_ < 3;
621 $eol = quotemeta $eol unless ref $eol;
622 $eol = qr|^(.*?)($eol)|s;
623
624 sub {
625 $_[0]{rbuf} =~ s/$eol// or return;
626
627 $cb->($_[0], $1, $2);
628 1
629 }
630};
631
632# compatibility with older API
633sub push_read_line {
634 my $self = shift;
635 $self->push_read (line => @_);
636}
637
638sub unshift_read_line {
639 my $self = shift;
640 $self->unshift_read (line => @_);
641}
642
643=back
644
645=item $handle->stop_read
646
647=item $handle->start_read
648
649In rare cases you actually do not want to read anything from the
650socket. In this case you can call C<stop_read>. Neither C<on_read> no
651any queued callbacks will be executed then. To start reading again, call
652C<start_read>.
653
654=cut
655
656sub stop_read {
657 my ($self) = @_;
658
156 delete $self->{on_read_w}; 659 delete $self->{rw};
157 return; 660}
158 } 661
159 662sub start_read {
160 $self->{on_read_w} = 663 my ($self) = @_;
161 AnyEvent->io (poll => 'r', fh => $self->{fh}, cb => sub { 664
162 #d# warn "READ:[$self->{read_size}] $self->{read_block_size} : ".length ($self->{rbuf})."\n"; 665 unless ($self->{rw} || $self->{eof}) {
163 my $rbuf_len = length $self->{rbuf}; 666 Scalar::Util::weaken $self;
164 my $l; 667
165 if (defined $self->{read_size}) { 668 $self->{rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
166 $l = sysread $self->{fh}, $self->{rbuf}, 669 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf};
167 ($self->{read_size} - $rbuf_len), $rbuf_len;
168 } else {
169 $l = sysread $self->{fh}, $self->{rbuf}, $self->{read_block_size}, $rbuf_len; 670 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
170 }
171 #d# warn "READL $l [$self->{rbuf}]\n";
172 671
672 if ($len > 0) {
673 $self->{filter_r}
674 ? $self->{filter_r}->($self, $rbuf)
675 : $self->_drain_rbuf;
676
173 if (not defined $l) { 677 } elsif (defined $len) {
174 return if $! == EAGAIN || $! == EINTR;
175 $self->{on_error}->($self) if $self->{on_error};
176 delete $self->{on_read_w}; 678 delete $self->{rw};
679 $self->{eof} = 1;
680 $self->_drain_rbuf;
177 681
178 } elsif ($l == 0) { 682 } elsif ($! != EAGAIN && $! != EINTR) {
179 $self->{on_eof}->($self) if $self->{on_eof}; 683 return $self->error;
180 delete $self->{on_read_w};
181
182 } else {
183 $self->{on_read}->($self);
184 } 684 }
185 }); 685 });
686 }
186} 687}
187 688
188=item B<on_error ($callback)> 689sub _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) = @_; 690 my ($self) = @_;
240 691
241 $self->{read_cb} = $cb; 692 if (length $self->{tls_wbuf}) {
242 my $old_blk_size = $self->{read_block_size}; 693 while ((my $len = Net::SSLeay::write ($self->{tls}, $self->{tls_wbuf})) > 0) {
243 $self->{read_block_size} = $len; 694 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 } 695 }
253 }); 696 }
254}
255 697
256=item B<readlines ($callback)> 698 if (defined (my $buf = Net::SSLeay::BIO_read ($self->{tls_wbio}))) {
257 699 $self->{wbuf} .= $buf;
258=item B<readlines ($sep, $callback)> 700 $self->_drain_wbuf;
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 "line" seperator.
262
263The C<$callback> will be called when at least one
264line could be read. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
265object itself and the rest of the arguments will be the read lines.
266
267NOTE: This method will override any callbacks installed via the C<on_read> method.
268
269=cut
270
271sub readlines {
272 my ($self, $sep, $cb) = @_;
273
274 if (ref $sep) {
275 $cb = $sep;
276 $sep = "\n";
277
278 } elsif (not defined $sep) {
279 $sep = "\n";
280 } 701 }
281 702
282 my $sep_len = length $sep; 703 while (defined (my $buf = Net::SSLeay::read ($self->{tls}))) {
704 $self->{rbuf} .= $buf;
705 $self->_drain_rbuf;
706 }
283 707
284 $self->{on_readline} = $cb; 708 my $err = Net::SSLeay::get_error ($self->{tls}, -1);
285 709
286 $self->on_read (sub { 710 if ($err!= Net::SSLeay::ERROR_WANT_READ ()) {
287 my @lines; 711 if ($err == Net::SSLeay::ERROR_SYSCALL ()) {
288 my $rb = \$_[0]->{rbuf}; 712 $self->error;
289 my $pos; 713 } elsif ($err == Net::SSLeay::ERROR_SSL ()) {
290 while (($pos = index ($$rb, $sep)) >= 0) { 714 $! = &Errno::EIO;
291 push @lines, substr $$rb, 0, $pos + $sep_len, ''; 715 $self->error;
292 } 716 }
293 $self->{on_readline}->($_[0], @lines); 717
718 # all others are fine for our purposes
719 }
720}
721
722=item $handle->starttls ($tls[, $tls_ctx])
723
724Instead of starting TLS negotiation immediately when the AnyEvent::Handle
725object is created, you can also do that at a later time by calling
726C<starttls>.
727
728The first argument is the same as the C<tls> constructor argument (either
729C<"connect">, C<"accept"> or an existing Net::SSLeay object).
730
731The second argument is the optional C<Net::SSLeay::CTX> object that is
732used when AnyEvent::Handle has to create its own TLS connection object.
733
734=cut
735
736# TODO: maybe document...
737sub starttls {
738 my ($self, $ssl, $ctx) = @_;
739
740 $self->stoptls;
741
742 if ($ssl eq "accept") {
743 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
744 Net::SSLeay::set_accept_state ($ssl);
745 } elsif ($ssl eq "connect") {
746 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
747 Net::SSLeay::set_connect_state ($ssl);
748 }
749
750 $self->{tls} = $ssl;
751
752 # basically, this is deep magic (because SSL_read should have the same issues)
753 # but the openssl maintainers basically said: "trust us, it just works".
754 # (unfortunately, we have to hardcode constants because the abysmally misdesigned
755 # and mismaintained ssleay-module doesn't even offer them).
756 # http://www.mail-archive.com/openssl-dev@openssl.org/msg22420.html
757 Net::SSLeay::CTX_set_mode ($self->{tls},
758 (eval { Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1)
759 | (eval { Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2));
760
761 $self->{tls_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
762 $self->{tls_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
763
764 Net::SSLeay::set_bio ($ssl, $self->{tls_rbio}, $self->{tls_wbio});
765
766 $self->{filter_w} = sub {
767 $_[0]{tls_wbuf} .= ${$_[1]};
768 &_dotls;
294 }); 769 };
770 $self->{filter_r} = sub {
771 Net::SSLeay::BIO_write ($_[0]{tls_rbio}, ${$_[1]});
772 &_dotls;
773 };
295} 774}
296 775
297=item B<write ($data)> 776=item $handle->stoptls
298 777
299=item B<write ($callback)> 778Destroys the SSL connection, if any. Partial read or write data will be
779lost.
300 780
301=item B<write ($data, $callback)>
302
303This method will write C<$data> to the filehandle and call the C<$callback>
304afterwards. If only C<$callback> is provided it will be called when the
305write buffer becomes empty the next time (or immediately if it already is empty).
306
307=cut 781=cut
308 782
309sub write { 783sub stoptls {
310 my ($self, $data, $cb) = @_;
311 if (ref $data) { $cb = $data; undef $data }
312 push @{$self->{write_bufs}}, [$data, $cb];
313 $self->_check_writer;
314}
315
316sub _check_writer {
317 my ($self) = @_; 784 my ($self) = @_;
318 785
319 if ($self->{write_w}) { 786 Net::SSLeay::free (delete $self->{tls}) if $self->{tls};
320 unless ($self->{write_cb}) { 787 delete $self->{tls_rbio};
321 while (@{$self->{write_bufs}} && not defined $self->{write_bufs}->[0]->[1]) { 788 delete $self->{tls_wbio};
322 my $wba = shift @{$self->{write_bufs}}; 789 delete $self->{tls_wbuf};
323 $self->{wbuf} .= $wba->[0]; 790 delete $self->{filter_r};
324 }
325 }
326 return;
327 }
328
329 my $wba = shift @{$self->{write_bufs}}
330 or return;
331
332 unless (defined $wba->[0]) {
333 $wba->[1]->($self) if $wba->[1];
334 $self->_check_writer;
335 return;
336 }
337
338 $self->{wbuf} = $wba->[0];
339 $self->{write_cb} = $wba->[1];
340
341 $self->{write_w} =
342 AnyEvent->io (poll => 'w', fh => $self->{fh}, cb => sub {
343 my $l = syswrite $self->{fh}, $self->{wbuf}, length $self->{wbuf};
344
345 if (not defined $l) {
346 return if $! == EAGAIN || $! == EINTR;
347 delete $self->{write_w}; 791 delete $self->{filter_w};
348 $self->{on_error}->($self) if $self->{on_error}; 792}
349 793
350 } else { 794sub DESTROY {
351 substr $self->{wbuf}, 0, $l, ''; 795 my $self = shift;
352 796
353 if (length ($self->{wbuf}) == 0) { 797 $self->stoptls;
354 $self->{write_cb}->($self) if $self->{write_cb}; 798}
355 799
356 delete $self->{write_w}; 800=item AnyEvent::Handle::TLS_CTX
357 delete $self->{wbuf};
358 delete $self->{write_cb};
359 801
360 $self->_check_writer; 802This function creates and returns the Net::SSLeay::CTX object used by
361 } 803default for TLS mode.
362 } 804
363 }); 805The context is created like this:
806
807 Net::SSLeay::load_error_strings;
808 Net::SSLeay::SSLeay_add_ssl_algorithms;
809 Net::SSLeay::randomize;
810
811 my $CTX = Net::SSLeay::CTX_new;
812
813 Net::SSLeay::CTX_set_options $CTX, Net::SSLeay::OP_ALL
814
815=cut
816
817our $TLS_CTX;
818
819sub TLS_CTX() {
820 $TLS_CTX || do {
821 require Net::SSLeay;
822
823 Net::SSLeay::load_error_strings ();
824 Net::SSLeay::SSLeay_add_ssl_algorithms ();
825 Net::SSLeay::randomize ();
826
827 $TLS_CTX = Net::SSLeay::CTX_new ();
828
829 Net::SSLeay::CTX_set_options ($TLS_CTX, Net::SSLeay::OP_ALL ());
830
831 $TLS_CTX
832 }
364} 833}
365 834
366=back 835=back
367 836
368=head1 AUTHOR 837=head1 AUTHOR
369 838
370Robin Redeker, C<< <elmex at ta-sa.org> >> 839Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
371 840
372=cut 841=cut
373 842
3741; # End of AnyEvent::Handle 8431; # End of AnyEvent::Handle

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines