Shuvgey/Server.pm untested

filter: Statementstmt 0.0% 0 / 221 Branchbran 0.0% 0 / 62 Conditioncond 0.0% 0 / 82 MC/DCmcdc 0.0% 0 / 51 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 453 CC 32 SCAR 36.6
CC
32
Cov
0%
psgi_env
110.0
run_tcp_server
56.0
start_server
56.0
CRAP 39.0
1 package Shuvgey::Server;
2 use strict;
3 use warnings;
4 use Net::SSLeay;
5 use AnyEvent;
6 use AnyEvent::Socket;
7 use AnyEvent::Handle;
8 use AnyEvent::TLS;
9 use Protocol::HTTP2;
10 use Protocol::HTTP2::Constants qw(const_name :settings);
11 use Protocol::HTTP2::Server;
12 use Data::Dumper;
13 use URI::Escape qw(uri_unescape);
14 use Carp;
15 use Sys::Hostname;
16 use Scalar::Util qw(blessed);
17 require Shuvgey;
18  
19 use constant {
20 TRUE => !undef,
21 FALSE => !!undef,
22  
23 STOP => exists $ENV{SHUVGEY_DEBUG},
24  
25 # Old h2 tls ident for compatibility
26 H2_14 => "h2-14",
27  
28 # Log levels
29 DEBUG => 0,
30 INFO => 1,
31 NOTICE => 2,
32 WARNING => 3,
33 ERROR => 4,
34 CRITICAL => 5,
35 ALERT => 6,
36 EMERGENCY => 7,
37 };
38  
39 my $start_time = 0;
40 my $hostname = hostname;
41  
42 sub talk($$) {
43 if ( shift() >= $ENV{SHUVGEY_DEBUG} ) {
44 my $message = shift;
45 chomp($message);
46 my $now = AnyEvent->now;
47 if ( $now - $start_time < 60 ) {
48 $message =~ s/\n/\n /g;
49 printf "[%05.3f] %s\n", $now - $start_time, $message;
50 }
51 else {
52 my @t = ( localtime() )[ 5, 4, 3, 2, 1, 0 ];
53 $t[0] += 1900;
54 $t[1]++;
55 $message =~ s/\n/\n /g;
56 printf "[%4d-%02d-%02d %02d:%02d:%02d] %s\n", @t, $message;
57 $start_time = $now;
58 }
59 }
60 }
61  
62 sub new {
63 my $class = shift;
64 bless {@_}, $class;
65 }
66  
67 sub run {
68 my ( $self, $app ) = @_;
69  
70 STOP and talk DEBUG, Dumper($self);
71  
72 my ( $host, $port );
73 if ( $self->{listen} ) {
74 ( $self->{host}, $self->{port} ) = split /:/,
75 shift @{ $self->{listen} };
76 }
77  
78 $host = $self->{host} || undef;
79 $port = $self->{port} || undef;
80  
81 if ( !exists $self->{no_tls} ) {
82 STOP and talk INFO, "tls\n";
83 if ( exists $self->{upgrade} ) {
84 $self->{no_tls} = TRUE;
85 }
86 elsif (!exists $self->{tls_crt}
87 || !-r $self->{tls_crt}
88 || !exists $self->{tls_key}
89 || !-r $self->{tls_key} )
90 {
91 croak "Can't read tls_crt or tls_key files\n"
92 . "Use --no_tls option to start Shuvgey without tls";
93 }
94 }
95  
96 $self->{exit} = AnyEvent->condvar;
97  
98 $self->run_tcp_server( $app, $host, $port );
99  
100 my $w;
101 $w = AnyEvent->signal(
102 signal => "TERM",
103 cb => sub {
104 undef $w;
105 $self->finish("Received SIGTERM");
106 }
107 );
108  
109 my $recv = $self->{exit}->recv;
110 STOP and talk INFO, $recv;
111 }
112  
113 sub run_tcp_server {
114 my ( $self, $app, $host, $port ) = @_;
115  
116 tcp_server $host, $port, sub {
117  
118 my ( $fh, $peer_host, $peer_port ) = @_;
119 my $tls;
120  
121 STOP and talk INFO, "Accept connection from $peer_host:$peer_port";
122  
123 if ( !exists $self->{no_tls} ) {
124 $tls = $self->create_tls or return;
125 }
126  
127 my $handle;
128 $handle = AnyEvent::Handle->new(
129 fh => $fh,
130 autocork => 1,
131 $tls
132 ? (
133 tls => "accept",
134 tls_ctx => $tls,
135 on_starttls => sub {
136 my ( $handle, $success, $error_message ) = @_;
137 if ( !$success ) {
138 STOP and talk ERROR, $error_message;
139 }
140 else {
141 my $proto =
142 Net::SSLeay::P_next_proto_negotiated( $handle->{tls} )
143 || '';
144 STOP
145 and talk INFO, "Client negotiated protocol: $proto";
146 if ( $proto ne Protocol::HTTP2::ident_tls
147 && $proto ne H2_14 )
148 {
149 STOP and talk ERROR, "$proto not supported";
150 $handle->push_write( $self->error_505 );
151 $handle->push_shutdown;
152 }
153 else {
154 STOP and talk INFO, "tls started ok";
155 STOP
156 and talk INFO, "cipher: "
157 . Net::SSLeay::get_cipher( $handle->{tls} );
158 $self->start_server( $handle, $app, $host, $port,
159 $peer_host, $peer_port );
160 }
161 }
162 },
163 on_stoptls => sub {
164 my ($handle) = @_;
165 STOP and talk INFO, "tls stoped: <$!>";
166 },
167 )
168 : (),
169 on_error => sub {
170 $_[0]->destroy;
171 STOP and talk ERROR, "connection error";
172 },
173 on_eof => sub {
174 $handle->destroy;
175 }
176 );
177 $self->start_server( $handle, $app, $host, $port, $peer_host,
178 $peer_port )
179 unless $tls;
180 },
181  
182 # Bound to host:port
183 sub {
184 ( undef, $host, $port ) = @_;
185 STOP and talk NOTICE, "Ready to serve request\n";
186  
187 # For Plack::Runner
188 $self->{server_ready}->(
189 {
190 host => $host,
191 port => $port,
192 server_software => 'Shuvgey',
193 }
194 ) if $self->{server_ready};
195 return TRUE;
196 };
197  
198 return TRUE;
199 }
200  
201 sub start_server {
202 my ( $self, $handle, $app, $host, $port, $peer_host, $peer_port ) = @_;
203 my $server;
204  
205 $server = Protocol::HTTP2::Server->new(
206 exists $self->{upgrade} ? ( upgrade => 1 ) : (),
207 settings => { &SETTINGS_MAX_CONCURRENT_STREAMS => 100, },
208 on_change_state => sub {
209 my ( $stream_id, $previous_state, $current_state ) = @_;
210 },
211 on_error => sub {
212 my $error = shift;
213 STOP and talk
214 ERROR,
215 sprintf "Error occured: %s\n",
216 const_name( "errors", $error );
217 },
218 on_request => sub {
219 my ( $stream_id, $headers, $data ) = @_;
220  
221 my $env =
222 $self->psgi_env( $host, $port, $peer_host, $peer_port,
223 $headers, $data );
224  
225 my $response = eval { $app->($env) }
226 || $self->internal_error($@);
227  
228 # TODO: support for CODE
229 if ( ref $response ne 'ARRAY' ) {
230 $response =
231 $self->internal_error("PSGI CODE response not supported yet");
232 }
233  
234 my $body;
235  
236 if ( ref $response->[2] eq 'ARRAY' ) {
237 $body = join '', @{ $response->[2] };
238 }
239 elsif (
240 ref $response->[2] eq 'GLOB'
241 or ( blessed( $response->[2] )
242 && $response->[2]->can('getline') )
243 )
244 {
245 local $/ = \4096;
246 $body = '';
247 while ( defined( my $chunk = $response->[2]->getline ) ) {
248 $body .= $chunk;
249 }
250 }
251 else {
252 STOP and talk INFO, Dumper $response->[2];
253 $response =
254 $self->internal_error( "body ref type "
255 . ( ref $response->[2] )
256 . " not supported yet" );
257 }
258  
259 my @h = ();
260 while ( @{ $response->[1] } ) {
261 my ( $h, $v ) = splice @{ $response->[1] }, 0, 2;
262 STOP and talk INFO, $h . " = " . $v;
263 push @h, $h, $v unless lc($h) eq 'server';
264 }
265 push @h, "Server", "Shuvgey/" . $Shuvgey::VERSION;
266  
267 $server->response(
268 stream_id => $stream_id,
269 ':status' => $response->[0],
270 headers => \@h,
271 data => $body,
272 );
273 },
274 );
275  
276 # First send settings to peer
277 while ( my $frame = $server->next_frame ) {
278 $handle->push_write($frame);
279 }
280  
281 $handle->on_read(
282 sub {
283 my $handle = shift;
284  
285 $server->feed( $handle->{rbuf} );
286  
287 $handle->{rbuf} = undef;
288 while ( my $frame = $server->next_frame ) {
289 $handle->push_write($frame);
290 }
291 $handle->push_shutdown if $server->shutdown;
292 }
293 );
294 ();
295 }
296  
297 sub create_tls {
298 my $self = shift;
299 my $tls;
300  
301 eval {
302 $tls = AnyEvent::TLS->new(
303 method => "TLSv1_2",
304 cert_file => $self->{tls_crt},
305 key_file => $self->{tls_key},
306 );
307  
308 # ECDH curve ( Net-SSLeay >= 1.56, openssl >= 1.0.0 )
309 if ( exists &Net::SSLeay::CTX_set_tmp_ecdh ) {
310 my $curve = Net::SSLeay::OBJ_txt2nid('prime256v1');
311 my $ecdh = Net::SSLeay::EC_KEY_new_by_curve_name($curve);
312 Net::SSLeay::CTX_set_tmp_ecdh( $tls->ctx, $ecdh );
313 Net::SSLeay::EC_KEY_free($ecdh);
314 }
315  
316 # ALPN (Net-SSLeay > 1.55, openssl >= 1.0.2)
317 if ( exists &Net::SSLeay::CTX_set_alpn_select_cb ) {
318 Net::SSLeay::CTX_set_alpn_select_cb( $tls->ctx,
319 [ Protocol::HTTP2::ident_tls, H2_14 ] );
320 }
321  
322 # NPN (Net-SSLeay > 1.45, openssl >= 1.0.1)
323 elsif ( exists &Net::SSLeay::CTX_set_next_protos_advertised_cb ) {
324 Net::SSLeay::CTX_set_next_protos_advertised_cb( $tls->ctx,
325 [ Protocol::HTTP2::ident_tls, H2_14 ] );
326 }
327 else {
328 die "ALPN and NPN are not supported\n";
329 }
330 };
331  
332 $self->finish("Some problem with TLS: $@\n") if $@;
333 return $tls;
334 }
335  
336 sub finish {
337 shift->{exit}->send(shift);
338 }
339  
340 sub psgi_env {
341 my ( $self, $host, $port, $peer_host, $peer_port, $headers, $data ) = @_;
342  
343 my $input;
344 open $input, '<', \$data if defined $data;
345  
346 my $env = {
347 'psgi.version' => [ 1, 1 ],
348 'psgi.input' => $input,
349 'psgi.errors' => *STDERR,
350 'psgi.multithread' => FALSE,
351 'psgi.multiprocess' => FALSE,
352 'psgi.run_once' => FALSE,
353 'psgi.nonblocking' => TRUE,
354 'psgi.streaming' => FALSE,
355 'SCRIPT_NAME' => '',
356 'SERVER_NAME' => $host eq '0.0.0.0' ? $hostname : $host,
357 'SERVER_PORT' => $port,
358  
359 'SERVER_PROTOCOL' => "HTTP/2",
360  
361 # This not in PSGI spec. Why not?
362 'REMOTE_HOST' => $peer_host,
363 'REMOTE_ADDR' => $peer_host,
364 'REMOTE_PORT' => $peer_port,
365 };
366  
367 for my $i ( 0 .. @$headers / 2 - 1 ) {
368 my ( $h, $v ) = ( $headers->[ $i * 2 ], $headers->[ $i * 2 + 1 ] );
369 if ( $h eq ':method' ) {
370 $env->{REQUEST_METHOD} = $v;
371 }
372 elsif ( $h eq ':scheme' ) {
373 $env->{'psgi.url_scheme'} = $v;
374 }
375 elsif ( $h eq ':path' ) {
376 $env->{REQUEST_URI} = $v;
377 my ( $path, $query ) = ( $v =~ /^([^?]*)\??(.*)?$/s );
378 $env->{QUERY_STRING} = $query || '';
379 $env->{PATH_INFO} = uri_unescape($path);
380 }
381 elsif ( $h eq ':authority' ) {
382  
383 #TODO: what to do with :authority?
384 }
385 elsif ( $h eq 'content-length' ) {
386 $env->{CONTENT_LENGTH} = $v;
387 }
388 elsif ( $h eq 'content-type' ) {
389 $env->{CONTENT_TYPE} = $v;
390 }
391 else {
392 my $header = 'HTTP_' . uc($h);
393 if ( exists $env->{$header} ) {
394 $env->{$header} .= ', ' . $v;
395 }
396 else {
397 $env->{$header} = $v;
398 }
399 }
400 }
401 @$headers = ();
402 STOP and talk INFO, Dumper($env);
403 return $env;
404 }
405  
406 sub internal_error {
407 my ( $self, $error ) = @_;
408  
409 my $message = "500 - Internal Server Error";
410 STOP and talk ERROR, "$message: $error\n";
411  
412 return [
413 500,
414 [
415 'Content-Type' => 'text/plain',
416 'Content-Length' => length($message)
417 ],
418 [$message]
419 ];
420 }
421  
422 sub error_505 {
423 my $error =
424 sprintf "Shuvgey supports only HTTP/2 protocol (drafts %s or %s)",
425 Protocol::HTTP2::ident_tls, H2_14;
426 join "\x0d\x0a",
427 "HTTP/1.1 505 HTTP version not supported",
428 "Content-Type: text/plain",
429 "Content-Length: " . length($error),
430 "", $error;
431 }
432  
433 1;