| 1 | package Catalyst::Engine::HTTP::POE; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use base 'Catalyst::Engine::HTTP'; | ||
| 6 | use Data::Dump qw(dump); | ||
| 7 | use HTTP::Body; | ||
| 8 | use HTTP::Date (); | ||
| 9 | use HTTP::Headers; | ||
| 10 | use HTTP::Response; | ||
| 11 | use HTTP::Status (); | ||
| 12 | use POE; | ||
| 13 | use POE::Filter::Line; | ||
| 14 | use POE::Filter::Stream; | ||
| 15 | use POE::Wheel::ReadWrite; | ||
| 16 | use POE::Wheel::SocketFactory; | ||
| 17 | use Socket; | ||
| 18 | use Time::HiRes; | ||
| 19 | |||
| 20 | use Catalyst::Engine::HTTP::Restarter::Watcher; | ||
| 21 | |||
| 22 | our $VERSION = '0.08'; | ||
| 23 | |||
| 24 | # Enable for helpful debugging information | ||
| 25 | sub DEBUG () { $ENV{CATALYST_POE_DEBUG} || 0 } | ||
| 26 | sub BENCH () { $ENV{CATALYST_POE_BENCH} || 0 } | ||
| 27 | |||
| 28 | # Max processes (including parent) | ||
| 29 | sub MAX_PROC () { $ENV{CATALYST_POE_MAX_PROC} || 1 } | ||
| 30 | |||
| 31 | # Keep-alive connection timeout in seconds | ||
| 32 | sub KEEPALIVE_TIMEOUT () { 300 } | ||
| 33 | |||
| 34 | # Benchmark::Stopwatch for profiling | ||
| 35 | if ( BENCH ) { | ||
| 36 | require Benchmark::Stopwatch; | ||
| 37 | } | ||
| 38 | |||
| 39 | sub run { | ||
| 40 | my ( $self, $class, @args ) = @_; | ||
| 41 | |||
| 42 | $self->spawn( $class, @args ); | ||
| 43 | |||
| 44 | POE::Kernel->run; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub spawn { | ||
| 48 | my ( $self, $class, $port, $host, $options ) = @_; | ||
| 49 | |||
| 50 | my $addr = $host ? inet_aton($host) : INADDR_ANY; | ||
| 51 | if ( $addr eq INADDR_ANY ) { | ||
| 52 | require Sys::Hostname; | ||
| 53 | $host = lc Sys::Hostname::hostname(); | ||
| 54 | } | ||
| 55 | else { | ||
| 56 | $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr); | ||
| 57 | } | ||
| 58 | |||
| 59 | $self->{alias} = delete $options->{alias} || 'catalyst-poe'; | ||
| 60 | |||
| 61 | $self->{config} = { | ||
| 62 | appclass => $class, | ||
| 63 | addr => $addr, | ||
| 64 | port => $port, | ||
| 65 | host => $host, | ||
| 66 | options => $options, | ||
| 67 | children => {}, | ||
| 68 | is_a_child => 0, | ||
| 69 | }; | ||
| 70 | |||
| 71 | POE::Session->create( | ||
| 72 | object_states => [ | ||
| 73 | $self => [ | ||
| 74 | qw/_start | ||
| 75 | _stop | ||
| 76 | shutdown | ||
| 77 | child_shutdown | ||
| 78 | dump_state | ||
| 79 | status | ||
| 80 | |||
| 81 | prefork | ||
| 82 | sig_chld | ||
| 83 | |||
| 84 | check_restart | ||
| 85 | restart | ||
| 86 | |||
| 87 | accept_new_client | ||
| 88 | accept_failed | ||
| 89 | |||
| 90 | client_flushed | ||
| 91 | client_error | ||
| 92 | |||
| 93 | read_input | ||
| 94 | process_input | ||
| 95 | process | ||
| 96 | |||
| 97 | handle_prepare | ||
| 98 | prepare_done | ||
| 99 | |||
| 100 | handle_finalize | ||
| 101 | finalize_done | ||
| 102 | client_done | ||
| 103 | |||
| 104 | keepalive_timeout | ||
| 105 | / | ||
| 106 | ], | ||
| 107 | ], | ||
| 108 | ); | ||
| 109 | |||
| 110 | return $self; | ||
| 111 | } | ||
| 112 | |||
| 113 | # start the server | ||
| 114 | sub _start { | ||
| 115 | my ( $kernel, $self ) = @_[ KERNEL, OBJECT ]; | ||
| 116 | |||
| 117 | $kernel->alias_set( $self->{alias} ); | ||
| 118 | |||
| 119 | # take a copy of %ENV | ||
| 120 | $self->{global_env} = \%ENV; | ||
| 121 | |||
| 122 | $self->{listener} = POE::Wheel::SocketFactory->new( | ||
| 123 | ( defined ( $self->{config}->{addr} ) | ||
| 124 | ? ( BindAddress => $self->{config}->{addr} ) | ||
| 125 | : () | ||
| 126 | ), | ||
| 127 | ( defined ( $self->{config}->{port} ) | ||
| 128 | ? ( BindPort => $self->{config}->{port} ) | ||
| 129 | : ( BindPort => 3000 ) | ||
| 130 | ), | ||
| 131 | SuccessEvent => 'accept_new_client', | ||
| 132 | FailureEvent => 'accept_failed', | ||
| 133 | SocketDomain => AF_INET, | ||
| 134 | SocketType => SOCK_STREAM, | ||
| 135 | SocketProtocol => 'tcp', | ||
| 136 | Reuse => 'on', | ||
| 137 | ); | ||
| 138 | |||
| 139 | # dump our state if we get a SIGUSR1 | ||
| 140 | $kernel->sig( USR1 => 'dump_state' ); | ||
| 141 | |||
| 142 | # shutdown on INT and TERM | ||
| 143 | $kernel->sig( INT => 'shutdown' ); | ||
| 144 | $kernel->sig( TERM => 'shutdown' ); | ||
| 145 | |||
| 146 | # restart on HUP | ||
| 147 | $kernel->sig( HUP => 'restart' ); | ||
| 148 | |||
| 149 | # Pre-fork if requested | ||
| 150 | $self->{config}->{options}->{max_proc} ||= MAX_PROC; | ||
| 151 | if ( $self->{config}->{options}->{max_proc} > 1 ) { | ||
| 152 | $kernel->sig( CHLD => 'sig_chld' ); | ||
| 153 | $kernel->yield( 'prefork' ); | ||
| 154 | } | ||
| 155 | |||
| 156 | # Init restarter | ||
| 157 | if ( $self->{config}->{options}->{restart} ) { | ||
| 158 | my $delay = $self->{config}->{options}->{restart_delay} || 1; | ||
| 159 | $kernel->delay_set( 'check_restart', $delay ); | ||
| 160 | } | ||
| 161 | |||
| 162 | my $url = 'http://' . $self->{config}->{host}; | ||
| 163 | $url .= ':' . $self->{config}->{port} | ||
| 164 | unless $self->{config}->{port} == 80; | ||
| 165 | |||
| 166 | $self->{url} = $url; | ||
| 167 | |||
| 168 | print "You can connect to your server at $url\n"; | ||
| 169 | } | ||
| 170 | |||
| 171 | sub _stop { } | ||
| 172 | |||
| 173 | sub shutdown { | ||
| 174 | my ( $kernel, $self ) = @_[ KERNEL, OBJECT ]; | ||
| 175 | |||
| 176 | DEBUG && warn "Catalyst POE engine shutting down...\n"; | ||
| 177 | |||
| 178 | if ( my @children = keys %{ $self->{config}->{children} } ) { | ||
| 179 | DEBUG && warn "Signaling all children to stop...\n"; | ||
| 180 | kill INT => @children; | ||
| 181 | } | ||
| 182 | |||
| 183 | delete $self->{listener}; | ||
| 184 | delete $self->{clients}; | ||
| 185 | |||
| 186 | $kernel->alias_remove( $self->{alias} ); | ||
| 187 | |||
| 188 | return 1; | ||
| 189 | } | ||
| 190 | |||
| 191 | sub child_shutdown { | ||
| 192 | my ( $kernel, $self ) = @_[ KERNEL, OBJECT ]; | ||
| 193 | |||
| 194 | return 0; | ||
| 195 | } | ||
| 196 | |||
| 197 | sub dump_state { | ||
| 198 | my ( $kernel, $self ) = @_[ KERNEL, OBJECT ]; | ||
| 199 | |||
| 200 | my $clients = scalar keys %{ $self->{clients} }; | ||
| 201 | warn "-- POE Engine State --\n"; | ||
| 202 | warn dump( $self ); | ||
| 203 | warn "Active clients: $clients\n"; | ||
| 204 | } | ||
| 205 | |||
| 206 | sub status { | ||
| 207 | my ( $kernel, $self ) = @_[ KERNEL, OBJECT ]; | ||
| 208 | |||
| 209 | # XXX: Include more status stuff here | ||
| 210 | my $status = { | ||
| 211 | url => $self->{url}, | ||
| 212 | active_clients => scalar keys %{ $self->{clients} }, | ||
| 213 | }; | ||
| 214 | |||
| 215 | return $status; | ||
| 216 | } | ||
| 217 | |||
| 218 | sub prefork { | ||
| 219 | my ( $kernel, $self ) = @_[ KERNEL, OBJECT ]; | ||
| 220 | |||
| 221 | return if $self->{config}->{is_a_child}; | ||
| 222 | |||
| 223 | my $max_proc = $self->{config}->{options}->{max_proc}; | ||
| 224 | |||
| 225 | DEBUG && warn 'Preforking ' . ( $max_proc - 1 ) . " children...\n"; | ||
| 226 | |||
| 227 | my $current_children = keys %{ $self->{config}->{children} }; | ||
| 228 | for ( $current_children + 2 .. $max_proc ) { | ||
| 229 | |||
| 230 | my $pid = fork(); | ||
| 231 | |||
| 232 | unless ( defined $pid ) { | ||
| 233 | DEBUG && warn "Server $$ fork failed: $!\n"; | ||
| 234 | $kernel->delay_set( prefork => 1 ); | ||
| 235 | return; | ||
| 236 | } | ||
| 237 | |||
| 238 | # Parent. Add the child process to its list. | ||
| 239 | if ( $pid ) { | ||
| 240 | $self->{config}->{children}->{$pid} = 1; | ||
| 241 | next; | ||
| 242 | } | ||
| 243 | |||
| 244 | # Child. Clear the child process list. | ||
| 245 | DEBUG && warn "Child $$ forked successfully.\n"; | ||
| 246 | $self->{config}->{is_a_child} = 1; | ||
| 247 | $self->{config}->{children} = {}; | ||
| 248 | |||
| 249 | $kernel->sig( INT => 'child_shutdown' ); | ||
| 250 | |||
| 251 | return; | ||
| 252 | } | ||
| 253 | } | ||
| 254 | |||
| 255 | sub sig_chld { | ||
| 256 | my ( $kernel, $self, $child_pid ) = @_[ KERNEL, OBJECT, ARG1 ]; | ||
| 257 | |||
| 258 | if ( delete $self->{config}->{children}->{$child_pid} ) { | ||
| 259 | DEBUG && warn "Server $$ received SIGCHLD from $child_pid.\n"; | ||
| 260 | $kernel->yield( 'prefork' ); | ||
| 261 | } | ||
| 262 | return 0; | ||
| 263 | } | ||
| 264 | |||
| 265 | sub check_restart { | ||
| 266 | my ( $kernel, $self ) = @_[ KERNEL, OBJECT ]; | ||
| 267 | |||
| 268 | # Only check in the parent process | ||
| 269 | return if $self->{config}->{is_a_child}; | ||
| 270 | |||
| 271 | my $options = $self->{config}->{options}; | ||
| 272 | |||
| 273 | # Init watcher object with no delay | ||
| 274 | if ( !$self->{watcher} ) { | ||
| 275 | $self->{watcher} = Catalyst::Engine::HTTP::Restarter::Watcher->new( | ||
| 276 | directory => ( | ||
| 277 | $options->{restart_directory} || | ||
| 278 | File::Spec->catdir( $FindBin::Bin, '..' ) | ||
| 279 | ), | ||
| 280 | regex => $options->{restart_regex}, | ||
| 281 | # current Cat versions will 'sleep 1' if this is 0 | ||
| 282 | delay => 0.00000000001, | ||
| 283 | ); | ||
| 284 | } | ||
| 285 | |||
| 286 | my @changed_files = $self->{watcher}->watch(); | ||
| 287 | |||
| 288 | # Restart if any files have changed | ||
| 289 | if (@changed_files) { | ||
| 290 | my $files = join ', ', @changed_files; | ||
| 291 | print STDERR qq/File(s) "$files" modified, restarting\n\n/; | ||
| 292 | |||
| 293 | $kernel->yield( 'restart' ); | ||
| 294 | } | ||
| 295 | else { | ||
| 296 | # Schedule next check | ||
| 297 | $kernel->delay_set( 'check_restart', $options->{restart_delay} ); | ||
| 298 | } | ||
| 299 | } | ||
| 300 | |||
| 301 | sub restart { | ||
| 302 | my ( $kernel, $self ) = @_[ KERNEL, OBJECT ]; | ||
| 303 | |||
| 304 | $kernel->call( 'catalyst-poe', 'shutdown' ); | ||
| 305 | |||
| 306 | ### if the standalone server was invoked with perl -I .. we will loose | ||
| 307 | ### those include dirs upon re-exec. So add them to PERL5LIB, so they | ||
| 308 | ### are available again for the exec'ed process --kane | ||
| 309 | use Config; | ||
| 310 | $ENV{PERL5LIB} .= join $Config{path_sep}, @INC; | ||
| 311 | |||
| 312 | my $options = $self->{config}->{options}; | ||
| 313 | exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } ); | ||
| 314 | } | ||
| 315 | |||
| 316 | sub accept_new_client { | ||
| 317 | my ( $kernel, $self, $socket, $peeraddr, $peerport ) | ||
| 318 | = @_[ KERNEL, OBJECT, ARG0 .. ARG2 ]; | ||
| 319 | |||
| 320 | my $stopwatch; | ||
| 321 | if ( BENCH ) { | ||
| 322 | $stopwatch = Benchmark::Stopwatch->new->start; | ||
| 323 | } | ||
| 324 | |||
| 325 | $peeraddr = inet_ntoa($peeraddr); | ||
| 326 | |||
| 327 | my $wheel = POE::Wheel::ReadWrite->new( | ||
| 328 | Handle => $socket, | ||
| 329 | Filter => POE::Filter::Stream->new, | ||
| 330 | FlushedEvent => 'client_flushed', | ||
| 331 | ErrorEvent => 'client_error', | ||
| 332 | HighMark => 128 * 1024, | ||
| 333 | HighEvent => sub {}, # useless, never gets called | ||
| 334 | LowMark => 8 * 1024, | ||
| 335 | LowEvent => sub {}, # also useless, we can use FlushedEvent | ||
| 336 | ); | ||
| 337 | |||
| 338 | # get the local connection information | ||
| 339 | my $local_sockaddr = getsockname($socket); | ||
| 340 | my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr); | ||
| 341 | my $localaddr = inet_ntoa($localiaddr) || '127.0.0.1'; | ||
| 342 | my $localname = gethostbyaddr( $localiaddr, AF_INET ) || 'localhost'; | ||
| 343 | |||
| 344 | my $ID = $wheel->ID; | ||
| 345 | |||
| 346 | $self->{clients}->{$ID} = { | ||
| 347 | wheel => $wheel, | ||
| 348 | socket => $socket, | ||
| 349 | peeraddr => $peeraddr, | ||
| 350 | peerport => $peerport, | ||
| 351 | localaddr => $localaddr, | ||
| 352 | localname => $localname, | ||
| 353 | |||
| 354 | requests => 0, | ||
| 355 | inputbuf => '', | ||
| 356 | written => 0, | ||
| 357 | |||
| 358 | stopwatch => $stopwatch, | ||
| 359 | }; | ||
| 360 | |||
| 361 | DEBUG && warn "[$ID] [$$] New connection (wheel $ID from $peeraddr:$peerport)\n"; | ||
| 362 | |||
| 363 | # Wait for some data to read | ||
| 364 | $poe_kernel->select_read( $socket, 'read_input', $ID ); | ||
| 365 | } | ||
| 366 | |||
| 367 | sub accept_failed { | ||
| 368 | my ( $kernel, $self, $op, $errnum, $errstr ) = @_[ KERNEL, OBJECT, ARG0 .. ARG2 ]; | ||
| 369 | |||
| 370 | warn "Unable to start server: $op error $errnum: $errstr\n"; | ||
| 371 | |||
| 372 | $kernel->yield('shutdown'); | ||
| 373 | } | ||
| 374 | |||
| 375 | sub client_error { | ||
| 376 | my ( $kernel, $self, $op, $errnum, $errstr, $ID ) = @_[ KERNEL, OBJECT, ARG0 .. ARG3 ]; | ||
| 377 | |||
| 378 | DEBUG && warn "[$ID] [$$] Wheel generated $op error $errnum: $errstr\n"; | ||
| 379 | |||
| 380 | delete $self->{clients}->{$ID}; | ||
| 381 | } | ||
| 382 | |||
| 383 | sub read_input { | ||
| 384 | my ( $kernel, $self, $handle, $ID ) = @_[ KERNEL, OBJECT, ARG0, ARG2 ]; | ||
| 385 | |||
| 386 | my $client = $self->{clients}->{$ID} || return; | ||
| 387 | |||
| 388 | BENCH && $client->{stopwatch}->lap('read_input'); | ||
| 389 | |||
| 390 | # Clear the keepalive timeout timer if set | ||
| 391 | if ( my $timer = delete $client->{_timeout_timer} ) { | ||
| 392 | $kernel->alarm_remove( $timer ); | ||
| 393 | } | ||
| 394 | |||
| 395 | # Read some data from the driver | ||
| 396 | my $driver = $client->{wheel}->[ $client->{wheel}->DRIVER_BOTH ]; | ||
| 397 | my $buffer_ref = $driver->get( $handle ); | ||
| 398 | |||
| 399 | if ( !$buffer_ref ) { | ||
| 400 | # Error, stop reading and shut down this client | ||
| 401 | DEBUG && warn "[$ID] [$$] Error reading, disconnecting\n"; | ||
| 402 | $kernel->select_read( $handle ); | ||
| 403 | delete $self->{clients}->{$ID}; | ||
| 404 | return; | ||
| 405 | } | ||
| 406 | |||
| 407 | $client->{inputbuf} .= join '', @{$buffer_ref}; | ||
| 408 | |||
| 409 | DEBUG && warn "[$ID] [$$] read_input (" . length( $client->{inputbuf} ) . " bytes in buffer)\n"; | ||
| 410 | |||
| 411 | $kernel->yield( 'process_input', $ID ); | ||
| 412 | } | ||
| 413 | |||
| 414 | sub process_input { | ||
| 415 | my ( $kernel, $self, $ID ) = @_[ KERNEL, OBJECT, ARG0 ]; | ||
| 416 | |||
| 417 | my $client = $self->{clients}->{$ID} || return; | ||
| 418 | |||
| 419 | # Have we started processing the body? | ||
| 420 | if ( exists $client->{_read} ) { | ||
| 421 | |||
| 422 | _process_chunk( $client ); | ||
| 423 | |||
| 424 | return; | ||
| 425 | } | ||
| 426 | |||
| 427 | # Have we already parsed headers | ||
| 428 | return if $client->{_headers}; | ||
| 429 | |||
| 430 | # Have we read enough to include all headers? | ||
| 431 | if ( $client->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s ) { | ||
| 432 | $client->{_headers} = 1; | ||
| 433 | |||
| 434 | # Copy the buffer for header parsing, and remove the header block | ||
| 435 | # from the content buffer. | ||
| 436 | my $buf = $client->{inputbuf}; | ||
| 437 | $client->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s; | ||
| 438 | |||
| 439 | # Parse the request line. | ||
| 440 | if ( $buf !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) { | ||
| 441 | # Invalid request | ||
| 442 | DEBUG && warn "[$ID] [$$] Bad request: $buf\n"; | ||
| 443 | |||
| 444 | my $status = 400; | ||
| 445 | my $message = HTTP::Status::status_message($status); | ||
| 446 | my $response = HTTP::Response->new( $status => $message ); | ||
| 447 | $response->content_type( 'text/plain' ); | ||
| 448 | $response->content( "$status $message" ); | ||
| 449 | # XXX: fix to use CRLF | ||
| 450 | $client->{wheel}->put( $response->as_string ); | ||
| 451 | return; | ||
| 452 | } | ||
| 453 | |||
| 454 | my $method = $1; | ||
| 455 | my $uri = $2; | ||
| 456 | my $proto = $3 || 'HTTP/0.9'; | ||
| 457 | |||
| 458 | DEBUG && warn "[$ID] [$$] process_input: Parsing headers ($method $uri $proto)\n"; | ||
| 459 | |||
| 460 | # Initialize CGI environment | ||
| 461 | my ( $path, $query_string ) = split /\?/, $uri, 2; | ||
| 462 | my %env = ( | ||
| 463 | PATH_INFO => $path || '', | ||
| 464 | QUERY_STRING => $query_string || '', | ||
| 465 | REMOTE_ADDR => $client->{peeraddr}, | ||
| 466 | REMOTE_HOST => $client->{peeraddr}, | ||
| 467 | REQUEST_METHOD => $method || '', | ||
| 468 | SERVER_NAME => $client->{localname}, | ||
| 469 | SERVER_PORT => $self->{config}->{port}, | ||
| 470 | SERVER_PROTOCOL => $proto, | ||
| 471 | %{ $self->{global_env} }, | ||
| 472 | ); | ||
| 473 | |||
| 474 | # Parse headers | ||
| 475 | my $headers = HTTP::Headers->new; | ||
| 476 | my ($key, $val); | ||
| 477 | HEADER: | ||
| 478 | while ( $buf =~ s/^([^\012]*)\012// ) { | ||
| 479 | $_ = $1; | ||
| 480 | s/\015$//; | ||
| 481 | if ( /^([\w\-~]+)\s*:\s*(.*)/ ) { | ||
| 482 | $headers->push_header( $key, $val ) if $key; | ||
| 483 | ($key, $val) = ($1, $2); | ||
| 484 | } | ||
| 485 | elsif ( /^\s+(.*)/ ) { | ||
| 486 | $val .= " $1"; | ||
| 487 | } | ||
| 488 | else { | ||
| 489 | last HEADER; | ||
| 490 | } | ||
| 491 | } | ||
| 492 | $headers->push_header( $key, $val ) if $key; | ||
| 493 | |||
| 494 | DEBUG && warn "[$ID] [$$] " . dump($headers) . "\n"; | ||
| 495 | |||
| 496 | # Convert headers into ENV vars | ||
| 497 | $headers->scan( sub { | ||
| 498 | my ( $key, $val ) = @_; | ||
| 499 | |||
| 500 | $key = uc $key; | ||
| 501 | $key = 'COOKIE' if $key eq 'COOKIES'; | ||
| 502 | $key =~ tr/-/_/; | ||
| 503 | $key = 'HTTP_' . $key | ||
| 504 | unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/; | ||
| 505 | |||
| 506 | if ( exists $env{$key} ) { | ||
| 507 | $env{$key} .= ", $val"; | ||
| 508 | } | ||
| 509 | else { | ||
| 510 | $env{$key} = $val; | ||
| 511 | } | ||
| 512 | } ); | ||
| 513 | |||
| 514 | $client->{env} = \%env; | ||
| 515 | |||
| 516 | $kernel->yield( 'process', $ID ); | ||
| 517 | } | ||
| 518 | } | ||
| 519 | |||
| 520 | sub process { | ||
| 521 | my ( $kernel, $self, $ID ) = @_[ KERNEL, OBJECT, ARG0 ]; | ||
| 522 | |||
| 523 | my $class = $self->{config}->{appclass}; | ||
| 524 | |||
| 525 | # This request may be executing within another request, | ||
| 526 | # so we must localize all of NEXT so it doesn't get confused about what's | ||
| 527 | # already been called | ||
| 528 | local $NEXT::NEXT{ $class, 'prepare' }; | ||
| 529 | local $NEXT::NEXT{ $class, 'prepare_request' }; | ||
| 530 | local $NEXT::NEXT{ $class, 'prepare_connection' }; | ||
| 531 | local $NEXT::NEXT{ $class, 'prepare_query_parameters' }; | ||
| 532 | local $NEXT::NEXT{ $class, 'prepare_headers' }; | ||
| 533 | local $NEXT::NEXT{ $class, 'prepare_cookies' }; | ||
| 534 | local $NEXT::NEXT{ $class, 'prepare_path' }; | ||
| 535 | local $NEXT::NEXT{ $class, 'prepare_body' }; | ||
| 536 | |||
| 537 | local $NEXT::NEXT{ $class, 'finalize_uploads' }; | ||
| 538 | local $NEXT::NEXT{ $class, 'finalize_error' }; | ||
| 539 | local $NEXT::NEXT{ $class, 'finalize_headers' }; | ||
| 540 | local $NEXT::NEXT{ $class, 'finalize_body' }; | ||
| 541 | |||
| 542 | # pass flow control to Catalyst | ||
| 543 | my $status = $class->handle_request( $ID ); | ||
| 544 | } | ||
| 545 | |||
| 546 | # Prepare handles the entire prepare stage so we can yield to each step | ||
| 547 | sub prepare { | ||
| 548 | my ( $self, $c, $ID ) = @_; | ||
| 549 | |||
| 550 | DEBUG && warn "[$ID] [$$] - prepare\n"; | ||
| 551 | |||
| 552 | # store our ID in context | ||
| 553 | $c->{_POE_ID} = $ID; | ||
| 554 | |||
| 555 | my $client = $self->{clients}->{$ID} || return; | ||
| 556 | $client->{context} = $c; | ||
| 557 | |||
| 558 | $client->{_prepare_done} = 0; | ||
| 559 | |||
| 560 | BENCH && $client->{stopwatch}->lap('prepare'); | ||
| 561 | |||
| 562 | $poe_kernel->yield( 'handle_prepare', 'prepare_request', $ID ); | ||
| 563 | $poe_kernel->yield( 'handle_prepare', 'prepare_connection', $ID ); | ||
| 564 | $poe_kernel->yield( 'handle_prepare', 'prepare_query_parameters', $ID ); | ||
| 565 | $poe_kernel->yield( 'handle_prepare', 'prepare_headers', $ID ); | ||
| 566 | $poe_kernel->yield( 'handle_prepare', 'prepare_cookies', $ID ); | ||
| 567 | $poe_kernel->yield( 'handle_prepare', 'prepare_path', $ID ); | ||
| 568 | |||
| 569 | # If parse_on_demand is set, prepare_body will be called later | ||
| 570 | unless ( $c->config->{parse_on_demand} ) { | ||
| 571 | $poe_kernel->yield( 'handle_prepare', 'prepare_body', $ID ); | ||
| 572 | |||
| 573 | # prepare_body calls prepare_done after reading all data | ||
| 574 | } | ||
| 575 | else { | ||
| 576 | # Parse on demand will call prepare_body later, so we're done with | ||
| 577 | # the rest of the prepare cycle now | ||
| 578 | $poe_kernel->yield( 'prepare_done', $ID ); | ||
| 579 | } | ||
| 580 | |||
| 581 | # Wait until all prepare processing has completed, or we will return too | ||
| 582 | # early | ||
| 583 | # XXX: Is there a better way to handle this? | ||
| 584 | while ( !$client->{_prepare_done} ) { | ||
| 585 | $poe_kernel->run_one_timeslice(); | ||
| 586 | } | ||
| 587 | |||
| 588 | return $c; | ||
| 589 | } | ||
| 590 | |||
| 591 | # handle_prepare localizes our per-client %ENV and calls $c->$method | ||
| 592 | # Allows plugins to do things during each step | ||
| 593 | sub handle_prepare { | ||
| 594 | my ( $kernel, $self, $method, $ID ) = @_[ KERNEL, OBJECT, ARG0, ARG1 ]; | ||
| 595 | |||
| 596 | DEBUG && warn "[$ID] [$$] - $method\n"; | ||
| 597 | |||
| 598 | my $client = $self->{clients}->{$ID} || return; | ||
| 599 | |||
| 600 | BENCH && $client->{stopwatch}->lap(" - $method"); | ||
| 601 | |||
| 602 | { | ||
| 603 | local (*ENV) = $client->{env}; | ||
| 604 | $client->{context}->$method(); | ||
| 605 | } | ||
| 606 | } | ||
| 607 | |||
| 608 | sub prepare_body { | ||
| 609 | my ( $self, $c ) = @_; | ||
| 610 | |||
| 611 | my $ID = $c->{_POE_ID}; | ||
| 612 | my $client = $self->{clients}->{$ID} || return; | ||
| 613 | |||
| 614 | BENCH && $client->{stopwatch}->lap('prepare_body'); | ||
| 615 | |||
| 616 | # Initialize the HTTP::Body object | ||
| 617 | my $type = $c->request->header('Content-Type'); | ||
| 618 | my $length = $c->request->header('Content-Length') | ||
| 619 | || length( $client->{inputbuf} ) | ||
| 620 | || 0; | ||
| 621 | |||
| 622 | # Catalyst >= 5.7007 has support for bypassing HTTP::Body object | ||
| 623 | if ( !$length && $Catalyst::VERSION ge '5.7007' ) { | ||
| 624 | # Defined but will cause all body code to be skipped | ||
| 625 | $c->request->{_body} = 0; | ||
| 626 | |||
| 627 | $poe_kernel->yield( 'prepare_done', $ID ); | ||
| 628 | return; | ||
| 629 | } | ||
| 630 | |||
| 631 | unless ( $c->request->{_body} ) { | ||
| 632 | $c->request->{_body} = HTTP::Body->new( $type, $length ); | ||
| 633 | } | ||
| 634 | |||
| 635 | if ( !$length ) { | ||
| 636 | # Nothing to parse, we're done | ||
| 637 | $poe_kernel->yield( 'prepare_done', $ID ); | ||
| 638 | return; | ||
| 639 | } | ||
| 640 | |||
| 641 | DEBUG && warn "[$ID] [$$] Processing body data (total length: $length)\n"; | ||
| 642 | |||
| 643 | # Read some more data | ||
| 644 | $client->{_prepare_body_done} = 0; | ||
| 645 | $client->{_read} = 0; | ||
| 646 | $client->{_read_length} = $length; | ||
| 647 | |||
| 648 | # First process any data that is already in our input buffer | ||
| 649 | if ( $client->{inputbuf} ) { | ||
| 650 | _process_chunk( $client ); | ||
| 651 | } | ||
| 652 | |||
| 653 | # If we have more body data to read, this will be processed in process_input | ||
| 654 | |||
| 655 | # We need to wait until all body data is read before returning | ||
| 656 | while ( !$client->{_prepare_body_done} ) { | ||
| 657 | $poe_kernel->run_one_timeslice(); | ||
| 658 | } | ||
| 659 | |||
| 660 | $poe_kernel->yield( 'prepare_done', $ID ); | ||
| 661 | } | ||
| 662 | |||
| 663 | sub prepare_done { | ||
| 664 | my ( $kernel, $self, $ID ) = @_[ KERNEL, OBJECT, ARG0 ]; | ||
| 665 | |||
| 666 | my $client = $self->{clients}->{$ID} || return; | ||
| 667 | |||
| 668 | DEBUG && warn "[$ID] [$$] prepare_done\n"; | ||
| 669 | # DEBUG && warn dump( $self->{clients}->{$ID}->{context} ); | ||
| 670 | |||
| 671 | $client->{_prepare_done} = 1; | ||
| 672 | |||
| 673 | BENCH && $client->{stopwatch}->lap('prepare_done'); | ||
| 674 | } | ||
| 675 | |||
| 676 | # Finalize handles the entire finalize stage | ||
| 677 | sub finalize { | ||
| 678 | my ( $self, $c ) = @_; | ||
| 679 | |||
| 680 | my $ID = $c->{_POE_ID}; | ||
| 681 | my $client = $self->{clients}->{$ID} || return; | ||
| 682 | |||
| 683 | BENCH && $client->{stopwatch}->lap('finalize'); | ||
| 684 | |||
| 685 | $client->{_finalize_done} = 0; | ||
| 686 | |||
| 687 | $poe_kernel->yield( 'handle_finalize', 'finalize_uploads', $ID ); | ||
| 688 | |||
| 689 | if ( $#{ $c->error } >= 0 ) { | ||
| 690 | $poe_kernel->yield( 'handle_finalize', 'finalize_error', $ID ); | ||
| 691 | } | ||
| 692 | |||
| 693 | $poe_kernel->yield( 'handle_finalize', 'finalize_headers', $ID ); | ||
| 694 | |||
| 695 | $poe_kernel->yield( 'handle_finalize', 'finalize_body', $ID ); | ||
| 696 | |||
| 697 | $poe_kernel->yield( 'finalize_done', $ID ); | ||
| 698 | |||
| 699 | while ( !$client->{_finalize_done} ) { | ||
| 700 | $poe_kernel->run_one_timeslice(); | ||
| 701 | } | ||
| 702 | |||
| 703 | return $c->response->status; | ||
| 704 | } | ||
| 705 | |||
| 706 | sub handle_finalize { | ||
| 707 | my ( $kernel, $self, $method, $ID ) = @_[ KERNEL, OBJECT, ARG0, ARG1 ]; | ||
| 708 | |||
| 709 | DEBUG && warn "[$ID] [$$] - $method\n"; | ||
| 710 | |||
| 711 | my $client = $self->{clients}->{$ID} || return; | ||
| 712 | |||
| 713 | BENCH && $client->{stopwatch}->lap(" - $method"); | ||
| 714 | |||
| 715 | # Set the response body to null when we're doing a HEAD request. | ||
| 716 | # Must be done here so finalize_headers can still set the proper | ||
| 717 | # Content-Length value | ||
| 718 | if ( $method eq 'finalize_body' ) { | ||
| 719 | if ( $client->{context}->request->method eq 'HEAD' ) { | ||
| 720 | $client->{context}->response->body(''); | ||
| 721 | } | ||
| 722 | } | ||
| 723 | |||
| 724 | $client->{context}->$method(); | ||
| 725 | } | ||
| 726 | |||
| 727 | sub finalize_headers { | ||
| 728 | my ( $self, $c ) = @_; | ||
| 729 | |||
| 730 | my $client = $self->{clients}->{ $c->{_POE_ID} } || return; | ||
| 731 | |||
| 732 | BENCH && $client->{stopwatch}->lap('finalize_headers'); | ||
| 733 | |||
| 734 | my $protocol = 'HTTP/1.0'; # We're not HTTP/1.1 (yet) | ||
| 735 | my $status = $c->response->status; | ||
| 736 | my $message = HTTP::Status::status_message($status); | ||
| 737 | |||
| 738 | my @headers; | ||
| 739 | push @headers, "$protocol $status $message"; | ||
| 740 | |||
| 741 | $c->response->headers->header( Date => HTTP::Date::time2str(time) ); | ||
| 742 | |||
| 743 | # Some notes: I found that to get keepalive mode to perform well under ab, | ||
| 744 | # I had to send all data in a single put() call, so the second put in write() below is | ||
| 745 | # what caused keepalive to be so slow. Not sure if this is just a quirk with ab | ||
| 746 | # or really a performance problem. :( | ||
| 747 | |||
| 748 | # Should we keep the connection open? | ||
| 749 | my $connection = $c->request->header('Connection'); | ||
| 750 | if ( $connection && $connection =~ /^keep-alive$/i ) { | ||
| 751 | $c->response->headers->header( Connection => 'keep-alive' ); | ||
| 752 | $client->{_keepalive} = 1; | ||
| 753 | } | ||
| 754 | else { | ||
| 755 | $c->response->headers->header( Connection => 'close' ); | ||
| 756 | } | ||
| 757 | |||
| 758 | push @headers, $c->response->headers->as_string("\x0D\x0A"); | ||
| 759 | |||
| 760 | # Buffer the headers so they are sent with the first write() call | ||
| 761 | # This reduces the number of TCP packets we are sending | ||
| 762 | $client->{_header_buf} = join("\x0D\x0A", @headers, ''); | ||
| 763 | } | ||
| 764 | |||
| 765 | sub finalize_done { | ||
| 766 | my ( $kernel, $self, $ID ) = @_[ KERNEL, OBJECT, ARG0 ]; | ||
| 767 | |||
| 768 | DEBUG && warn "[$ID] [$$] finalize_done\n"; | ||
| 769 | |||
| 770 | my $client = $self->{clients}->{$ID} || return; | ||
| 771 | |||
| 772 | # If we did not send our headers yet (we had no body), send them now | ||
| 773 | if ( my $headers = delete $client->{_header_buf} ) { | ||
| 774 | $client->{wheel}->put( $headers ); | ||
| 775 | } | ||
| 776 | |||
| 777 | $client->{_finalize_done} = 1; | ||
| 778 | |||
| 779 | BENCH && $client->{stopwatch}->lap('finalize_done'); | ||
| 780 | } | ||
| 781 | |||
| 782 | sub write { | ||
| 783 | my ( $self, $c, $buffer ) = @_; | ||
| 784 | |||
| 785 | my $ID = $c->{_POE_ID}; | ||
| 786 | my $client = $self->{clients}->{$ID} || return; | ||
| 787 | |||
| 788 | BENCH && $client->{stopwatch}->lap('write'); | ||
| 789 | |||
| 790 | # keep track of the amount of data we've sent | ||
| 791 | $client->{_written} += length $buffer; | ||
| 792 | DEBUG && warn "[$ID] [$$] written: " . $client->{_written} . "\n"; | ||
| 793 | |||
| 794 | # Add headers to the first write() call | ||
| 795 | if ( my $headers = delete $client->{_header_buf} ) { | ||
| 796 | $client->{_highmark_reached} = $client->{wheel}->put( $headers . $buffer ); | ||
| 797 | } | ||
| 798 | else { | ||
| 799 | $client->{_highmark_reached} = $client->{wheel}->put( $buffer ); | ||
| 800 | } | ||
| 801 | |||
| 802 | # if the output buffer has reached the highmark, we have a | ||
| 803 | # lot of outgoing data. Don't return until it's been sent | ||
| 804 | while ( $client && $client->{_highmark_reached} ) { | ||
| 805 | $poe_kernel->run_one_timeslice(); | ||
| 806 | } | ||
| 807 | |||
| 808 | # always return 1, we can't detect failures here | ||
| 809 | return 1; | ||
| 810 | } | ||
| 811 | |||
| 812 | # client_flushed is called when all data is done being written to the browser | ||
| 813 | sub client_flushed { | ||
| 814 | my ( $kernel, $self, $ID ) = @_[ KERNEL, OBJECT, ARG0 ]; | ||
| 815 | |||
| 816 | my $client = $self->{clients}->{$ID} || return; | ||
| 817 | |||
| 818 | BENCH && $client->{stopwatch}->lap('client_flushed'); | ||
| 819 | |||
| 820 | # Are we done writing? | ||
| 821 | if ( $client->{context} ) { | ||
| 822 | my $cl = $client->{context}->response->content_length; | ||
| 823 | if ( $cl && $client->{_written} >= $cl ) { | ||
| 824 | DEBUG && warn "[$ID] [$$] client_flushed, written full content-length\n"; | ||
| 825 | $kernel->yield( 'client_done', $ID ); | ||
| 826 | return; | ||
| 827 | } | ||
| 828 | } | ||
| 829 | |||
| 830 | # if we get this event because of the highmark being reached | ||
| 831 | # don't clean up but reset the highmark value to 0 | ||
| 832 | if ( $client->{_highmark_reached} ) { | ||
| 833 | $client->{_highmark_reached} = 0; | ||
| 834 | return; | ||
| 835 | } | ||
| 836 | |||
| 837 | # we may have not had a content-length... | ||
| 838 | $kernel->yield( 'client_done', $ID ); | ||
| 839 | } | ||
| 840 | |||
| 841 | sub client_done { | ||
| 842 | my ( $kernel, $self, $ID ) = @_[ KERNEL, OBJECT, ARG0 ]; | ||
| 843 | |||
| 844 | my $client = $self->{clients}->{$ID} || return; | ||
| 845 | |||
| 846 | BENCH && warn "[$ID] [$$] Stopwatch:\n" . $client->{stopwatch}->stop->summary; | ||
| 847 | |||
| 848 | # clean up everything about this client unless we are using keepalive | ||
| 849 | if ( $client->{_keepalive} ) { | ||
| 850 | DEBUG && warn "[$ID] [$$] client_done, keepalive enabled, waiting for more requests\n"; | ||
| 851 | $client->{requests}++; | ||
| 852 | |||
| 853 | # Clear important variables from the previous state | ||
| 854 | delete $client->{_headers}; | ||
| 855 | delete $client->{_written}; | ||
| 856 | delete $client->{_read}; | ||
| 857 | |||
| 858 | if ( BENCH ) { | ||
| 859 | $client->{stopwatch} = Benchmark::Stopwatch->new->start; | ||
| 860 | } | ||
| 861 | |||
| 862 | # timeout idle connection after some seconds | ||
| 863 | $client->{_timeout_timer} = $kernel->delay_set( 'keepalive_timeout', KEEPALIVE_TIMEOUT, $ID ); | ||
| 864 | } | ||
| 865 | else { | ||
| 866 | DEBUG && warn "[$ID] [$$] client_done, closing connection\n"; | ||
| 867 | delete $self->{clients}->{$ID}; | ||
| 868 | } | ||
| 869 | } | ||
| 870 | |||
| 871 | sub keepalive_timeout { | ||
| 872 | my ( $kernel, $self, $ID ) = @_[ KERNEL, OBJECT, ARG0 ]; | ||
| 873 | |||
| 874 | DEBUG && warn "[$ID] [$$] Timing out idle keepalive connection\n"; | ||
| 875 | |||
| 876 | delete $self->{clients}->{$ID}; | ||
| 877 | } | ||
| 878 | |||
| 879 | # Process a chunk of body data | ||
| 880 | sub _process_chunk { | ||
| 881 | my $client = shift; | ||
| 882 | |||
| 883 | # Read no more than content-length | ||
| 884 | my $cl = $client->{env}->{CONTENT_LENGTH} || length( $client->{inputbuf} ) || 0; | ||
| 885 | |||
| 886 | my $buf = substr $client->{inputbuf}, 0, $cl, ''; | ||
| 887 | my $read = length($buf); | ||
| 888 | |||
| 889 | return unless $read; | ||
| 890 | |||
| 891 | $client->{context}->prepare_body_chunk( $buf ); | ||
| 892 | |||
| 893 | $client->{_read} += $read; | ||
| 894 | |||
| 895 | if ( DEBUG ) { | ||
| 896 | my $ID = $client->{wheel}->ID; | ||
| 897 | my $togo = $client->{_read_length} - $client->{_read}; | ||
| 898 | warn "[$ID] [$$] prepare_body: Read $read bytes ($togo to go)\n"; | ||
| 899 | } | ||
| 900 | |||
| 901 | # Is that all the body data? | ||
| 902 | if ( $client->{_read} >= $client->{_read_length} ) { | ||
| 903 | # Some browsers (like MSIE 5.01) send extra CRLFs after the content | ||
| 904 | # so we need to strip it away | ||
| 905 | $client->{inputbuf} =~ s/^\s+//; | ||
| 906 | |||
| 907 | $client->{_prepare_body_done} = 1; | ||
| 908 | } | ||
| 909 | } | ||
| 910 | |||
| 911 | 1; | ||
| 912 | __END__ |