Twiggy/Server/SS.pm untested

filter: Statementstmt 0.0% 0 / 61 Branchbran 0.0% 0 / 8 Conditioncond 0.0% 0 / 21 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 114 CC 5 SCAR 21.0
CC
5
Cov
0%
_create_ss_tcp_server
20.0
start_listen
6.0
BEGIN
2.0
CRAP 8.2
1 package Twiggy::Server::SS;
2 use strict;
3 use warnings;
4 use base qw(Twiggy::Server);
5 use AnyEvent;
6 use AnyEvent::Util qw(fh_nonblocking guard);
7 use AnyEvent::Socket qw(format_address);
8 use Server::Starter qw(server_ports);
9  
10 sub start_listen {
11 my ($self, $app) = @_;
12  
13 if (Twiggy::Server::DEBUG() && $self->{listen}) {
14 warn "'listen' option is currently ignored when used in conjunction with Server::Starter (start_server script)";
15 }
16  
17 my $host = $self->{host} || '';
18  
19 my @listen;
20 my $ports = server_ports();
21 while (my ($hostport, $fd) = each %$ports ) {
22 push @listen, $hostport;
23 $self->_create_ss_tcp_server($hostport, $fd, $app);
24 }
25  
26 # overwrite, just in case somebody wants to refer to it afterwards
27 $self->{listen} = \@listen;
28 }
29  
30 sub _create_ss_tcp_server {
31 my ($self, $hostport, $fd, $app) = @_;
32  
33 my $is_tcp = 1; # currently no unix socket support
34  
35 my ($host, $port);
36 if ($hostport =~ /(.*):(\d+)/) {
37 $host = $1;
38 $port = $2;
39 } else {
40 $host ||= '0.0.0.0';
41 $port = $hostport;
42 }
43  
44 # /WE/ don't care what the address family, type of socket we got, just
45 # create a new handle, and perform a fdopen on it. So that part of
46 # AE::Socket::tcp_server is stripped out
47  
48 my %state;
49 $state{fh} = IO::Socket::INET->new(
50 Proto => 'tcp',
51 Listen => 128,
52 );
53  
54 $state{fh}->fdopen( $fd, 'w' ) or
55 Carp::croak "failed to bind to listening socket: $!";
56 fh_nonblocking $state{fh}, 1;
57  
58 my($listen_host, $listen_port);
59  
60 my $len;
61 my $prepare = $self->_accept_prepare_handler(\$listen_host, \$listen_port);
62 if ($prepare) {
63 my ($service, $host) = AnyEvent::Socket::unpack_sockaddr getsockname $state{fh};
64 $len = $prepare && $prepare->( $state{fh}, format_address $host, $service );
65 }
66  
67 $len ||= 128;
68  
69 listen $state{fh}, $len or Carp::croak "listen: $!";
70  
71 my $accept = $self->_accept_handler($app, $is_tcp, \$listen_host, \$listen_port);
72 $state{aw} = AE::io $state{fh}, 0, sub {
73 # this closure keeps $state alive
74 while ($state{fh} && (my $peer = accept my $fh, $state{fh})) {
75 fh_nonblocking $fh, 1; # POSIX requires inheritance, the outside world does not
76  
77 my ($service, $host) = AnyEvent::Socket::unpack_sockaddr($peer);
78 $accept->($fh, format_address $host, $service);
79 }
80 };
81  
82 defined wantarray
83 ? guard { %state = () } # clear fh and watcher, which breaks the circular dependency
84 : ()
85 }
86  
87 1;