EventMux.pm

filter: Statementstmt 55.7% 308 / 553 Branchbran 42.5% 138 / 324 Conditioncond 40.0% 28 / 70 MC/DCmcdc 19.5% 8 / 41 Subroutinesub 64.7% 44 / 68 Podpod 100% 24 / 24 totaltotal 50.9% 550 / 1080 CC 191 SCAR 37.1
CC
191
Cov
50%
connect
93.9
_read_events
92.5
set
90.0
CRAP 41.0
↑ Summary EventMux/Dump.pm »
1 package IO::EventMux;
2 29 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 29 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 29 ▶use Carp qw(carp cluck croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 # TODO: Look into adding queuing support to IO::EventMux:
6  
7 # TODO: Add Timeout option to $mux->add and $mux->connect
8 #
9 # # Try to connect within 10 sec
10 # my $fh = $mux->connect("tcp://127.0.0.1:22", Timeout => 10);
11 # while(my $event = $mux->mux) {
12 # if($event->{fh} eq $fh and $event->{type} eq 'connected') {
13 # print "connected to 127.0.0.1:22 with $event->{fh}\n";
14 #
15 # } elsif($event->{fh} eq $fh and $event->{type} eq 'error') {
16 # print "did not connect to 127.0.0.1:22 because of error: $event->{fh}";
17 #
18 # } elsif($event->{fh} eq $fh and $event->{type} eq 'timeout') {
19 # print "did not connect to 127.0.0.1:22 because of timeout";
20 # }
21 # }
22  
23 # TODO: Add session identifier option to $mux->add for handling udp protocols
24 # where session information is hidden in a packet and not the fh.
25 #
26 # # Using fh and sender as identifier
27 # my $mux->add($fh, Meta => { ... }, MetaHandler => sub {
28 # return $fh.$_[2]; # @_ = ($fh, $packet_data, $sender);
29 # });
30 #
31 # # Using fh and packet data as identifier
32 # my $mux->add($fh, Meta => { ... }, MetaHandler => sub {
33 # return $fh.unpack("N", $_[1]); # @_ = ($fh, $packet_data, $sender);
34 # });
35 #
36 # # Using fh as identifier, default
37 # my $mux->add($fh, Meta => { ... }, MetaHandler => sub {
38 # return $_[0]; # @_ = ($fh, $packet_data, $sender);
39 # });
40 #
41 # while(my $event = $mux->mux) {
42 # my $meta = $mux->meta($event->{id});
43 # }
44 #
45  
46  
47 29 our $VERSION = '2.02';
48  
49 =head1 NAME
50  
51 IO::EventMux - Multiplexer for sockets, pipes and any other types of
52 filehandles that you can set O_NONBLOCK on and does buffering for the user.
53  
54 =head1 SYNOPSIS
55  
56 use IO::EventMux;
57  
58 my $mux = IO::EventMux->new();
59  
60 $mux->add($my_fh);
61  
62 while (1) {
63 my $event = $mux->mux();
64  
65 # ... do something with $event->{type} and $event->{fh}
66 }
67  
68 =head1 DESCRIPTION
69  
70 This module provides multiplexing for any set of sockets, pipes, or whatever
71 you can set O_NONBLOCK on. It can be useful for both server and client
72 processes, but it works best when the application's main loop is centered
73 around its C<mux()> method.
74  
75 The file handles it can work with are either perl's own typeglobs or IO::Handle
76 objects (preferred).
77  
78 =head1 METHODS
79  
80 =cut
81  
82 29 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
83 29 ▶use IO::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
84 29 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
85 29 ▶use IO::Socket::UNIX;
Subroutine BEGIN: called CC=1 SCAR=0.0
86 29 ▶use Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
87 29 ▶use Errno qw(EPROTO ECONNREFUSED ETIMEDOUT EMSGSIZE ECONNREFUSED EHOSTUNREACH
Subroutine BEGIN: called CC=1 SCAR=0.0
88 29 ENETUNREACH EACCES EAGAIN ENOTCONN ECONNRESET EWOULDBLOCK);
89 29 ▶use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
Subroutine BEGIN: called CC=1 SCAR=0.0
90 29 ▶use POSIX qw(strerror);
Subroutine BEGIN: called CC=1 SCAR=0.0
91  
92 29 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
93  
94 # Define EPOLL constants as this needs to be done at compile time
95 29 ▶use constant EPOLLIN => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
96 29 ▶use constant EPOLLOUT => 4;
Subroutine BEGIN: called CC=1 SCAR=0.0
97 29 ▶use constant EPOLLERR => 8;
Subroutine BEGIN: called CC=1 SCAR=0.0
98 29 ▶use constant EPOLLHUP => 16;
Subroutine BEGIN: called CC=1 SCAR=0.0
99 29 ▶use constant EPOLL_CTL_ADD => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
100 29 ▶use constant EPOLL_CTL_DEL => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
101 29 ▶use constant EPOLL_CTL_MOD => 3;
Subroutine BEGIN: called CC=1 SCAR=0.0
102  
103 # Make nice fallback for socket_errors usage
104 0 ▶eval "use IO::EventMux::Socket::MsgHdr qw(socket_errors);"; ## no critic
Subroutine BEGIN: called CC=1 SCAR=1.2
105 29 ▶if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 29 0 29
106 0 ▶ *IO::EventMux::socket_errors = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
107 0 die "You need to install IO::EventMux::Socket::MsgHdr"
108 ." to use the Errors options";
109 29 };
110 }
111  
112 29 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
113 29 SOL_IP => 0,
114 IP_RECVERR => 11,
115 29 };
116  
117 # List of allowed options for add()
118 29 my %allowed_add_opts = map { $_ => 1 } qw(
119 ManualRead ManualWrite ManualAccept
120 ReadSize Buffered Type Errors
121 Meta MetaHandler
122 );
123  
124 =head2 B<new([%options])>
125  
126 Constructs an IO::EventMux object.
127  
128 The optional parameters for the handle will be taken from the IO::EventMux
129 object if not given here:
130  
131 =cut
132  
133 =head3 EventLoop
134  
135 Defines what mechanism to use for the event loop, currently only two build in
136 are available; L<IO::Epoll> and L<IO::Select>. IO::Select being the default.
137  
138 my $mux = new IO::EventMux(EventLoop => [$mechanism, $args]);
139  
140 IO::Epoll example for holding 1024 file handles:
141  
142 my $mux = new IO::EventMux(EventLoop => ["IO::Epoll", 1024]);
143  
144 It's also possible to define your own, this is done by creating a hash that
145 implements the following structure:
146  
147 my $mux = new IO::EventMux(EventLoop => {
148 Add => sub {
149 my($self, $list, $fh) = @_;
150 ...
151 },
152 Wait => sub {
153 my($self, $timeout) = @_;
154 ...
155 return {
156 can_read => [$fh, ...],
157 can_write => [$fh, ...],
158 };
159
160 },
161 Remove => sub {
162 my($self, $list, $fh) = @_;
163 ...
164 },
165 Handles => sub {
166 my($self) = @_;
167 ...
168 },
169 });
170  
171 =cut
172  
173 15 ▶sub new {
Subroutine new: called CC=6 SCAR=30.7
Pod documented
174 15 my ($class, %opts) = @_;
175  
176 #$opts{EventLoop} = ['IO::Epoll', 1024];
177  
178 15 my %eventloopvars;
179 15 ▶ if(my $eventloop = $opts{EventLoop}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $eventloop = $opts{'EventLoop'}) { } 0 15 15
180 # FIXME: Make test for IO::Epoll
181 0 ▶ if(ref $eventloop eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $eventloop eq 'HASH') { } 0 0 0
elsif (ref $eventloop eq 'ARRAY') { } 0 0 0
182 0 *_eventloop_wait = \$eventloop->{Wait};
183 0 *_eventloop_add = \$eventloop->{Add};
184 0 *_eventloop_remove = \$eventloop->{Remove};
185 0 *handles = \$eventloop->{Handles};
186 0 %eventloopvars = %{$eventloop->{Vars}};
187
188 } elsif(ref $eventloop eq 'ARRAY') {
189 0 my ($type, @args) = @{$eventloop};
190  
191 0 ▶ if($type eq 'IO::Epoll') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'IO::Epoll') { } 0 0 0
elsif ($type eq 'IO::Select') { } 0 0 0
192 0 require IO::Epoll;
193 0 *epoll_create = *IO::Epoll::epoll_create;
194 0 *epoll_ctl = *IO::Epoll::epoll_ctl;
195 0 *epoll_wait = *IO::Epoll::epoll_wait;
196
197 0 *_eventloop_wait = *_eventloop_wait_epoll;
198 0 *_eventloop_add = *_eventloop_add_epoll;
199 0 *_eventloop_remove = *_eventloop_remove_epoll;
200 0 *handles = *_eventloop_handles_epoll;
201  
202 0 %eventloopvars = (
203 epollfd => epoll_create($args[0]),
204 fds => {},
205 );
206
207 } elsif($type eq 'IO::Select') {
208 0 goto EVENTLOOP_IO_SOCKET;
209
210 } else {
211 0 croak "Unsupport Eventloop type: $type";
212 }
213
214 } else {
215 0 croak "EventLoop variriable needs to Array or Hash";
216 }
217  
218 } else { #EVENTLOOP_IO_SOCKET:
219 15 *_eventloop_wait = *_eventloop_wait_select;
220 15 *_eventloop_add = *_eventloop_add_select;
221 15 *_eventloop_remove = *_eventloop_remove_select;
222 15 *handles = *_eventloop_handles_select;
223 15 %eventloopvars = (
224 readfh => IO::Select->new(),
225 writefh => IO::Select->new(),
226 );
227 }
228  
229 15 return bless {
230 %eventloopvars,
231  
232 # GLOBAL
233 auto_accept => 1,
234 auto_write => 1,
235 auto_read => 1,
236 auto_close => 1,
237 errors => 0,
238 read_size => 65536,
239
240 fhs => { },
241 sessions => { },
242 listenfh => { },
243
244 events => [ ],
245 actionq => [ ],
246
247 # FH only
248 return_last => 0,
249 type => 'stream',
250 class => 'socket',
251  
252 }, $class;
253 }
254  
255 =head2 B<mux([$timeout])>
256  
257 This method will block until ether an event occurs on one of the file handles
258 or the $timeout (floating point seconds) expires. If the $timeout argument is
259 not present, it waits forever. If $timeout is 0, it returns immediately.
260  
261 The return value is always a hash, which always has the key 'type', indicating
262 what kind it is. It will also usually carry the 'fh' key, indicating what file
263 handle the event happened on.
264  
265 The 'type' key can have the following values:
266  
267 =over
268  
269 =item timeout
270  
271 Nothing happened and timeout occurred.
272  
273 =item error
274  
275 An error occurred in connection with the file handle, such as
276 "connection refused", etc.
277  
278 =item accepted
279  
280 A new client connected to a listening socket and the connection was accepted by
281 EventMux. The listening socket file handle is in the 'parent_fh' key. If the
282 file handle is a unix domain socket the credentials of the user connection will be available in the keys; 'pid', 'uid' and 'gid'.
283  
284 =item ready
285  
286 A file handle is ready to be written to, this can be use full when working with
287 nonblocking connects so you know when the remote connection accepted the
288 connection.
289  
290 =item accepting
291  
292 A new client is trying to connect to a listening socket, but the user code must
293 call accept manually. This only happens when the ManualAccept option is
294 set.
295  
296 =item read
297  
298 A socket has incoming data. If the socket's Buffered option is set, this
299 will be what the buffering rule define.
300  
301 The data is contained in the 'data' key of the event hash. If recv()
302 returned a sender address, it is contained in the 'sender' key and must be
303 manually unpacked according to the socket domain, e.g. with
304 C<Socket::unpack_sockaddr_in()>.
305  
306 =item read_last
307  
308 A socket last data before it was closed did not match the buffering rules, as defined by the IO::Buffered type given. he read_last type contains the result of a call to C<read_last()> on the chosen buffer type.
309  
310 The default is not to return read_last and if no buffer is set read will contain this information.
311  
312 =item sent
313  
314 A socket has sent all the data in it's queue with the send call. This however
315 does not indicate that the data has reached the other end, normally only that
316 the data has reached the local buffer of the kernel.
317  
318 =item closing
319  
320 A file handle was detected to be have been closed by the other end or the file
321 handle was set to be closed by the user. So EventMux stooped listening for
322 events on this file handle. Event data like 'Meta' is still accessible.
323  
324 The 'missing' key indicates the amount of data or packets left in the user
325 space buffer when the file handle was closed. This does not indicate the amount
326 of data received by the other end, only that the user space buffer left.
327  
328 =item closed
329  
330 A socket/pipe was disconnected/closed, the file descriptor, all internal
331 references, and data store with the file handle was removed.
332  
333 =item can_write
334  
335 The ManualWrite option is set for the file handle, and C<select()> has
336 indicated that the handle can be written to.
337  
338 =item can_read
339  
340 The ManualRead option is set for the file handle, and C<select()> has
341 indicated that the handle can be read from.
342  
343 =back
344  
345 =cut
346  
347 19 ▶sub mux {
Subroutine mux: called CC=5 SCAR=16.6
Pod documented
348 19 my ($self,$timeout) = @_;
349 19 my $event;
350  
351 19 ▶ croak "timeout can not be negativ: $timeout"
Branch: 1 branch
BranchTrueFalseTotal
if defined $timeout and $timeout < 0 0 19 19
Condition66%2/3
defined $timeout and $timeout < 0
!ll&&!rl&&r
5140
MC/DC0%0/2
defined $timeout and $timeout < 0
defined $timeout $timeout < 0
Truth table66%2/3
A and B
A= defined $timeoutB= $timeout < 0
ABresult
0X0
100
111
352 if defined $timeout and $timeout < 0;
353  
354 19 ▶ until ($event = shift @{$self->{events}}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($event = shift @{$$self{"events"};}) 13 19 32
355 # actions to execute?
356 13 ▶ if (my $action = shift @{$self->{actionq}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $action = shift @{$$self{'actionq'};}) { } 0 13 13
357 0 $action->($self);
358 } else {
359 13 $self->_get_event($timeout);
360 }
361 }
362
363 19 return $event;
364 }
365  
366 13 ▶sub _get_event {
Subroutine _get_event: called CC=16 SCAR=28.5
367 13 my ($self, $timeout) = @_;
368
369 # TODO: with EPOLL we get fh errors as events, EPOLLERR
370 # use this to be smarter about how we handle them
371 13 my $select = _eventloop_wait($self, $timeout);
372 13 ▶ if(!$select) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($select) 1 12 13
373 1 $self->push_event({ type => 'timeout' });
374 1 return;
375 }
376  
377 # buffers to flush?, can_write is set.
378 12 for my $fh (@{$select->{can_write}}) {
379 10 my $cfg = $self->{fhs}{$fh};
380  
381 10 ▶ if(exists $cfg->{ready} and $cfg->{ready} == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'ready'} and $cfg->{'ready'} == 0) { } 4 6 10
elsif ($self->{'fhs'}{$fh}{'auto_write'}) { } 6 0 6
Condition100%3/3
exists $cfg->{"ready"} and $cfg->{"ready"} == 0
!ll&&!rl&&r
514
MC/DC100%2/2
exists $cfg->{"ready"} and $cfg->{"ready"} == 0
exists $cfg->{"ready"} $cfg->{"ready"} == 0
Truth table100%3/3
A and B
A= exists $cfg->{"ready"}B= $cfg->{"ready"} == 0
ABresult
0X0
100
111
382 4 $cfg->{ready} = 1;
383  
384 4 ▶ if($cfg->{class} eq 'socket') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'class'} eq 'socket') { } 4 0 4
385 4 my $perror = getsockopt($fh, SOL_SOCKET, SO_ERROR);
386 4 ▶ if(defined $perror) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $perror) 4 0 4
387 4 my $error = unpack("i", $perror);
388 4 ▶ if($error == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error == 0) { } 3 1 4
389 3 $self->push_event({ type => 'ready', fh => $fh });
390 } else {
391 1 $self->push_event({ type => 'error', fh => $fh,
392 error => strerror($error),
393 });
394 }
395 }
396
397 } else {
398 0 $self->push_event({ type => 'ready', fh => $fh });
399 }
400  
401 } elsif ($self->{fhs}{$fh}{auto_write}) {
402 6 ▶ if ($cfg->{type} eq "dgram") {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'type'} eq 'dgram') { } 5 1 6
403 5 $self->_send_dgram($fh);
404 } else {
405 1 $self->_send_stream($fh);
406 }
407  
408 } else {
409 0 $self->push_event({ type => 'can_write', fh => $fh });
410 }
411 }
412
413 # incoming data, can_read is set.
414 12 for my $fh (@{$select->{can_read}}) {
415 12 my $cfg = $self->{fhs}{$fh};
416
417 12 ▶ if ($self->{listenfh}{$fh}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'listenfh'}{$fh}) { } 4 8 12
elsif (not $self->{'fhs'}{$fh}{'auto_read'}) { } 0 8 8
418 # new connection
419 4 ▶ if ($cfg->{auto_accept}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'auto_accept'}) { } 4 0 4
420 4 ▶ my $newfh = $fh->accept or next;
Branch: 1 branch
BranchTrueFalseTotal
my $newfh = $fh->accept or next 4 0 4
421
422 4 my %creds;
423 4 ▶ if($cfg->{class} eq 'socket') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"class"} eq "socket") 4 0 4
424 4 %creds = $self->socket_creds($newfh);
425 }
426
427 4 $self->push_event({ type => 'accepted', fh => $newfh,
428 parent_fh => $fh, %creds});
429
430 # Add accepted client to IO::EventMux
431 4 $self->add($newfh, %{$self->{fhs}{$fh}{opts}}, Listen => 0);
432
433 # Set ready as we already sent a connect.
434 4 $self->{fhs}{$newfh}{ready} = 1;
435
436 } else {
437 0 $self->push_event({ type => 'accepting', fh => $fh });
438 }
439  
440 } elsif (!$self->{fhs}{$fh}{auto_read}) {
441 0 $self->push_event({ type => 'can_read', fh => $fh });
442  
443 } else {
444 8 $self->_read_all($fh);
445 }
446 }
447 }
448  
449 0 ▶sub _eventloop_handles_select {
Subroutine _eventloop_handles_select: not called CC=1 SCAR=6.9
450 0 my ($self) = @_;
451 0 return $self->{readfh}->handles;
452 }
453  
454 65 ▶sub _eventloop_add_select {
Subroutine _eventloop_add_select: called CC=1 SCAR=0.0
455 65 my ($self, $list, $fh) = @_;
456 65 $self->{$list}->add($fh);
457 }
458  
459 9 ▶sub _eventloop_remove_select {
Subroutine _eventloop_remove_select: called CC=1 SCAR=0.0
460 9 my ($self, $list, $fh) = @_;
461 9 $self->{$list}->remove($fh);
462 }
463  
464 13 ▶sub _eventloop_wait_select {
Subroutine _eventloop_wait_select: called CC=3 SCAR=11.1
465 13 my ($self, $timeout) = @_;
466  
467 13 $! = 0;
468 # TODO : handle OOB data and exceptions
469 my @result = IO::Select->select($self->{readfh}, $self->{writefh},
470 13 [@{$self->{readfh}}, @{$self->{writefh}}], $timeout);
471
472 #use Data::Dumper; print Dumper({readeble => $result[0], writeble =>
473 # $result[1], exception => $result[2]}) if @result > 0;
474
475 13 ▶ if (@result > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@result > 0) { } 12 1 13
476 return {
477 12 can_read => $result[0],
478 can_write => $result[1],
479 };
480 } else {
481 1 ▶ if ($!) {
Branch: 1 branch
BranchTrueFalseTotal
if ($!) 0 1 1
482 0 die "Died because of error in IO::Select: $!";
483 }
484 1 return;
485 }
486 }
487  
488  
489 0 ▶sub _eventloop_handles_epoll {
Subroutine _eventloop_handles_epoll: not called CC=1 SCAR=6.9
490 0 my ($self) = @_;
491  
492 0 return map { $_->[0] } values %{$self->{fds}};
493 }
494  
495 0 ▶sub _dumpflags {
Subroutine _dumpflags: not called CC=5 SCAR=34.0
496 0 my @flags;
497 0 ▶ push(@flags, "EPOLLIN") if EPOLLIN & $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if 1 & $_[0] 0 0 0
498 0 ▶ push(@flags, "EPOLLOUT") if EPOLLOUT & $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if 4 & $_[0] 0 0 0
499 0 ▶ push(@flags, "EPOLLERR") if EPOLLERR & $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if 8 & $_[0] 0 0 0
500 0 ▶ push(@flags, "EPOLLHUP") if EPOLLHUP & $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if 16 & $_[0] 0 0 0
501 0 return join("|", @flags);
502 }
503  
504 0 ▶sub _eventloop_add_epoll {
Subroutine _eventloop_add_epoll: not called CC=5 SCAR=34.0
505 0 my ($self, $list, $fh) = @_;
506 0 my $fd = fileno $fh;
507 0 $self->{fhs}{$fh}{fd} = $fd;
508  
509 #my ($package, $filename, $line, $subroutine, $hasargs, $wantarray,
510 # $evaltext, $is_require, $hints, $bitmask, $hinthash) = caller(0);
511  
512 0 ▶ my $mask = $list eq 'writefh' ? EPOLLOUT : EPOLLIN;
Branch: 1 branch
BranchTrueFalseTotal
$list eq 'writefh' ? : 0 0 0
513
514 0 $mask |= EPOLLERR|EPOLLHUP;
515  
516 0 ▶ if(my $cfd = $self->{fds}{$fd}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cfd = $self->{'fds'}{$fd}) { } 0 0 0
517 0 $mask |= $cfd->[1];
518 #print "modadd: $package\::$subroutine $line : $fh : "._dumpflags($mask)."\n";
519 0 ▶ epoll_ctl($self->{epollfd}, EPOLL_CTL_MOD, $fd, $mask) >= 0
Branch: 1 branch
BranchTrueFalseTotal
epoll_ctl($self->{"epollfd"}, 3, $fd, $mask) >= 0 or croak(qq[->add($fh, ...) : epoll_ctl($self->{"epollfd"}, ] . "EPOLL_CTL_MOD, $fd, $mask): $!\n") 0 0 0
520 or croak("->add($fh, ...) : epoll_ctl($self->{epollfd}, "
521 ."EPOLL_CTL_MOD, $fd, $mask): $!\n");
522 } else {
523 #print "add: $package\::$subroutine $line : $fh : "._dumpflags($mask)."\n";
524 0 ▶ epoll_ctl($self->{epollfd}, EPOLL_CTL_ADD, $fd, $mask) >= 0
Branch: 1 branch
BranchTrueFalseTotal
epoll_ctl($self->{"epollfd"}, 1, $fd, $mask) >= 0 or croak(qq[->add($fh, ...) : epoll_ctl($self->{"epollfd"}, ] . "EPOLL_CTL_ADD, $fd, $mask): $!\n") 0 0 0
525 or croak("->add($fh, ...) : epoll_ctl($self->{epollfd}, "
526 ."EPOLL_CTL_ADD, $fd, $mask): $!\n");
527 }
528  
529 0 $self->{fds}{$fd} = [$fh, $mask];
530 }
531  
532 0 ▶sub _eventloop_remove_epoll {
Subroutine _eventloop_remove_epoll: not called CC=8 SCAR=42.8
533 0 my ($self, $list, $fh) = @_;
534 0 my $fd = $self->{fhs}{$fh}{fd};
535  
536 #print "$fh -> $fd\n";
537 #use Data::Dumper; print Dumper($self->{fds});
538
539 #my ($package, $filename, $line, $subroutine, $hasargs, $wantarray,
540 # $evaltext, $is_require, $hints, $bitmask, $hinthash) = caller(0);
541
542 0 ▶ my $mask = $list eq 'writefh' ? EPOLLIN : EPOLLOUT;
Branch: 1 branch
BranchTrueFalseTotal
$list eq 'writefh' ? : 0 0 0
543
544 0 $mask |= EPOLLERR|EPOLLHUP;
545
546 0 ▶ if(my $cfd = $self->{fds}{$fd}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cfd = $self->{"fds"}{$fd}) 0 0 0
547 0 ▶ if(($cfd->[1] & EPOLLIN and $cfd->[1] & EPOLLOUT)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($cfd->[1] & 1 and $cfd->[1] & 4) { } 0 0 0
elsif ($cfd->[1] & ($list eq 'writefh' ? 4 : 1)) { } 0 0 0
Condition0%0/3
$cfd->[1] & 1 and $cfd->[1] & 4
!ll&&!rl&&r
000
MC/DC0%0/2
$cfd->[1] & 1 and $cfd->[1] & 4
$cfd->[1] & 1 $cfd->[1] & 4
Truth table0%0/3
A and B
A= $cfd->[1] & 1B= $cfd->[1] & 4
ABresult
0X0
100
111
548 0 $cfd->[1] = $mask;
549 #print "modrem($list): $package\::$subroutine $line : $fh : "._dumpflags($mask)."\n";
550 0 ▶ epoll_ctl($self->{epollfd}, EPOLL_CTL_MOD, $fd, $mask) >= 0
Branch: 1 branch
BranchTrueFalseTotal
epoll_ctl($self->{"epollfd"}, 3, $fd, $mask) >= 0 or croak(qq[->add($fh, ...) : epoll_ctl($self->{"epollfd"}, ] . "EPOLL_CTL_MOD, $fd, EPOLLIN): $!\n") 0 0 0
551 or croak("->add($fh, ...) : epoll_ctl($self->{epollfd}, "
552 ."EPOLL_CTL_MOD, $fd, EPOLLIN): $!\n");
553 ▶ } elsif($cfd->[1] & ($list eq 'writefh' ? EPOLLOUT : EPOLLIN)) {
Branch: 1 branch
BranchTrueFalseTotal
$list eq 'writefh' ? : 0 0 0
554 #print "remove($list): $package\::$subroutine $line : $fh : "._dumpflags($mask)."\n";
555 0 epoll_ctl($self->{epollfd}, EPOLL_CTL_DEL, $fd, 0);
556 0 delete $self->{fds}{$fd};
557 }
558 }
559 }
560  
561  
562 0 ▶sub _eventloop_wait_epoll {
Subroutine _eventloop_wait_epoll: not called CC=8 SCAR=42.8
563 0 my ($self, $timeout) = @_;
564  
565 0 ▶ $timeout = defined $timeout ? $timeout * 1000 : -1;
Branch: 1 branch
BranchTrueFalseTotal
defined $timeout ? : 0 0 0
566  
567 # Max 100 events returned, 1s resolution
568 0 ▶ my $events = epoll_wait($self->{epollfd}, 100, $timeout)
Branch: 1 branch
BranchTrueFalseTotal
my $events = epoll_wait($self->{"epollfd"}, 100, $timeout) or die "Died because of error in epoll_wait: $!" 0 0 0
569 or die "Died because of error in epoll_wait: $!";
570
571 # Return undef if timed out.
572 0 ▶ return if @{$events} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @{$events;} == 0 0 0 0
573  
574 0 my %select;
575 0 foreach my $event (@{$events}) {
576 0 my ($fh) = @{$self->{fds}{$event->[0]}};
577 #print "event: $fh\n";
578 0 ▶ if($event->[1] & EPOLLIN) {
Branch: 3 branches
BranchTrueFalseTotal
if ($event->[1] & 1) { } 0 0 0
elsif ($event->[1] & 4) { } 0 0 0
elsif ($event->[1] & 8 | 16) { } 0 0 0
579 0 push(@{$select{can_read}}, $fh);
580 } elsif($event->[1] & EPOLLOUT) {
581 0 push(@{$select{can_write}}, $fh);
582 } elsif($event->[1] & EPOLLERR|EPOLLHUP) {
583 0 push(@{$select{can_read}}, $fh);
584 }
585 }
586  
587 0 return \%select;
588 }
589  
590  
591 =head2 B<add($handle, [ %options ])>
592  
593 Add a socket to the internal list of handles being watched.
594  
595 The optional parameters for the handle will be taken from the IO::EventMux
596 object if not given here:
597  
598 =head3 Listen
599  
600 Defines if the file handle should be treated as a listening socket, the default
601 is to auto detect this. I should not be necessary to set this value.
602  
603 The socket must be set up for listening, which is easily done with
604 IO::Socket::INET:
605  
606 my $listener = IO::Socket::INET->new(
607 Listen => 5,
608 LocalPort => 7007,
609 ReuseAddr => 1,
610 );
611  
612 $mux->add($listener);
613  
614 =head3 Type
615  
616 Either "stream" or "dgram". Should be auto detected in most cases.
617  
618 Defaults to "stream".
619  
620 =head3 ManualAccept
621  
622 If a connection comes in on a listening socket, it will by default be accepted
623 automatically, and C<mux()> will return a 'connect' event. If ManualAccept is set
624 an 'accepting' event will be returned instead, and the user code must handle it
625 itself.
626  
627 $mux->add($my_fh, ManualAccept => 1);
628  
629 =head3 ManualWrite
630  
631 By default EventMux handles nonblocking writing and you should use
632 C<$mux->send($fh, $data)> or C<$mux->sendto($fh, $addr, $data)> to send your data,
633 but if for some reason you send data yourself you can tell EventMux not to do
634 writing for you and generate a 'can_write' event instead.
635
636 $mux->add($my_fh, ManualWrite => 1);
637  
638 In both cases you can use C<send()> to write data to the file handle.
639  
640 Note: If both ManualRead and ManualWrite is set, EventMux will not set the
641 socket to nonblocking.
642  
643 =head3 ManualRead
644  
645 By default EventMux will handle nonblocking reading and generate a read event
646 with the data, but if some reason you would like to do the reading yourself
647 you can have EventMux generate a 'can_read' event for you instead.
648
649 $mux->add($my_fh, ManualRead => 1);
650  
651 Never read or recv on the file handle. When the socket becomes readable, a
652 C<can_read()> event is returned.
653  
654 Note: If both ManualRead and ManualWrite is set, EventMux will not set the
655 socket to nonblocking.
656  
657 =head3 ReadSize
658  
659 By default IO::EventMux will try to read 65536 bytes from the file handle, setting
660 this options to something smaller might help make it easier for EventMux to be
661 fair about how it returns it's event, but will also give more overhead as more
662 system calls will be required to empty a file handle.
663  
664 =head3 Errors
665  
666 By default IO::EventMux will not deal with socket errors on non connected sockets
667 such as a UDP socket in listening mode or where no peer has been defined. Or
668 in other words whenever you use C<sendto()> on socket. When enabling error
669 handling, IO::EventMux sets the socket to collect errors with the MSG_ERRQUEUE
670 option and collect errors with C<recvmsg()> call.
671  
672 Errors are sent as error events with a little more information than normal, eg:
673  
674 $event = {
675 data => 'packet data',
676 dst_port => 'destination port',
677 from => 'ip where the error is from',
678 dst_ip => 'destination ip',
679 }
680  
681 =head3 Meta
682  
683 An optional scalar piece of metadata for the file handle. Can be retrieved and
684 manipulated later with meta()
685  
686 =head3 Buffered
687  
688 IO::EventMux supports buffering of data before generating events, this can be used to only return events when a "complete" event is done. For this IO::EventMux uses IO::Buffered.
689  
690 # Would only return when a complete line
691 $mux->add($goodfh, Buffered => new IO::Buffered(Split => qr/\n/));
692  
693 Read more here: L<IO::Buffered>
694  
695 =cut
696  
697 36 ▶sub add {
Subroutine add: called CC=32 SCAR=42.0
Pod documented
698 36 my ($self, $fh, %opts) = @_;
699  
700 36 ▶ croak "undefined file handle given" if !defined $fh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fh 0 36 36
701 36 ▶ croak "file handle already added: $fh" if $self->{fhs}{$fh};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"fhs"}{$fh} 0 36 36
702 croak "Buffered is not a IO::Buffered object" if defined $opts{Buffered}
703 and !(blessed($opts{Buffered})
704 36 ▶ and $opts{Buffered}->isa('IO::Buffered'));
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"Buffered"} and not builtin::blessed($opts{"Buffered"}) && $opts{"Buffered"}->isa("IO::Buffered") 0 36 36
Condition16%1/6
defined $opts{"Buffered"} and not builtin::blessed($opts{"Buffered"}) && $opts{"Buffered"}->isa("IO::Buffered")
!ll&&!rl&&r
3600
builtin::blessed($opts{'Buffered'}) && $opts{'Buffered'}->isa('IO::Buffered')
!ll&&!rl&&r
000
MC/DC0%0/3
defined $opts{"Buffered"} and not builtin::blessed($opts{"Buffered"}) && $opts{"Buffered"}->isa("IO::Buffered")
defined $opts{"Buffered"} builtin::blessed($opts{'Buffered'}) $opts{'Buffered'}->isa('IO::Buffered')
Truth table25%1/4
A and not(B && C)
A= defined $opts{"Buffered"}B= builtin::blessed($opts{'Buffered'})C= $opts{'Buffered'}->isa('IO::Buffered')
ABCresult
0XX0
1110
10X1
1101
705 croak "MetaHandler is not a code ref" if defined $opts{MetaHandler}
706 36 ▶ and !(ref $opts{MetaHandler} eq 'CODE');
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"MetaHandler"} and not ref $opts{"MetaHandler"} eq "CODE" 0 36 36
Condition33%1/3
defined $opts{"MetaHandler"} and not ref $opts{"MetaHandler"} eq "CODE"
!ll&&!rl&&r
3600
MC/DC0%0/2
defined $opts{"MetaHandler"} and not ref $opts{"MetaHandler"} eq "CODE"
defined $opts{"MetaHandler"} not ref $opts{"MetaHandler"} eq "CODE"
Truth table33%1/3
A and not(B)
A= defined $opts{"MetaHandler"}B= not ref $opts{"MetaHandler"} eq "CODE"
ABresult
0X0
100
111
707  
708 # Init for new fh
709 $self->{fhs}{$fh} = {
710 errors => (exists $opts{Errors} ? $opts{Errors} : $self->{errors}),
711 type => 'stream',
712 auto_accept => (exists $opts{ManualAccept} ? !$opts{ManualAccept}
713 : $self->{auto_accept}),
714 auto_write => (exists $opts{ManualWrite} ? !$opts{ManualWrite}
715 : $self->{auto_write}),
716 auto_read => (exists $opts{ManualRead} ? !$opts{ManualRead}
717 : $self->{auto_read}),
718 read_size => (exists $opts{ReadSize} ? $opts{ReadSize}
719 : $self->{read_size}),
720 # Save %opts, so we can given it to $fh->accept() children.
721 opts => \%opts,
722 inbuffer => (defined $opts{Buffered} ? $opts{Buffered} : undef),
723 36 ▶ meta_handler => (exists $opts{MetaHandler} ? $opts{MetaHandler} : undef),
Branch: 7 branches
BranchTrueFalseTotal
exists $opts{'Errors'} ? : 1 35 36
exists $opts{'ManualAccept'} ? : 0 36 36
exists $opts{'ManualWrite'} ? : 0 36 36
exists $opts{'ManualRead'} ? : 0 36 36
exists $opts{'ReadSize'} ? : 0 36 36
defined $opts{'Buffered'} ? : 0 36 36
exists $opts{'MetaHandler'} ? : 0 36 36
724 mode => 'normal',
725 };
726
727 # Set the initial session/Meta information
728 36 ▶ if(exists $opts{Meta}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"Meta"}) 0 36 36
729 0 $self->{sessions}{$fh} = $opts{Meta};
730 }
731  
732 36 my $cfg = $self->{fhs}{$fh};
733  
734 # Check if we can set the socket nonblocking
735 36 ▶ if($cfg->{auto_read} or $cfg->{auto_write} or $opts{Listen}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"auto_read"} or $cfg->{"auto_write"} or $opts{"Listen"}) 36 0 36
Condition33%2/6
$cfg->{"auto_read"} or $cfg->{"auto_write"} or $opts{"Listen"}
l!l&&r!l&&!r
3600
$cfg->{"auto_read"} or $cfg->{"auto_write"}
l!l&&r!l&&!r
3600
MC/DC0%0/3
$cfg->{"auto_read"} or $cfg->{"auto_write"} or $opts{"Listen"}
$cfg->{"auto_read"} $cfg->{"auto_write"} $opts{"Listen"}
Truth table25%1/4
A or B or C
A= $cfg->{"auto_read"}B= $cfg->{"auto_write"}C= $opts{"Listen"}
ABCresult
1XX1
01X1
0011
0000
736 36 $self->nonblock($fh);
737 }
738
739 # Check if it's a socket and what the type is
740 36 ▶ if(my $type = $self->socket_type($fh)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $self->socket_type($fh)) { } 35 1 36
741 35 $cfg->{class} = 'socket';
742 35 $cfg->{type} = $type;
743
744 35 ▶ if($self->socket_listening($fh)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->socket_listening($fh)) 7 28 35
745 7 $self->{listenfh}{$fh} = 1;
746 }
747  
748 } else {
749 1 $cfg->{class} = 'other';
750 }
751
752 # Override what has been detected
753 36 ▶ $self->{listenfh}{$fh} = 1 if $opts{Listen};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"Listen"} 2 34 36
754 36 ▶ $cfg->{type} = $opts{Type} if exists $opts{Type};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"Type"} 0 36 36
755  
756 36 ▶ if($cfg->{type} eq 'stream') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'type'} eq 'stream') { } 19 17 36
757 # Return a ready event by creating ready option
758 19 $cfg->{ready} = 0;
759  
760 # Use string out buffer for stream
761 19 $cfg->{outbuffer} = '';
762  
763 19 ▶ if($cfg->{inbuffer}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"inbuffer"}) 0 19 19
764 # Should an event of read_last be returned for this buffer type
765 0 $cfg->{return_last} = $opts{Buffered}->returns_last();
766 }
767  
768 } else {
769 17 ▶ croak "Can't use Buffered for dgram file handles" if $cfg->{inbuffer};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"inbuffer"} 0 17 17
770
771 # Set socket to recieve errors
772 17 ▶ setsockopt($fh, SOL_IP, IP_RECVERR, 1) if $cfg->{errors};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"errors"} 1 16 17
773
774 # Use array out buffer for dgram
775 17 @{$cfg->{outbuffer}} = ();
776 }
777  
778 36 ▶ if (!exists $self->{listenfh}{$fh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"listenfh"}{$fh}) 29 7 36
779 29 _eventloop_add($self, "writefh",$fh);
780 }
781 36 _eventloop_add($self, "readfh", $fh);
782  
783 # Find out if this object has it's own recv() function else use sysread()
784 36 ▶ if (blessed($fh) && $fh->can('recv')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($fh) and $fh->can('recv')) { } 33 3 36
Condition66%2/3
builtin::blessed($fh) and $fh->can("recv")
!ll&&!rl&&r
3033
MC/DC50%1/2
builtin::blessed($fh) and $fh->can("recv")
builtin::blessed($fh) $fh->can("recv")
Truth table66%2/3
A and B
A= builtin::blessed($fh)B= $fh->can("recv")
ABresult
0X0
100
111
785 9 ▶ $cfg->{read} = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
786 9 my ($fh, $readsize, $flags) = @_;
787 9 my $data = '';
788 9 ▶ my $sender = $fh->recv($data, $readsize, ($flags or 0));
Condition50%1/2
$flags || 0
l!l
09
MC/DC0%0/1
$flags || 0
$flags
Truth table50%1/2
A
A= $flags
Aresult
11
00
789 9 ▶ croak $! if !defined $sender;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sender 2 7 9
790 7 ▶ return (($sender or undef), $data);
Condition100%2/2
$sender || undef
l!l
52
MC/DC100%1/1
$sender || undef
$sender
Truth table100%2/2
A
A= $sender
Aresult
11
00
791 33 };
792
793 } else {
794 0 ▶ $cfg->{read} = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
795 0 my ($fh, $readsize, $flags) = @_;
796 0 my $data = '';
797 0 my $rv = sysread($fh, $data, $readsize);
798 0 ▶ croak $! if !defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 0 0 0
799 0 return(undef, $data);
800 3 };
801
802 }
803  
804 # Find out if this object has it's own send() function else use syswrite()
805 36 ▶ if(blessed($fh) && $fh->can('send')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($fh) and $fh->can('send')) { } 33 3 36
Condition66%2/3
builtin::blessed($fh) and $fh->can("send")
!ll&&!rl&&r
3033
MC/DC50%1/2
builtin::blessed($fh) and $fh->can("send")
builtin::blessed($fh) $fh->can("send")
Truth table66%2/3
A and B
A= builtin::blessed($fh)B= $fh->can("send")
ABresult
0X0
100
111
806 4 ▶ $cfg->{write} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
807 4 my ($fh, $data, @to) = @_;
808 4 my $rv = $fh->send($data, 0, @to);
809 4 ▶ croak $! if !defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 1 3 4
810 3 return $rv;
811 }
812 33 } else {
813 0 ▶ $cfg->{write} = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
814 0 my ($fh, $data) = @_;
815 0 my $rv = syswrite($fh, $data);
816 0 ▶ croak $! if !defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 0 0 0
817 0 return $rv;
818 }
819 3 }
820 }
821  
822  
823 =head2 B<listen()>
824  
825 Wrapper around connect() with option (Listen => SOMAXCONN) set
826  
827 =cut
828  
829 4 ▶sub listen {
Subroutine listen: called CC=2 SCAR=6.9
Pod documented
830 4 my ($self) = shift;
831  
832 # Put Listen first in argument list so the user can override it
833 4 ▶ if(@_ % 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ % 2) { } 2 2 4
834 2 my ($url, %opts) = @_;
835 2 $self->connect($url, Listen => SOMAXCONN, %opts);
836 } else {
837 2 my (%opts) = @_;
838 2 $self->connect(Listen => SOMAXCONN, %opts);
839 }
840 }
841  
842 =head2 B<connect()>
843  
844 Connect and add a socket to IO::EventMux, by using either URL syntax or
845 IO::Socket Syntax. All options related to IO::EventMux is passed when calling
846 add() on the new socket. Connect returns the new socket on completion.
847  
848 URL Syntax supports this format:
849  
850 * (tcp|udp)://HOST:PORT, Returns a udp of tcp socket.
851 * (unix|unix_dgram)://path/file.sock, Returns a unix domain socket connection.
852  
853 For more information on how to use IO::Socket syntax look in
854 L<IO::Socket::INET> and L<IO::Socket::UNIX>.
855  
856 Example of URL syntax; making a connection to localhost port 22
857  
858 my $fh = $mux->connect("tcp://127.0.0.1:22");
859  
860 Example of the same thing in IO::Socket Syntax;
861
862 my $fh = $mux->connect(
863 Proto => 'tcp',
864 PeerAddr => '127.0.0.1',
865 PeerPort => 22,
866 );
867  
868 =cut
869  
870 8 ▶sub connect {
Subroutine connect: called CC=29 SCAR=45.4
Pod documented
871 8 my ($self) = shift;
872 8 ▶ croak "no arguments given" if @_ == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 0 8 8
873
874 # Check if we called with url_connect or IO::Socket syntax
875 8 ▶ if(@_ % 2) { # url_connect
Branch: 1 branch
BranchTrueFalseTotal
if (@_ % 2) { } 4 4 8
876 4 my ($url, %opts) = @_;
877 4 ▶ croak "url not defined" if !defined $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url 0 4 4
878
879 # FIXME: Use Misc::Regexp
880 4 ▶ if ($url =~ m{^(tcp|udp)://(\d+\.\d+\.\d+\.\d+):(\d+)$}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($url =~ m[^(tcp|udp)://(\d+\.\d+\.\d+\.\d+):(\d+)$]) { } 4 0 4
elsif ($url =~ m[^unix(?:_(dgram))?://(.+)$]) { } 0 0 0
881 4 my ($proto, $ip, $port) = ($1, $2, $3);
882
883 my %sopts = (
884 Proto => $proto,
885 Type => ($proto eq 'tcp' ? SOCK_STREAM : SOCK_DGRAM),
886 Blocking => 0,
887 4 ▶ ($opts{Listen} ?(Listen => $opts{Listen}):()),
Branch: 2 branches
BranchTrueFalseTotal
$proto eq 'tcp' ? : 2 2 4
$opts{'Listen'} ? : 2 2 4
888 );
889  
890 4 my $fh;
891 4 ▶ if($opts{Listen}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'Listen'}) { } 2 2 4
892 # Only TCP supports the Listen option
893 2 ▶ delete $sopts{Listen} if $proto eq 'udp';
Branch: 1 branch
BranchTrueFalseTotal
if $proto eq "udp" 1 1 2
894 2 ▶ delete $opts{Listen} if $proto eq 'udp';
Branch: 1 branch
BranchTrueFalseTotal
if $proto eq "udp" 1 1 2
895
896 2 ▶ $fh = IO::Socket::INET->new(
Branch: 3 branches
BranchTrueFalseTotal
$fh = "IO::Socket::INET"->new($ip ? ("LocalAddr", $ip) : (), $port ? ("LocalPort", $port) : (), "ReuseAddr", 1, %sopts) or croak("Listening to ${url}: $!") 2 0 2
$ip ? : 2 0 2
$port ? : 2 0 2
897 ($ip?(LocalAddr => $ip):()),
898 ($port?(LocalPort => $port):()),
899 ReuseAddr => 1,
900 %sopts,
901 ) or croak "Listening to $url: $!";
902
903 } else {
904 2 ▶ $fh = IO::Socket::INET->new(
Branch: 3 branches
BranchTrueFalseTotal
$fh = "IO::Socket::INET"->new($ip ? ("PeerAddr", $ip) : (), $port ? ("PeerPort", $port) : (), %sopts) or croak("Connection to ${url}: $!") 2 0 2
$ip ? : 2 0 2
$port ? : 2 0 2
905 ($ip?(PeerAddr => $ip):()),
906 ($port?(PeerPort => $port):()),
907 %sopts,
908 ) or croak "Connection to $url: $!";
909 }
910  
911 4 $self->add($fh, %opts);
912 4 return $fh;
913
914 } elsif($url =~ m{^unix(?:_(dgram))?://(.+)$}) {
915 0 my ($dgram, $file) = ($1, $2);
916
917 0 ▶ my %sopts = (
Branch: 1 branch
BranchTrueFalseTotal
$dgram ? : 0 0 0
918 ($dgram?(Type => SOCK_DGRAM):()),
919 Blocking => 0,
920 );
921
922 0 my $fh;
923 0 ▶ if($opts{Listen}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'Listen'}) { } 0 0 0
924 0 ▶ $fh = IO::Socket::UNIX->new(
Branch: 1 branch
BranchTrueFalseTotal
$fh = "IO::Socket::UNIX"->new("Peer", $file, %sopts) or croak("Listening to ${url}: $!") 0 0 0
925 Peer => $file,
926 %sopts,
927 ) or croak "Listening to $url: $!";
928
929 } else {
930 0 ▶ $fh = IO::Socket::UNIX->new(
Branch: 1 branch
BranchTrueFalseTotal
$fh = "IO::Socket::UNIX"->new("Local", $file, %sopts) or croak("Connecting to ${url}: $!") 0 0 0
931 Local => $file,
932 %sopts,
933 ) or croak "Connecting to $url: $!";
934 }
935  
936 0 delete $opts{Listen};
937 0 $self->add($fh, %opts);
938 0 return $fh;
939
940 } else {
941 0 croak "unknown url type: $url";
942 }
943
944 } else { # IO::Socket
945 4 my (%opts) = @_;
946
947 # Get list of options that are for IO::Socket
948 20 my (%sopts) = map { $_ => $opts{$_} }
949 4 grep { !exists $allowed_add_opts{$_} } keys %opts;
950
951 # Remove Socket options from add options, but keep Listen
952 2 %opts = map { $_ => $opts{$_} }
953 4 ▶ grep { !exists $sopts{$_} or $_ eq 'Listen'} keys %opts;
Condition66%2/3
!exists $sopts{$_} || $_ eq 'Listen'
l!l&&r!l&&!r
0218
MC/DC50%1/2
!exists $sopts{$_} || $_ eq 'Listen'
!exists $sopts{$_} $_ eq 'Listen'
Truth table66%2/3
not(A) || B
A= !exists $sopts{$_}B= $_ eq 'Listen'
ABresult
1X1
011
000
954  
955 # Check if this is a tcp or udp socket
956 4 ▶ if(defined $sopts{Proto}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sopts{'Proto'}) { } 4 0 4
elsif (defined $sopts{'Local'} or defined $sopts{'Peer'}) { } 0 0 0
957 # Only TCP supports the Listen option
958 4 ▶ delete $sopts{Listen} if $sopts{Proto} eq 'udp';
Branch: 1 branch
BranchTrueFalseTotal
if $sopts{"Proto"} eq "udp" 2 2 4
959 4 ▶ delete $opts{Listen} if $sopts{Proto} eq 'udp';
Branch: 1 branch
BranchTrueFalseTotal
if $sopts{"Proto"} eq "udp" 2 2 4
960
961 4 ▶ my $fh = IO::Socket::INET->new(
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::Socket::INET"->new("Blocking", 0, %sopts) or croak("Could not create IO::Socket::INET: $!") 4 0 4
962 Blocking => 0,
963 %sopts,
964 ) or croak "Could not create IO::Socket::INET: $!";
965
966 4 $self->add($fh, %opts);
967 4 return $fh;
968  
969 # Check if this is a UNIX domain socket
970 ▶ } elsif(defined $sopts{Local} or defined $sopts{Peer}) {
Condition0%0/3
defined $sopts{"Local"} or defined $sopts{"Peer"}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $sopts{"Local"} or defined $sopts{"Peer"}
defined $sopts{"Local"} defined $sopts{"Peer"}
Truth table0%0/3
A or B
A= defined $sopts{"Local"}B= defined $sopts{"Peer"}
ABresult
1X1
011
000
971 0 ▶ my $fh = IO::Socket::UNIX->new(
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::Socket::UNIX"->new("Blocking", 0, %sopts) or croak("Could not create IO::Socket::UNIX: $!") 0 0 0
972 Blocking => 0,
973 %sopts,
974 ) or croak "Could not create IO::Socket::UNIX: $!";
975
976 0 $self->add($fh, %opts);
977 0 return $fh;
978
979 } else {
980 0 croak "unknown socket options set or no Proto defined";
981 }
982 }
983 }
984  
985 =head2 B<set()>
986  
987 Set new options on a fh in IO::EventMux, currently only Buffered options is handled
988  
989 =cut
990  
991 0 ▶sub set {
Subroutine set: not called CC=9 SCAR=45.0
Pod documented
992 0 my ($self, $fh, %opts) = @_;
993
994 0 ▶ croak "undefined file handle given" if !defined $fh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fh 0 0 0
995 0 ▶ croak "$fh not handled by IO::EventMux" if !exists $self->{fhs}{$fh};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"fhs"}{$fh} 0 0 0
996 croak "Buffered is not a IO::Buffered object" if defined $opts{Buffered}
997 and !(blessed($opts{Buffered})
998 0 ▶ and $opts{Buffered}->isa('IO::Buffered'));
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"Buffered"} and not builtin::blessed($opts{"Buffered"}) && $opts{"Buffered"}->isa("IO::Buffered") 0 0 0
Condition0%0/6
defined $opts{"Buffered"} and not builtin::blessed($opts{"Buffered"}) && $opts{"Buffered"}->isa("IO::Buffered")
!ll&&!rl&&r
000
builtin::blessed($opts{'Buffered'}) && $opts{'Buffered'}->isa('IO::Buffered')
!ll&&!rl&&r
000
MC/DC0%0/3
defined $opts{"Buffered"} and not builtin::blessed($opts{"Buffered"}) && $opts{"Buffered"}->isa("IO::Buffered")
defined $opts{"Buffered"} builtin::blessed($opts{'Buffered'}) $opts{'Buffered'}->isa('IO::Buffered')
Truth table0%0/4
A and not(B && C)
A= defined $opts{"Buffered"}B= builtin::blessed($opts{'Buffered'})C= $opts{'Buffered'}->isa('IO::Buffered')
ABCresult
0XX0
1110
10X1
1101
999  
1000 0 my $cfg = $self->{fhs}{$fh};
1001 0 my $inbuffer = $cfg->{inbuffer};
1002  
1003 0 ▶ if(exists $opts{Buffered}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"Buffered"}) 0 0 0
1004 0 ▶ if(defined $opts{Buffered}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"Buffered"}) 0 0 0
1005 0 ▶ if(blessed($inbuffer)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($inbuffer)) { } 0 0 0
1006 0 $opts{Buffered}->write($inbuffer->buffer());
1007 } else {
1008 0 $opts{Buffered}->write($inbuffer);
1009 }
1010 }
1011 0 $cfg->{inbuffer} = $opts{Buffered};
1012 }
1013 }
1014  
1015  
1016 =head2 B<handles()>
1017  
1018 Returns a list of file handles managed by this object.
1019  
1020 =cut
1021  
1022 0 ▶sub handles { } # Stub - is created in new()
Subroutine handles: not called CC=1 SCAR=0.0
Pod documented
1023  
1024 =head2 B<has_events()>
1025  
1026 Returns true if there are pending events, or false otherwise
1027  
1028 =cut
1029  
1030 0 ▶sub has_events {
Subroutine has_events: not called CC=1 SCAR=6.9
Pod documented
1031 0 my ($self) = @_;
1032 0 return @{$self->{events}} + @{$self->{actionq}};
1033 }
1034  
1035 =head2 B<type()>
1036  
1037 Returns the socket type for a file handle
1038  
1039 =cut
1040  
1041 12 ▶sub type {
Subroutine type: called CC=1 SCAR=0.0
Pod documented
1042 12 my ($self, $fh) = @_;
1043 12 return $self->{fhs}{$fh}{type};
1044 }
1045  
1046 =head2 B<class()>
1047  
1048 Returns the socket class for a file handle
1049  
1050 =cut
1051  
1052 0 ▶sub class {
Subroutine class: not called CC=1 SCAR=6.9
Pod documented
1053 0 my ($self, $fh) = @_;
1054 0 return $self->{fhs}{$fh}{class};
1055 }
1056  
1057 =head2 B<meta($fh, [$newval])>
1058  
1059 Set or get a piece of metadata on the filehandle. This can be any scalar value.
1060  
1061 =cut
1062  
1063 0 ▶sub meta {
Subroutine meta: not called CC=3 SCAR=24.8
Pod documented
1064 0 my ($self, $id, $newval) = @_;
1065 0 ▶ return if !defined $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 0 0 0
1066  
1067 0 ▶ if (@_ > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 2) 0 0 0
1068 0 $self->{sessions}{$id} = $newval;
1069 }
1070  
1071 0 return $self->{sessions}{$id};
1072 }
1073  
1074 =head2 B<remove($fh)>
1075  
1076 Make EventMux forget about a file handle. The caller will then take over the
1077 responsibility of closing it.
1078  
1079 =cut
1080  
1081 0 ▶sub remove {
Subroutine remove: not called CC=1 SCAR=6.9
Pod documented
1082 0 my ($self, $fh) = @_;
1083  
1084 0 _eventloop_remove($self, "readfh", $fh);
1085 0 _eventloop_remove($self, "writefh", $fh);
1086 0 delete $self->{listenfh}{$fh};
1087 0 delete $self->{fhs}{$fh};
1088 }
1089  
1090  
1091 =head2 B<close($fh)>
1092  
1093 Close a file handle. IO::EventMux will stop listing to both reads and writes on
1094 the file handle and return a "closing" event and on next C<mux> call kill will
1095 be called, returning "closed" for the file handle.
1096  
1097 Note: All 'Meta' data associated with the file handle will be kept until the
1098 final 'closed' event is returned.
1099  
1100 =cut
1101  
1102 0 ▶sub close {
Subroutine close: not called CC=3 SCAR=24.8
Pod documented
1103 0 my ($self, $fh) = @_;
1104 0 ▶ return if !exists $self->{fhs}{$fh}; # Only remove if we handle this fh
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"fhs"}{$fh} 0 0 0
1105  
1106 0 ▶ return if $self->{fhs}{$fh}{disconnecting};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"fhs"}{$fh}{"disconnecting"} 0 0 0
1107 0 $self->{fhs}{$fh}{disconnecting} = 1;
1108
1109 0 delete $self->{listenfh}{$fh};
1110 0 _eventloop_remove($self, "readfh", $fh);
1111 0 _eventloop_remove($self, "writefh", $fh);
1112
1113 0 $self->push_event({ type => 'closing', fh => $fh });
1114
1115 # wait with the close so a valid file handle can be returned
1116 0 ▶ push @{$self->{actionq}}, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1117 0 $self->kill($fh);
1118 0 };
1119 }
1120  
1121 =head2 B<kill($fh)>
1122  
1123 Closes a file handle without giving time to finish any outstanding operations.
1124 Returns a 'closed' event, deletes all buffers and does not keep 'Meta' data.
1125  
1126 Note: Does not return the 'read_last' event.
1127  
1128 =cut
1129  
1130 0 ▶sub kill {
Subroutine kill: not called CC=2 SCAR=17.9
Pod documented
1131 0 my ($self, $fh) = @_;
1132 0 ▶ return if !exists $self->{fhs}{$fh}; # Only remove if we handle this fh
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"fhs"}{$fh} 0 0 0
1133  
1134 0 _eventloop_remove($self, "readfh", $fh);
1135 0 _eventloop_remove($self, "writefh", $fh);
1136  
1137 0 $self->push_event({ type => 'closed', fh => $fh,
1138 missing => $self->buflen($fh) });
1139
1140 0 $self->_close_fh($fh);
1141 }
1142  
1143 0 ▶sub _close_fh {
Subroutine _close_fh: not called CC=3 SCAR=24.8
1144 0 my ($self, $fh) = @_;
1145  
1146 0 ▶ if ($self->{fhs}{$fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"fhs"}{$fh}) 0 0 0
1147 0 delete $self->{fhs}{$fh};
1148 0 shutdown $fh, 2;
1149 0 ▶ CORE::close $fh or croak "closing $fh: $!";
Branch: 1 branch
BranchTrueFalseTotal
CORE::close $fh or croak("closing ${fh}: $!") 0 0 0
1150 }
1151 }
1152  
1153 =head2 B<buflen($fh)>
1154  
1155 Queries the length of the output buffer for this file handle. This only
1156 applies if ManualWrite is turned off, which is the default. For Type="dgram"
1157 sockets, it returns the number of datagrams in the queue.
1158  
1159 An application can use this method to see whether it should send more data or
1160 wait until the buffer queue is a bit shorter.
1161  
1162 =cut
1163  
1164 0 ▶sub buflen {
Subroutine buflen: not called CC=5 SCAR=34.0
Pod documented
1165 0 my ($self, $fh) = @_;
1166 0 my $cfg = $self->{fhs}{$fh};
1167  
1168 0 ▶ croak "$fh not handled by EventMux" if !$cfg;
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg 0 0 0
1169  
1170 0 ▶ if ($cfg->{type} eq "dgram") {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"type"} eq "dgram") 0 0 0
1171 0 ▶ return $cfg->{outbuffer} ? scalar(@{$cfg->{outbuffer}}) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$cfg->{'outbuffer'} ? : 0 0 0
1172 }
1173  
1174 0 ▶ return $cfg->{outbuffer} ? length($cfg->{outbuffer}) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$cfg->{'outbuffer'} ? : 0 0 0
1175 }
1176  
1177  
1178 =head2 B<recvdata($fh, $length)>
1179  
1180 TODO: Queues @data to be written to the file handle $fh. Can only be used when ManualWrite is
1181 off (default).
1182  
1183 =cut
1184  
1185 # FIXME: Cleanup, remove print
1186 0 ▶sub recvdata {
Subroutine recvdata: not called CC=3 SCAR=24.8
Pod documented
1187 0 my ($self, $fh, $length) = @_;
1188 0 my $cfg = $self->{fhs}{$fh};
1189
1190 0 ▶ if(my $buffer = $cfg->{inbuffer}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $buffer = $cfg->{"inbuffer"}) 0 0 0
1191 0 $cfg->{recvlength} = $length;
1192 0 print "length: $length\n";
1193 0 foreach my $record ($buffer->read($cfg->{recvlength})) {
1194 0 $self->push_event({ type => 'read', fh => $fh,
1195 data => $record });
1196 0 delete $cfg->{recvlength};
1197 }
1198 }
1199 }
1200  
1201  
1202 =head2 B<send($fh, @data)>
1203  
1204 Queues @data to be written to the file handle $fh. Can only be used when ManualWrite is
1205 off (default).
1206  
1207 =over
1208  
1209 =item If the socket is of Type="stream"
1210  
1211 Returns true on success, undef on error. The data is sent when the socket
1212 becomes unblocked and a 'sent' event is posted when all data is sent and the
1213 buffer is empty. Therefore the socket should not be closed until
1214 L</B<buflen($fh)>> returns 0 or a sent request has been posted.
1215  
1216 =item If the socket is of Type="dgram"
1217  
1218 Each item in @data will be sent as a separate packet. Returns true on success
1219 and undef on error.
1220  
1221 =back
1222  
1223 =cut
1224  
1225 4 ▶sub send {
Subroutine send: called CC=1 SCAR=0.0
Pod documented
1226 4 my ($self, $fh, @data) = @_;
1227 4 return $self->sendto($fh, undef, @data);
1228 }
1229  
1230 =head2 B<sendto($fh, $to, @data)>
1231  
1232 Like C<send()>, but with the recepient C<$to> as a packed sockaddr structure,
1233 such as the one returned by C<Socket::pack_sockaddr_in()>. Only for Type="dgram"
1234 sockets.
1235  
1236 $mux->sendto($my_fh, pack_sockaddr_in($port, inet_aton($ip)), $data);
1237  
1238 =cut
1239  
1240 5 ▶sub sendto {
Subroutine sendto: called CC=8 SCAR=25.4
Pod documented
1241 5 my ($self, $fh, $to, @data) = @_;
1242  
1243 5 ▶ croak "send() on an undefined file handle" if !defined $fh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fh 0 5 5
1244  
1245 5 my $cfg = $self->{fhs}{$fh};
1246  
1247 5 ▶ croak "send() on filehandle not handled by IO::Eventmux" if !$cfg;
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg 1 4 5
1248  
1249 4 ▶ return if $cfg->{disconnecting};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"disconnecting"} 0 4 4
1250  
1251 4 ▶ if (not $cfg->{auto_write}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"auto_write"}) 0 4 4
1252 0 croak "send() on a ManualWrite file handle";
1253 0 return;
1254 }
1255  
1256 4 ▶ if ($cfg->{type} eq "dgram") {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'type'} eq 'dgram') { } 4 0 4
1257 4 push @{$cfg->{outbuffer}}, map { [$_, $to] } @data;
1258 4 my $rv = $self->_send_dgram($fh);
1259
1260 3 ▶ if(@{$cfg->{outbuffer}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$cfg->{"outbuffer"};}) 0 3 3
1261 0 _eventloop_add($self, "writefh", $fh);
1262 }
1263  
1264 3 return $rv;
1265
1266 } else {
1267 0 $cfg->{outbuffer} .= join('', @data);
1268 0 my $rv = $self->_send_stream($fh);
1269
1270 0 ▶ if(length $cfg->{outbuffer}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $cfg->{"outbuffer"}) 0 0 0
1271 0 _eventloop_add($self, "writefh", $fh);
1272 }
1273  
1274 0 return $rv;
1275 }
1276 }
1277  
1278 9 ▶sub _send_dgram {
Subroutine _send_dgram: called CC=11 SCAR=27.2
1279 9 my ($self, $fh) = @_;
1280 9 my $cfg = $self->{fhs}{$fh};
1281 9 my $write = $self->{fhs}{$fh}{write};
1282 9 my $packets_sent = 0;
1283  
1284 9 ▶ if (@{$cfg->{outbuffer}} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$cfg->{"outbuffer"};} == 0) 5 4 9
1285 # no data to send
1286 5 _eventloop_remove($self, "writefh", $fh);
1287 5 return;
1288 }
1289  
1290 4 ▶ while (my $queue_item = shift @{$cfg->{outbuffer}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $queue_item = shift @{$$cfg{"outbuffer"};}) 4 3 7
1291 4 my ($data, $to) = @$queue_item;
1292
1293 4 ▶ croak "Trying to send undef" if !defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 4 4
1294  
1295 4 ▶ my $rv = eval { $write->($fh, $data, (defined $to ? $to : ())); };
Branch: 1 branch
BranchTrueFalseTotal
defined $to ? : 1 3 4
1296
1297 # Clean up error
1298 4 $@ =~ s/\s*at \S+ line [\d\.]+\n//g;
1299  
1300 4 ▶ if ($@ =~ /Resource temporarily unavailable/) {
Branch: 4 branches
BranchTrueFalseTotal
if ($@ =~ /Resource temporarily unavailable/) { } 0 4 4
elsif ($@ and $cfg->{'errors'} and my(@events) = socket_errors($fh)) { } 0 4 4
elsif ($@) { } 0 4 4
elsif ($rv < length $data) { } 1 3 4
1301 # retry later
1302 0 unshift @{$cfg->{outbuffer}}, $queue_item;
1303 0 return $packets_sent;
1304
1305 ▶ } elsif($@ and $cfg->{errors} and my @events = socket_errors($fh)) {
Condition33%2/6
$@ and $cfg->{"errors"} and my(@events) = socket_errors($fh)
!ll&&!rl&&r
400
$@ and $cfg->{"errors"}
!ll&&!rl&&r
400
MC/DC0%0/3
$@ and $cfg->{"errors"} and my(@events) = socket_errors($fh)
$@ $cfg->{"errors"} my(@events) = socket_errors($fh)
Truth table25%1/4
A and B and C
A= $@B= $cfg->{"errors"}C= my(@events) = socket_errors($fh)
ABCresult
0XX0
10X0
1100
1111
1306 0 unshift @{$cfg->{outbuffer}}, $queue_item;
1307 0 $self->push_event(@events);
1308 0 next;
1309
1310 } elsif($@) {
1311 # FIXME: Add MetaHandler id to error information
1312 0 $self->push_event({ type => 'error', error => "$@", fh => $fh,
1313 receiver => $to });
1314 0 return;
1315
1316 } elsif ($rv < length $data) {
1317 1 die "Incomplete datagram sent (should not happen)";
1318  
1319 } else {
1320 # all pending data was sent
1321 3 $packets_sent++;
1322 }
1323 }
1324
1325 # Buffer is empty and stop listening to write
1326 3 $self->push_event({type => 'sent', fh => $fh});
1327 3 _eventloop_remove($self, "writefh", $fh);
1328  
1329 3 return $packets_sent;
1330 }
1331  
1332 1 ▶sub _send_stream {
Subroutine _send_stream: called CC=9 SCAR=40.5
1333 1 my ($self, $fh) = @_;
1334 1 my $cfg = $self->{fhs}{$fh};
1335 1 my $write = $self->{fhs}{$fh}{write};
1336  
1337 #my ($package, $filename, $line, $subroutine, $hasargs, $wantarray,
1338 # $evaltext, $is_require, $hints, $bitmask, $hinthash) = caller(0);
1339 #
1340 #print "sendstream $line\n";
1341  
1342 1 ▶ if ($cfg->{outbuffer} eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"outbuffer"} eq "") 1 0 1
1343 # no data to send
1344 1 _eventloop_remove($self, "writefh", $fh);
1345 1 return;
1346 }
1347  
1348 0 my $rv = eval { $write->($fh, $cfg->{outbuffer}); };
1349  
1350 # Clean up error
1351 0 $@ =~ s/\s*at \S+ line [\d\.]+\n//g;
1352  
1353 # Check for undef or -1 as both can be error retvals
1354 0 ▶ if ($@ =~ /Resource temporarily unavailable/) {
Branch: 5 branches
BranchTrueFalseTotal
if ($@ =~ /Resource temporarily unavailable/) { } 0 0 0
elsif ($@ =~ /Bad file descriptor/) { } 0 0 0
elsif ($@ =~ /Cannot determine peer address/ and $cfg->{'ready'} == 0) { } 0 0 0
elsif ($@) { } 0 0 0
elsif ($rv < length $cfg->{'outbuffer'}) { } 0 0 0
1355 0 return;
1356
1357 } elsif($@ =~ /Bad file descriptor/) {
1358 0 $self->push_event({ type => 'error', error => "$@", fh => $fh });
1359 0 $self->push_event({ type => 'closing', fh => $fh });
1360 0 $self->kill($fh);
1361 0 return;
1362
1363 ▶ } elsif($@ =~ /Cannot determine peer address/ and $cfg->{ready} == 0) {
Condition0%0/3
$@ =~ /Cannot determine peer address/ and $cfg->{"ready"} == 0
!ll&&!rl&&r
000
MC/DC0%0/2
$@ =~ /Cannot determine peer address/ and $cfg->{"ready"} == 0
$@ =~ /Cannot determine peer address/ $cfg->{"ready"} == 0
Truth table0%0/3
A and B
A= $@ =~ /Cannot determine peer address/B= $cfg->{"ready"} == 0
ABresult
0X0
100
111
1364 # To soon to send data, retry when we get a ready
1365 0 return;
1366  
1367 } elsif($@) {
1368 0 $self->push_event({ type => 'error', error => "$@", fh => $fh });
1369 0 return;
1370  
1371 } elsif ($rv < length $cfg->{outbuffer}) {
1372 # only part of the data was sent
1373 0 substr($cfg->{outbuffer}, 0, $rv) = '';
1374 0 _eventloop_add($self, "writefh", $fh);
1375
1376 } else {
1377 # all pending data was sent
1378 0 $cfg->{outbuffer} = '';
1379 0 _eventloop_remove($self, "writefh", $fh);
1380  
1381 0 ▶ if($cfg->{ready} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"ready"} == 0) 0 0 0
1382 0 $cfg->{ready} = 1;
1383 0 $self->push_event({ type => 'ready', fh => $fh });
1384 }
1385
1386 0 $self->push_event({type => 'sent', fh => $fh});
1387 }
1388  
1389  
1390 0 return $rv;
1391 }
1392  
1393 =head2 B<push_event($event)>
1394  
1395 Push event on queue
1396  
1397 =cut
1398  
1399 21 ▶sub push_event {
Subroutine push_event: called CC=1 SCAR=0.0
Pod documented
1400 21 my($self, @events) = @_;
1401 21 push(@{$self->{events}}, @events);
1402 }
1403  
1404 =head2 B<nonblock($fh)>
1405  
1406 Puts socket into nonblocking mode.
1407  
1408 =cut
1409  
1410 37 ▶sub nonblock {
Subroutine nonblock: called CC=4 SCAR=14.2
Pod documented
1411 37 my $socket = $_[1];
1412  
1413 37 ▶ my $flags = fcntl($socket, F_GETFL, 0)
Branch: 1 branch
BranchTrueFalseTotal
my $flags = fcntl($socket, 3, 0) or die "Can't get flags for socket: $!\n" 37 0 37
1414 or die "Can't get flags for socket: $!\n";
1415 37 ▶ if (not $flags & O_NONBLOCK) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $flags & 2048) 16 21 37
1416 16 ▶ fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
Branch: 1 branch
BranchTrueFalseTotal
fcntl $socket, 4, $flags | 2048 or die "Can't make socket nonblocking: $!\n" 16 0 16
1417 or die "Can't make socket nonblocking: $!\n";
1418 }
1419 }
1420  
1421 =head2 B<socket_creds($fh)>
1422  
1423 Return credentials on UNIX domain sockets.
1424  
1425 =cut
1426  
1427 4 ▶sub socket_creds {
Subroutine socket_creds: called CC=2 SCAR=7.0
Pod documented
1428 4 my ($self, $fh) = @_;
1429 4 my %creds;
1430  
1431 # TODO: Support localhost TCP via: /proc/net/tcp
1432 4 my $rv = getsockopt($fh, SOL_SOCKET, SO_PEERCRED);
1433 4 ▶ if(defined $rv) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rv) 4 0 4
1434 4 my ($pid, $uid, $gid) = unpack('LLL', $rv);
1435 4 %creds = (pid => $pid, uid => $uid, gid => $gid);
1436 }
1437  
1438 4 return %creds;
1439 }
1440  
1441  
1442 =head2 B<socket_type($fh)>
1443  
1444 Return socket type.
1445  
1446 =cut
1447  
1448 36 ▶sub socket_type {
Subroutine socket_type: called CC=5 SCAR=16.6
Pod documented
1449 36 my ($self, $fh) = @_;
1450
1451 36 my $ptype = getsockopt($fh, SOL_SOCKET, SO_TYPE);
1452 36 ▶ if(defined $ptype) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ptype) { } 35 1 36
1453 35 my $type = unpack("S", $ptype);
1454 35 ▶ if($type == SOCK_STREAM) { # type = 1
Branch: 2 branches
BranchTrueFalseTotal
if ($type == 1) { } 18 17 35
elsif ($type == 2 or $type == 3) { } 17 0 17
1455 18 return 'stream';
1456  
1457 ▶ } elsif($type == SOCK_DGRAM or $type == SOCK_RAW) { # type = 2,3
Condition33%1/3
$type == 2 or $type == 3
l!l&&r!l&&!r
1700
MC/DC0%0/2
$type == 2 or $type == 3
$type == 2 $type == 3
Truth table33%1/3
A or B
A= $type == 2B= $type == 3
ABresult
1X1
011
000
1458 17 return 'dgram';
1459
1460 } else {
1461 0 croak "Unknown socket type: $type";
1462 }
1463  
1464 } else {
1465 1 return;
1466 }
1467 }
1468  
1469  
1470 =head2 B<socket_listening($fh)>
1471  
1472 Check if the socket is set to listening mode
1473  
1474 =cut
1475  
1476 35 ▶sub socket_listening {
Subroutine socket_listening: called CC=2 SCAR=7.4
Pod documented
1477 35 my ($self, $fh) = @_;
1478 35 my $listening = getsockopt($fh, SOL_SOCKET, SO_ACCEPTCONN);
1479 35 ▶ if(defined $listening) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $listening) { } 35 0 35
1480 35 return unpack("I", $listening);
1481 } else {
1482 0 return;
1483 }
1484 }
1485  
1486  
1487 =head2 recroak()
1488  
1489 Helper function to rethrow croaks
1490  
1491 =cut
1492  
1493 0 ▶sub recroak {
Subroutine recroak: not called CC=1 SCAR=6.9
Pod documented
1494 0 $_[0] =~ s/ at \S+ line \d+.*$//s;
1495 0 croak $_[0];
1496 }
1497  
1498 # Call read_events until at least one event is returned or max 10 times.
1499 9 ▶sub _read_all {
Subroutine _read_all: called CC=4 SCAR=14.5
1500 9 my ($self, $fh) = @_;
1501
1502 9 my $eventscount = int @{$self->{events}};
1503 9 my $reads = 10; # Max number of reads pr. fh.
1504  
1505 9 ▶ while($reads--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($reads--) 9 0 9
1506 9 ▶ if($self->_read_events($fh) and int @{$self->{events}} == $eventscount){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_read_events($fh) and int @{$self->{'events'};} == $eventscount) { } 0 9 9
Condition66%2/3
$self->_read_events($fh) and int @{$self->{"events"};} == $eventscount
!ll&&!rl&&r
180
MC/DC0%0/2
$self->_read_events($fh) and int @{$self->{"events"};} == $eventscount
$self->_read_events($fh) int @{$self->{"events"};} == $eventscount
Truth table66%2/3
A and B
A= $self->_read_events($fh)B= int @{$self->{"events"};} == $eventscount
ABresult
0X0
100
111
1507 0 next;
1508 } else {
1509 9 last;
1510 }
1511 }
1512 }
1513  
1514 # Returns 1 when another call might give more events, else undef
1515 9 ▶sub _read_events {
Subroutine _read_events: called CC=19 SCAR=45.3
1516 9 my ($self, $fh) = @_;
1517  
1518 9 my $cfg = $self->{fhs}{$fh};
1519 9 my $read = $cfg->{read};
1520 9 my $buffer = $cfg->{inbuffer};
1521  
1522 9 my ($sender, $data) = eval { $read->($fh, $cfg->{read_size}); };
1523
1524 # Clean up error
1525 9 $@ =~ s/\s*at \S+ line [\d\.]+\n//g;
1526
1527 9 ▶ if($@ =~ /Resource temporarily unavailable/) {
Branch: 7 branches
BranchTrueFalseTotal
if ($@ =~ /Resource temporarily unavailable/) { } 0 9 9
elsif ($@ =~ /Filehandle.+opened only for output/) { } 0 9 9
elsif ($@ =~ /Bad file descriptor/) { } 0 9 9
elsif ($@ and $cfg->{'errors'} and my(@events) = socket_errors($fh)) { } 0 9 9
elsif ($@) { } 0 9 9
elsif ($cfg->{'type'} eq 'stream' and length $data == 0) { } 1 8 9
elsif ($buffer) { } 0 8 8
1528 0 return;
1529  
1530 } elsif($@ =~ /Filehandle.+opened only for output/) {
1531 0 $self->push_event({ type => 'error', error => "$@ in _read_events()",
1532 fh => $fh });
1533 0 $self->push_event({ type => 'closing', fh => $fh });
1534 0 $self->kill($fh);
1535 0 return;
1536
1537 } elsif($@ =~ /Bad file descriptor/) {
1538 0 $self->push_event({ type => 'error', error => "$@ in _read_events()",
1539 fh => $fh });
1540 0 $self->push_event({ type => 'closing', fh => $fh });
1541 0 $self->kill($fh);
1542 0 return;
1543
1544 ▶ } elsif($@ and $cfg->{errors} and my @events = socket_errors($fh)) {
Condition33%2/6
$@ and $cfg->{"errors"} and my(@events) = socket_errors($fh)
!ll&&!rl&&r
900
$@ and $cfg->{"errors"}
!ll&&!rl&&r
900
MC/DC0%0/3
$@ and $cfg->{"errors"} and my(@events) = socket_errors($fh)
$@ $cfg->{"errors"} my(@events) = socket_errors($fh)
Truth table25%1/4
A and B and C
A= $@B= $cfg->{"errors"}C= my(@events) = socket_errors($fh)
ABCresult
0XX0
10X0
1100
1111
1545 # FIXME: Adde MetaHandler information to events
1546 0 $self->push_event(@events);
1547 0 return 1;
1548
1549 } elsif($@) {
1550 0 $self->push_event({ type => 'error', error => "$@ in _read_events()",
1551 fh => $fh });
1552 0 return;
1553
1554 # Check if connection closed for tcp
1555 ▶ } elsif($cfg->{type} eq 'stream' and length $data == 0) {
Condition100%3/3
$cfg->{"type"} eq "stream" and length $data == 0
!ll&&!rl&&r
711
MC/DC100%2/2
$cfg->{"type"} eq "stream" and length $data == 0
$cfg->{"type"} eq "stream" length $data == 0
Truth table100%3/3
A and B
A= $cfg->{"type"} eq "stream"B= length $data == 0
ABresult
0X0
100
111
1556 # Return the last of the buffer on disconnect
1557 1 ▶ if($buffer) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffer) 0 1 1
1558 0 ▶ if($buffer->buffer() ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffer->buffer ne "") 0 0 0
1559 $self->push_event({
1560 0 ▶ type => $cfg->{return_last} ? 'read_last' : 'read',
Branch: 1 branch
BranchTrueFalseTotal
$cfg->{'return_last'} ? : 0 0 0
1561 fh => $fh,
1562 data => $buffer->buffer()
1563 });
1564 }
1565 }
1566
1567 # Wait with the close so a valid file handle can be returned
1568 0 ▶ push(@{$self->{actionq}}, sub { $self->kill($fh); });
Subroutine __ANON__: not called CC=1 SCAR=0.4
1569 1 $self->push_event({ type => 'closing', fh => $fh });
1570 1 return;
1571
1572 } elsif($buffer) {
1573 0 eval { $buffer->write($data); };
1574 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
1575 # Push buffer overflow error or other error to the event queue
1576 0 $self->push_event({ type => 'error', error => "$@", fh => $fh,
1577 data=> $data });
1578 0 $self->push_event({ type => 'read_last', fh => $fh,
1579 data => $buffer->buffer() });
1580  
1581 # Wait with the close so a valid file handle can be returned
1582 0 ▶ push(@{$self->{actionq}}, sub { $self->kill($fh); });
Subroutine __ANON__: not called CC=1 SCAR=6.9
1583 0 $self->push_event({ type => 'closing', fh => $fh });
1584 0 return;
1585
1586 } else {
1587 0 foreach my $record ($buffer->read($cfg->{recvlength})) {
1588 0 $self->push_event({ type => 'read', fh => $fh,
1589 data => $record });
1590 0 delete $cfg->{recvlength};
1591 }
1592 }
1593
1594 0 return 1;
1595  
1596 } else {
1597 # Add MetaHandler information
1598 8 my $id;
1599 8 ▶ if(defined $cfg->{meta_handler}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cfg->{"meta_handler"}) 0 8 8
1600 0 $id = $cfg->{meta_handler}->($fh, $data, $sender);
1601 }
1602  
1603 8 ▶ $self->push_event({ type => 'read', fh => $fh, data => $data,
Branch: 2 branches
BranchTrueFalseTotal
$sender ? : 5 3 8
$id ? : 0 8 8
1604 ($sender ? (sender => $sender) : ()),
1605 ($id ? (id => $id) : ()),
1606 });
1607 8 return 1;
1608 }
1609 }
1610  
1611 =head2 socket_errors
1612  
1613 Dummy sub that casts an error if the IO::EventMux::Socket::MsgHdr is not installed and the Errors option is used
1614  
1615 =cut
1616  
1617 =head2 NOTES
1618  
1619 B<Working with PIPE's:>
1620 When the other end of a pipe closes it's end, signals can get thrown. To handle
1621 this a signal handler needs to be defined:
1622  
1623 # Needed when writing to a broken pipe
1624 $SIG{PIPE} = sub { # SIGPIPE
1625 croak "Broken pipe";
1626 };
1627  
1628 B<Getting rid of 'Filehandle ... opened only for output'>
1629  
1630 # Needed as sysread() throws warnings when STDIN gets closed by the child
1631 $SIG{__WARN__} = sub {
1632 croak @_;
1633 };
1634  
1635 =cut
1636  
1637 =head1 AUTHOR
1638  
1639 Jonas Jensen <jonas@infopro.dk>, Troels Liebe Bentsen <troels@infopro.dk>
1640  
1641 =head1 COPYRIGHT AND LICENCE
1642  
1643 Copyright 2006-2008: Troels Liebe Bentsen
1644 Copyright 2006-2007: Jonas Jensen
1645  
1646 This library is free software; you can redistribute it and/or modify
1647 it under the same terms as Perl itself.
1648  
1649 =cut
1650  
1651 29 1;
↑ Summary EventMux/Dump.pm »