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.1 by elmex, Sun Apr 27 16:56:17 2008 UTC vs.
Revision 1.23 by root, Sat May 24 15:11:22 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
32 #TODO
33
34 # or use the constructor to pass the callback:
35
36 my $ae_fh2 =
37 AnyEvent::Handle->new (
38 fh => \*STDIN,
39 on_eof => sub {
40 $cv->broadcast;
41 },
42 #TODO
43 );
44
45 $cv->wait;
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
150For the TLS server side, use C<accept>, and for the TLS client side of a
151connection, use C<connect> mode.
152
153You can also provide your own TLS connection object, but you have
154to make sure that you call either C<Net::SSLeay::set_connect_state>
155or C<Net::SSLeay::set_accept_state> on it before you pass it to
156AnyEvent::Handle.
157
158=item tls_ctx => $ssl_ctx
159
160Use the given Net::SSLeay::CTX object to create the new TLS connection
161(unless a connection object was specified directly). If this parameter is
162missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>.
163
164=back
165
166=cut
167
168sub new {
169 my $class = shift;
170
171 my $self = bless { @_ }, $class;
172
173 $self->{fh} or Carp::croak "mandatory argument fh is missing";
174
175 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
176
177 if ($self->{tls}) {
178 require Net::SSLeay;
179 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
180 }
181
182 $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof};
183 $self->on_error (delete $self->{on_error}) if $self->{on_error};
184 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
185 $self->on_read (delete $self->{on_read} ) if $self->{on_read};
186
187 $self->start_read;
188
189 $self
190}
191
192sub _shutdown {
193 my ($self) = @_;
194
195 delete $self->{rw};
196 delete $self->{ww};
197 delete $self->{fh};
198}
199
200sub error {
201 my ($self) = @_;
202
203 {
204 local $!;
205 $self->_shutdown;
206 }
207
208 if ($self->{on_error}) {
209 $self->{on_error}($self);
210 } else {
211 die "AnyEvent::Handle uncaught fatal error: $!";
212 }
213}
214
215=item $fh = $handle->fh
216
217This method returns the file handle of the L<AnyEvent::Handle> object.
218
219=cut
220
221sub fh { $_[0]->{fh} }
222
223=item $handle->on_error ($cb)
224
225Replace the current C<on_error> callback (see the C<on_error> constructor argument).
226
227=cut
228
229sub on_error {
230 $_[0]{on_error} = $_[1];
231}
232
233=item $handle->on_eof ($cb)
234
235Replace the current C<on_eof> callback (see the C<on_eof> constructor argument).
236
237=cut
238
239sub on_eof {
240 $_[0]{on_eof} = $_[1];
241}
242
243#############################################################################
244
245=back
246
247=head2 WRITE QUEUE
248
249AnyEvent::Handle manages two queues per handle, one for writing and one
250for reading.
251
252The write queue is very simple: you can add data to its end, and
253AnyEvent::Handle will automatically try to get rid of it for you.
254
255When data could be written and the write buffer is shorter then the low
256water mark, the C<on_drain> callback will be invoked.
257
258=over 4
259
260=item $handle->on_drain ($cb)
261
262Sets the C<on_drain> callback or clears it (see the description of
263C<on_drain> in the constructor).
264
265=cut
266
267sub on_drain {
268 my ($self, $cb) = @_;
269
270 $self->{on_drain} = $cb;
271
272 $cb->($self)
273 if $cb && $self->{low_water_mark} >= length $self->{wbuf};
274}
275
276=item $handle->push_write ($data)
277
278Queues the given scalar to be written. You can push as much data as you
279want (only limited by the available memory), as C<AnyEvent::Handle>
280buffers it independently of the kernel.
281
282=cut
283
284sub _drain_wbuf {
285 my ($self) = @_;
286
287 unless ($self->{ww}) {
288 Scalar::Util::weaken $self;
289 my $cb = sub {
290 my $len = syswrite $self->{fh}, $self->{wbuf};
291
292 if ($len > 0) {
293 substr $self->{wbuf}, 0, $len, "";
294
295 $self->{on_drain}($self)
296 if $self->{low_water_mark} >= length $self->{wbuf}
297 && $self->{on_drain};
298
299 delete $self->{ww} unless length $self->{wbuf};
300 } elsif ($! != EAGAIN && $! != EINTR) {
301 $self->error;
302 }
303 };
304
305 $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb);
306
307 $cb->($self);
308 };
309}
310
311sub push_write {
312 my $self = shift;
313
314 if ($self->{filter_w}) {
315 $self->{filter_w}->($self, \$_[0]);
316 } else {
317 $self->{wbuf} .= $_[0];
318 $self->_drain_wbuf;
319 }
320}
321
322#############################################################################
323
324=back
325
326=head2 READ QUEUE
327
328AnyEvent::Handle manages two queues per handle, one for writing and one
329for reading.
330
331The read queue is more complex than the write queue. It can be used in two
332ways, the "simple" way, using only C<on_read> and the "complex" way, using
333a queue.
334
335In the simple case, you just install an C<on_read> callback and whenever
336new data arrives, it will be called. You can then remove some data (if
337enough is there) from the read buffer (C<< $handle->rbuf >>) if you want
338or not.
339
340In the more complex case, you want to queue multiple callbacks. In this
341case, AnyEvent::Handle will call the first queued callback each time new
342data arrives and removes it when it has done its job (see C<push_read>,
343below).
344
345This way you can, for example, push three line-reads, followed by reading
346a chunk of data, and AnyEvent::Handle will execute them in order.
347
348Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
349the specified number of bytes which give an XML datagram.
350
351 # in the default state, expect some header bytes
352 $handle->on_read (sub {
353 # some data is here, now queue the length-header-read (4 octets)
354 shift->unshift_read_chunk (4, sub {
355 # header arrived, decode
356 my $len = unpack "N", $_[1];
357
358 # now read the payload
359 shift->unshift_read_chunk ($len, sub {
360 my $xml = $_[1];
361 # handle xml
362 });
363 });
364 });
365
366Example 2: Implement a client for a protocol that replies either with
367"OK" and another line or "ERROR" for one request, and 64 bytes for the
368second request. Due tot he availability of a full queue, we can just
369pipeline sending both requests and manipulate the queue as necessary in
370the callbacks:
371
372 # request one
373 $handle->push_write ("request 1\015\012");
374
375 # we expect "ERROR" or "OK" as response, so push a line read
31 $ae_fh->readlines (sub { 376 $handle->push_read_line (sub {
32 my ($ae_fh, @lines) = @_; 377 # if we got an "OK", we have to _prepend_ another line,
33 for (@lines) { 378 # so it will be read before the second request reads its 64 bytes
34 chomp; 379 # which are already in the queue when this callback is called
35 print "Line: $_"; 380 # we don't do this in case we got an error
381 if ($_[1] eq "OK") {
382 $_[0]->unshift_read_line (sub {
383 my $response = $_[1];
384 ...
385 });
36 } 386 }
37 $cv->broadcast;
38 }); 387 });
39 388
40 $cv->wait; 389 # request two
390 $handle->push_write ("request 2\015\012");
41 391
42=head1 DESCRIPTION 392 # simply read 64 bytes, always
43 393 $handle->push_read_chunk (64, sub {
44This module is a helper module to make it easier to do non-blocking I/O 394 my $response = $_[1];
45on filehandles (and sockets, see L<AnyEvent::Socket>). 395 ...
46 396 });
47The event loop is provided by L<AnyEvent>.
48
49=head1 METHODS
50 397
51=over 4 398=over 4
52 399
53=item B<new (%args)>
54
55The constructor has these arguments:
56
57=over 4
58
59=item fh => $filehandle
60
61The filehandle this L<AnyEvent::Handle> object will operate on.
62
63NOTE: The filehandle will be set to non-blocking.
64
65=item read_block_size => $size
66
67The default read block size use for reads via the C<on_read>
68method.
69
70=back
71
72=cut 400=cut
73 401
74sub new { 402sub _drain_rbuf {
75 my $this = shift;
76 my $class = ref($this) || $this;
77 my $self = { 403 my ($self) = @_;
78 read_block_size => 4096, 404
79 rbuf => '', 405 if (
80 @_ 406 defined $self->{rbuf_max}
407 && $self->{rbuf_max} < length $self->{rbuf}
408 ) {
409 $! = &Errno::ENOSPC; return $self->error;
81 }; 410 }
82 bless $self, $class;
83 411
84 $self->{fh}->blocking (0) if $self->{fh}; 412 return if $self->{in_drain};
413 local $self->{in_drain} = 1;
85 414
86 if ($self->{on_read}) { 415 while (my $len = length $self->{rbuf}) {
87 $self->on_read ($self->{on_read}); 416 no strict 'refs';
417 if (my $cb = shift @{ $self->{queue} }) {
418 if (!$cb->($self)) {
419 if ($self->{eof}) {
420 # no progress can be made (not enough data and no data forthcoming)
421 $! = &Errno::EPIPE; return $self->error;
422 }
88 423
424 unshift @{ $self->{queue} }, $cb;
425 return;
426 }
89 } elsif ($self->{on_readline}) { 427 } elsif ($self->{on_read}) {
90 $self->readlines ($self->{on_readline}); 428 $self->{on_read}($self);
91 }
92 429
93 return $self 430 if (
94} 431 $self->{eof} # if no further data will arrive
432 && $len == length $self->{rbuf} # and no data has been consumed
433 && !@{ $self->{queue} } # and the queue is still empty
434 && $self->{on_read} # and we still want to read data
435 ) {
436 # then no progress can be made
437 $! = &Errno::EPIPE; return $self->error;
438 }
439 } else {
440 # read side becomes idle
441 delete $self->{rw};
442 return;
443 }
444 }
95 445
96=item B<fh> 446 if ($self->{eof}) {
447 $self->_shutdown;
448 $self->{on_eof}($self)
449 if $self->{on_eof};
450 }
451}
97 452
98This method returns the filehandle of the L<AnyEvent::Handle> object. 453=item $handle->on_read ($cb)
99 454
100=cut 455This replaces the currently set C<on_read> callback, or clears it (when
101 456the new callback is C<undef>). See the description of C<on_read> in the
102sub fh { $_[0]->{fh} } 457constructor.
103
104=item B<on_read ($callback)>
105
106This method installs a C<$callback> that will be called
107when new data arrived. You can access the read buffer via the C<rbuf>
108method (see below).
109
110The first argument of the C<$callback> will be the L<AnyEvent::Handle> object.
111 458
112=cut 459=cut
113 460
114sub on_read { 461sub on_read {
115 my ($self, $cb) = @_; 462 my ($self, $cb) = @_;
463
116 $self->{on_read} = $cb; 464 $self->{on_read} = $cb;
465}
117 466
118 unless (defined $self->{on_read}) { 467=item $handle->rbuf
468
469Returns the read buffer (as a modifiable lvalue).
470
471You can access the read buffer directly as the C<< ->{rbuf} >> member, if
472you want.
473
474NOTE: The read buffer should only be used or modified if the C<on_read>,
475C<push_read> or C<unshift_read> methods are used. The other read methods
476automatically manage the read buffer.
477
478=cut
479
480sub rbuf : lvalue {
481 $_[0]{rbuf}
482}
483
484=item $handle->push_read ($cb)
485
486=item $handle->unshift_read ($cb)
487
488Append the given callback to the end of the queue (C<push_read>) or
489prepend it (C<unshift_read>).
490
491The callback is called each time some additional read data arrives.
492
493It must check whether enough data is in the read buffer already.
494
495If not enough data is available, it must return the empty list or a false
496value, in which case it will be called repeatedly until enough data is
497available (or an error condition is detected).
498
499If enough data was available, then the callback must remove all data it is
500interested in (which can be none at all) and return a true value. After returning
501true, it will be removed from the queue.
502
503=cut
504
505sub push_read {
506 my ($self, $cb) = @_;
507
508 push @{ $self->{queue} }, $cb;
509 $self->_drain_rbuf;
510}
511
512sub unshift_read {
513 my ($self, $cb) = @_;
514
515 push @{ $self->{queue} }, $cb;
516 $self->_drain_rbuf;
517}
518
519=item $handle->push_read_chunk ($len, $cb->($self, $data))
520
521=item $handle->unshift_read_chunk ($len, $cb->($self, $data))
522
523Append the given callback to the end of the queue (C<push_read_chunk>) or
524prepend it (C<unshift_read_chunk>).
525
526The callback will be called only once C<$len> bytes have been read, and
527these C<$len> bytes will be passed to the callback.
528
529=cut
530
531sub _read_chunk($$) {
532 my ($self, $len, $cb) = @_;
533
534 sub {
535 $len <= length $_[0]{rbuf} or return;
536 $cb->($_[0], substr $_[0]{rbuf}, 0, $len, "");
537 1
538 }
539}
540
541sub push_read_chunk {
542 $_[0]->push_read (&_read_chunk);
543}
544
545
546sub unshift_read_chunk {
547 $_[0]->unshift_read (&_read_chunk);
548}
549
550=item $handle->push_read_line ([$eol, ]$cb->($self, $line, $eol))
551
552=item $handle->unshift_read_line ([$eol, ]$cb->($self, $line, $eol))
553
554Append the given callback to the end of the queue (C<push_read_line>) or
555prepend it (C<unshift_read_line>).
556
557The callback will be called only once a full line (including the end of
558line marker, C<$eol>) has been read. This line (excluding the end of line
559marker) will be passed to the callback as second argument (C<$line>), and
560the end of line marker as the third argument (C<$eol>).
561
562The end of line marker, C<$eol>, can be either a string, in which case it
563will be interpreted as a fixed record end marker, or it can be a regex
564object (e.g. created by C<qr>), in which case it is interpreted as a
565regular expression.
566
567The end of line marker argument C<$eol> is optional, if it is missing (NOT
568undef), then C<qr|\015?\012|> is used (which is good for most internet
569protocols).
570
571Partial lines at the end of the stream will never be returned, as they are
572not marked by the end of line marker.
573
574=cut
575
576sub _read_line($$) {
577 my $self = shift;
578 my $cb = pop;
579 my $eol = @_ ? shift : qr|(\015?\012)|;
580 my $pos;
581
582 $eol = quotemeta $eol unless ref $eol;
583 $eol = qr|^(.*?)($eol)|s;
584
585 sub {
586 $_[0]{rbuf} =~ s/$eol// or return;
587
588 $cb->($_[0], $1, $2);
589 1
590 }
591}
592
593sub push_read_line {
594 $_[0]->push_read (&_read_line);
595}
596
597sub unshift_read_line {
598 $_[0]->unshift_read (&_read_line);
599}
600
601=item $handle->stop_read
602
603=item $handle->start_read
604
605In rare cases you actually do not want to read anything from the
606socket. In this case you can call C<stop_read>. Neither C<on_read> no
607any queued callbacks will be executed then. To start reading again, call
608C<start_read>.
609
610=cut
611
612sub stop_read {
613 my ($self) = @_;
614
119 delete $self->{on_read_w}; 615 delete $self->{rw};
120 return; 616}
121 } 617
122 618sub start_read {
123 $self->{on_read_w} = 619 my ($self) = @_;
124 AnyEvent->io (poll => 'r', fh => $self->{fh}, cb => sub { 620
125 #d# warn "READ:[$self->{read_size}] $self->{read_block_size} : ".length ($self->{rbuf})."\n"; 621 unless ($self->{rw} || $self->{eof}) {
126 my $rbuf_len = length $self->{rbuf}; 622 Scalar::Util::weaken $self;
127 my $l; 623
128 if (defined $self->{read_size}) { 624 $self->{rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
129 $l = sysread $self->{fh}, $self->{rbuf}, 625 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf};
130 ($self->{read_size} - $rbuf_len), $rbuf_len;
131 } else {
132 $l = sysread $self->{fh}, $self->{rbuf}, $self->{read_block_size}, $rbuf_len; 626 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
133 }
134 #d# warn "READL $l [$self->{rbuf}]\n";
135 627
628 if ($len > 0) {
629 $self->{filter_r}
630 ? $self->{filter_r}->($self, $rbuf)
631 : $self->_drain_rbuf;
632
136 if (not defined $l) { 633 } elsif (defined $len) {
137 return if $! == EAGAIN || $! == EINTR;
138 $self->{on_error}->($self, $!) if $self->{on_error};
139 delete $self->{on_read_w}; 634 delete $self->{rw};
635 $self->{eof} = 1;
636 $self->_drain_rbuf;
140 637
141 } elsif ($l == 0) { 638 } elsif ($! != EAGAIN && $! != EINTR) {
142 $self->{on_eof}->($self) if $self->{on_eof}; 639 return $self->error;
143 delete $self->{on_read_w};
144
145 } else {
146 $self->{on_read}->($self);
147 } 640 }
148 }); 641 });
642 }
149} 643}
150 644
151=item B<on_error ($callback)> 645sub _dotls {
152
153Whenever a read or write operation resulted in an error the C<$callback>
154will be called.
155
156The first argument of C<$callback> will be the L<AnyEvent::Handle> object itself
157and the second argument will be the value of C<$!>.
158
159=cut
160
161sub on_error {
162 $_[0]->{on_error} = $_[1];
163}
164
165=item B<on_eof ($callback)>
166
167Installs the C<$callback> that will be called when the end of file is
168encountered in a read operation this C<$callback> will be called. The first
169argument will be the L<AnyEvent::Handle> object itself.
170
171=cut
172
173sub on_eof {
174 $_[0]->{on_eof} = $_[1];
175}
176
177=item B<rbuf>
178
179Returns a reference to the read buffer.
180
181NOTE: The read buffer should only be used or modified if the C<on_read>
182method is used directly. The C<read> and C<readlines> methods will provide
183the read data to their callbacks.
184
185=cut
186
187sub rbuf : lvalue { $_[0]->{rbuf} }
188
189=item B<read ($len, $callback)>
190
191Will read exactly C<$len> bytes from the filehandle and call the C<$callback>
192if done so. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
193object itself and the second argument the read data.
194
195NOTE: This method will override any callbacks installed via the C<on_read> method.
196
197=cut
198
199sub read {
200 my ($self, $len, $cb) = @_; 646 my ($self) = @_;
201 647
202 $self->{read_cb} = $cb; 648 if (length $self->{tls_wbuf}) {
203 my $old_blk_size = $self->{read_block_size}; 649 while ((my $len = Net::SSLeay::write ($self->{tls}, $self->{tls_wbuf})) > 0) {
204 $self->{read_block_size} = $len; 650 substr $self->{tls_wbuf}, 0, $len, "";
205
206 $self->on_read (sub {
207 #d# warn "OFOFO $len || ".length($_[0]->{rbuf})."||\n";
208
209 if ($len == length $_[0]->{rbuf}) {
210 $_[0]->{read_block_size} = $old_blk_size;
211 $_[0]->on_read (undef);
212 $_[0]->{read_cb}->($_[0], (substr $self->{rbuf}, 0, $len, ''));
213 } 651 }
214 }); 652 }
215}
216 653
217=item B<readlines ($callback)> 654 if (defined (my $buf = Net::SSLeay::BIO_read ($self->{tls_wbio}))) {
218 655 $self->{wbuf} .= $buf;
219=item B<readlines ($sep, $callback)> 656 $self->_drain_wbuf;
220
221This method will read lines from the filehandle, seperated by C<$sep> or C<"\n">
222if C<$sep> is not provided. C<$sep> will be used as part of a regex, so it can be
223a regex itself and won't be quoted!
224
225The C<$callback> will be called when at least one
226line could be read. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
227object itself and the rest of the arguments will be the read lines.
228
229NOTE: This method will override any callbacks installed via the C<on_read> method.
230
231=cut
232
233sub readlines {
234 my ($self, $NL, $cb) = @_;
235
236 if (ref $NL) {
237 $cb = $NL;
238 $NL = "\n";
239 }
240
241 $self->{on_readline} = $cb;
242
243 $self->on_read (sub {
244 my @lines;
245 push @lines, $1 while $_[0]->{rbuf} =~ s/(.*)$NL//;
246 $self->{on_readline}->($_[0], @lines);
247 }); 657 }
248}
249 658
250=item B<write ($data)> 659 while (defined (my $buf = Net::SSLeay::read ($self->{tls}))) {
660 $self->{rbuf} .= $buf;
661 $self->_drain_rbuf;
662 }
251 663
252=item B<write ($callback)> 664 if (
253 665 (my $err = Net::SSLeay::get_error ($self->{tls}, -1))
254=item B<write ($data, $callback)> 666 != Net::SSLeay::ERROR_WANT_READ ()
255 667 ) {
256This method will write C<$data> to the filehandle and call the C<$callback> 668 if ($err == Net::SSLeay::ERROR_SYSCALL ()) {
257afterwards. If only C<$callback> is provided it will be called when the 669 $self->error;
258write buffer becomes empty the next time (or immediately if it already is empty). 670 } elsif ($err == Net::SSLeay::ERROR_SSL ()) {
259 671 $! = &Errno::EIO;
260=cut 672 $self->error;
261
262sub write {
263 my ($self, $data, $cb) = @_;
264 if (ref $data) { $cb = $data; undef $data }
265 push @{$self->{write_bufs}}, [$data, $cb];
266 $self->_check_writer;
267}
268
269sub _check_writer {
270 my ($self) = @_;
271
272 if ($self->{write_w}) {
273 unless ($self->{write_cb}) {
274 while (@{$self->{write_bufs}} && not defined $self->{write_bufs}->[0]->[1]) {
275 my $wba = shift @{$self->{write_bufs}};
276 $self->{wbuf} .= $wba->[0];
277 }
278 } 673 }
279 return; 674
675 # all others are fine for our purposes
676 }
677}
678
679# TODO: maybe document...
680sub starttls {
681 my ($self, $ssl, $ctx) = @_;
682
683 if ($ssl eq "accept") {
684 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
685 Net::SSLeay::set_accept_state ($ssl);
686 } elsif ($ssl eq "connect") {
687 $ssl = Net::SSLeay::new ($ctx || TLS_CTX ());
688 Net::SSLeay::set_connect_state ($ssl);
689 }
690
691 $self->{tls} = $ssl;
692
693 # basically, this is deep magic (because SSL_read should have the same issues)
694 # but the openssl maintainers basically said: "trust us, it just works".
695 # (unfortunately, we have to hardcode constants because the abysmally misdesigned
696 # and mismaintained ssleay-module doesn't even offer them).
697 Net::SSLeay::CTX_set_mode ($self->{tls},
698 (eval { Net::SSLeay::MODE_ENABLE_PARTIAL_WRITE () } || 1)
699 | (eval { Net::SSLeay::MODE_ACCEPT_MOVING_WRITE_BUFFER () } || 2));
700
701 $self->{tls_rbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
702 $self->{tls_wbio} = Net::SSLeay::BIO_new (Net::SSLeay::BIO_s_mem ());
703
704 Net::SSLeay::set_bio ($ssl, $self->{tls_rbio}, $self->{tls_wbio});
705
706 $self->{filter_w} = sub {
707 $_[0]{tls_wbuf} .= ${$_[1]};
708 &_dotls;
280 } 709 };
281 710 $self->{filter_r} = sub {
282 my $wba = shift @{$self->{write_bufs}} 711 Net::SSLeay::BIO_write ($_[0]{tls_rbio}, ${$_[1]});
283 or return; 712 &_dotls;
284
285 unless (defined $wba->[0]) {
286 $wba->[1]->($self) if $wba->[1];
287 $self->_check_writer;
288 return;
289 } 713 };
714}
290 715
291 $self->{wbuf} = $wba->[0]; 716sub DESTROY {
292 $self->{write_cb} = $wba->[1]; 717 my $self = shift;
293 718
294 $self->{write_w} = 719 Net::SSLeay::free (delete $self->{tls}) if $self->{tls};
295 AnyEvent->io (poll => 'w', fh => $self->{fh}, cb => sub { 720}
296 my $l = syswrite $self->{fh}, $self->{wbuf}, length $self->{wbuf};
297 721
298 if (not defined $l) { 722=item AnyEvent::Handle::TLS_CTX
299 return if $! == EAGAIN || $! == EINTR;
300 delete $self->{write_w};
301 723
302 $self->{on_error}->($self, $!) if $self->{on_error}; 724This function creates and returns the Net::SSLeay::CTX object used by
725default for TLS mode.
303 726
304 } else { 727The context is created like this:
305 substr $self->{wbuf}, 0, $l, '';
306 728
307 if (length ($self->{wbuf}) == 0) { 729 Net::SSLeay::load_error_strings;
308 $self->{write_cb}->($self) if $self->{write_cb}; 730 Net::SSLeay::SSLeay_add_ssl_algorithms;
731 Net::SSLeay::randomize;
309 732
310 delete $self->{write_w}; 733 my $CTX = Net::SSLeay::CTX_new;
311 delete $self->{wbuf};
312 delete $self->{write_cb};
313 734
314 $self->_check_writer; 735 Net::SSLeay::CTX_set_options $CTX, Net::SSLeay::OP_ALL
315 } 736
316 } 737=cut
317 }); 738
739our $TLS_CTX;
740
741sub TLS_CTX() {
742 $TLS_CTX || do {
743 require Net::SSLeay;
744
745 Net::SSLeay::load_error_strings ();
746 Net::SSLeay::SSLeay_add_ssl_algorithms ();
747 Net::SSLeay::randomize ();
748
749 $TLS_CTX = Net::SSLeay::CTX_new ();
750
751 Net::SSLeay::CTX_set_options ($TLS_CTX, Net::SSLeay::OP_ALL ());
752
753 $TLS_CTX
754 }
318} 755}
319 756
320=back 757=back
321 758
322=head1 AUTHOR 759=head1 AUTHOR
323 760
324Robin Redeker, C<< <elmex at ta-sa.org> >> 761Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
325
326=head1 BUGS
327
328Please report any bugs or feature requests to
329C<bug-io-anyevent at rt.cpan.org>, or through the web interface at
330L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=IO-AnyEvent>.
331I will be notified, and then you'll automatically be notified of progress on
332your bug as I make changes.
333
334=head1 SUPPORT
335
336You can find documentation for this module with the perldoc command.
337
338 perldoc AnyEvent::Handle
339
340You can also look for information at:
341
342=over 4
343
344=item * AnnoCPAN: Annotated CPAN documentation
345
346L<http://annocpan.org/dist/IO-AnyEvent>
347
348=item * CPAN Ratings
349
350L<http://cpanratings.perl.org/d/IO-AnyEvent>
351
352=item * RT: CPAN's request tracker
353
354L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=IO-AnyEvent>
355
356=item * Search CPAN
357
358L<http://search.cpan.org/dist/IO-AnyEvent>
359
360=back
361
362=head1 ACKNOWLEDGEMENTS
363
364=head1 COPYRIGHT & LICENSE
365
366Copyright 2008 Robin Redeker, all rights reserved.
367
368This program is free software; you can redistribute it and/or modify it
369under the same terms as Perl itself.
370 762
371=cut 763=cut
372 764
3731; # End of AnyEvent::Handle 7651; # End of AnyEvent::Handle

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines