| 1 | package YAHC; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | our $VERSION = '0.006'; | ||
| 7 | |||
| 8 | use EV; | ||
| 9 | use Time::HiRes; | ||
| 10 | use Exporter 'import'; | ||
| 11 | use Scalar::Util qw/weaken/; | ||
| 12 | use Fcntl qw/F_GETFL F_SETFL O_NONBLOCK/; | ||
| 13 | use POSIX qw/EINPROGRESS EINTR EAGAIN EWOULDBLOCK strftime/; | ||
| 14 | use Socket qw/PF_INET SOCK_STREAM $CRLF SOL_SOCKET SO_ERROR SO_RCVTIMEO SO_SNDTIMEO inet_aton inet_ntoa pack_sockaddr_in/; | ||
| 15 | |||
| 16 | sub YAHC::Error::NO_ERROR () { 0 } | ||
| 17 | sub YAHC::Error::REQUEST_TIMEOUT () { 1 << 0 } | ||
| 18 | sub YAHC::Error::CONNECT_TIMEOUT () { 1 << 1 } | ||
| 19 | sub YAHC::Error::READ_TIMEOUT () { 1 << 2 } | ||
| 20 | sub YAHC::Error::WRITE_TIMEOUT () { 1 << 3 } | ||
| 21 | sub YAHC::Error::CONNECT_ERROR () { 1 << 4 } | ||
| 22 | sub YAHC::Error::READ_ERROR () { 1 << 5 } | ||
| 23 | sub YAHC::Error::WRITE_ERROR () { 1 << 6 } | ||
| 24 | sub YAHC::Error::REQUEST_ERROR () { 1 << 7 } | ||
| 25 | sub YAHC::Error::RESPONSE_ERROR () { 1 << 8 } | ||
| 26 | sub YAHC::Error::CALLBACK_ERROR () { 1 << 9 } | ||
| 27 | sub YAHC::Error::INTERNAL_ERROR () { 1 << 31 } | ||
| 28 | |||
| 29 | sub YAHC::State::INITIALIZED () { 1 << 0 } | ||
| 30 | sub YAHC::State::RESOLVE_DNS () { 1 << 1 } | ||
| 31 | sub YAHC::State::WAIT_SYNACK () { 1 << 2 } | ||
| 32 | sub YAHC::State::CONNECTED () { 1 << 3 } | ||
| 33 | sub YAHC::State::WRITING () { 1 << 4 } | ||
| 34 | sub YAHC::State::READING () { 1 << 5 } | ||
| 35 | sub YAHC::State::USER_ACTION () { 1 << 15 } | ||
| 36 | sub YAHC::State::COMPLETED () { 1 << 30 } # terminal state | ||
| 37 | |||
| 38 | use constant { | ||
| 39 | HTTP_PORT => 80, | ||
| 40 | TCP_READ_CHUNK => 65536, | ||
| 41 | CALLBACKS => [ qw/init_callback wait_synack_callback connected_callback | ||
| 42 | writing_callback reading_callback completed_callback callback/ ], | ||
| 43 | }; | ||
| 44 | |||
| 45 | our @EXPORT_OK = qw/ | ||
| 46 | yahc_reinit_conn | ||
| 47 | yahc_conn_last_error | ||
| 48 | yahc_conn_id | ||
| 49 | yahc_conn_url | ||
| 50 | yahc_conn_state | ||
| 51 | yahc_conn_errors | ||
| 52 | yahc_conn_timeline | ||
| 53 | yahc_conn_request | ||
| 54 | yahc_conn_response | ||
| 55 | /; | ||
| 56 | |||
| 57 | our %EXPORT_TAGS = (all => \@EXPORT_OK); | ||
| 58 | |||
| 59 | ################################################################################ | ||
| 60 | # User facing functons | ||
| 61 | ################################################################################ | ||
| 62 | |||
| 63 | sub new { | ||
| 64 | my ($class, $args) = @_; | ||
| 65 | |||
| 66 | die 'YAHC: ->new() expect args to be a hashref' if defined $args and ref($args) ne 'HASH'; | ||
| 67 | die 'YAHC: please do `my ($yahc, $yahc_storage) = YAHC::new()` and keep both these objects in the same scope' unless wantarray; | ||
| 68 | |||
| 69 | # wrapping target selection here allows all client share same list | ||
| 70 | # and more importantly to share index within the list | ||
| 71 | $args->{_target} = _wrap_target_selection($args->{host}) if $args->{host}; | ||
| 72 | |||
| 73 | # this's a radical way of avoiding circular references. | ||
| 74 | # let's see how it plays out in practise. | ||
| 75 | my %storage = ( | ||
| 76 | watchers => {}, | ||
| 77 | callbacks => {}, | ||
| 78 | connections => {}, | ||
| 79 | ); | ||
| 80 | |||
| 81 | my $self = bless { | ||
| 82 | loop => new EV::Loop, | ||
| 83 | pid => $$, # store pid to detect forks | ||
| 84 | storage => \%storage, | ||
| 85 | watchers => $storage{watchers}, | ||
| 86 | callbacks => $storage{callbacks}, | ||
| 87 | connections => $storage{connections}, | ||
| 88 | last_connection_id => $$ * 1000, | ||
| 89 | |||
| 90 | debug => delete $args->{debug}, | ||
| 91 | keep_timeline => delete $args->{keep_timeline}, | ||
| 92 | pool_args => $args, | ||
| 93 | }, $class; | ||
| 94 | |||
| 95 | weaken($self->{storage}); | ||
| 96 | weaken($self->{watchers}); | ||
| 97 | weaken($self->{callbacks}); | ||
| 98 | weaken($self->{connections}); | ||
| 99 | return $self, \%storage; | ||
| 100 | } | ||
| 101 | |||
| 102 | sub request { | ||
| 103 | my ($self, @args) = @_; | ||
| 104 | my ($conn_id, $request); | ||
| 105 | die 'YAHC: new_request() expects arguments' unless @args; | ||
| 106 | die 'YAHC: storage object is destroyed' unless $self->{storage}; | ||
| 107 | |||
| 108 | if (@args == 1) { | ||
| 109 | $conn_id = 'connection_' . $self->{last_connection_id}++; | ||
| 110 | $request = $args[0]; | ||
| 111 | } else { | ||
| 112 | ($conn_id, $request) = @args; | ||
| 113 | } | ||
| 114 | |||
| 115 | die "YAHC: Connection with name '$conn_id' already exists" | ||
| 116 | if exists $self->{connections}{$conn_id}; | ||
| 117 | |||
| 118 | my $conn = { | ||
| 119 | id => $conn_id, | ||
| 120 | request => $request, | ||
| 121 | response => { status_code => 0 }, | ||
| 122 | attempt => 0, | ||
| 123 | retries => $request->{retries} || 0, | ||
| 124 | state => YAHC::State::INITIALIZED(), | ||
| 125 | debug => delete $request->{debug} || $self->{debug}, | ||
| 126 | keep_timeline => delete $request->{keep_timeline} || $self->{keep_timeline}, | ||
| 127 | selected_target => [], | ||
| 128 | }; | ||
| 129 | |||
| 130 | my $pool_args = $self->{pool_args}; | ||
| 131 | $request->{_target} = _wrap_target_selection($request->{host}) if $request->{host}; | ||
| 132 | do { $request->{$_} ||= $pool_args->{$_} if $pool_args->{$_} } foreach (qw/host port scheme/); | ||
| 133 | die 'YAHC: host must be defined' unless $request->{host}; | ||
| 134 | |||
| 135 | $request->{scheme} //= 'http'; | ||
| 136 | die 'YAHC: only support scheme http' unless $request->{scheme} eq 'http'; | ||
| 137 | |||
| 138 | my %callbacks; | ||
| 139 | foreach (@{ CALLBACKS() }) { | ||
| 140 | next unless $request->{$_}; | ||
| 141 | $callbacks{$_} = delete $request->{$_}; | ||
| 142 | $conn->{"has_$_"} = 1; | ||
| 143 | } | ||
| 144 | |||
| 145 | $self->{watchers}{$conn_id} = {}; | ||
| 146 | $self->{callbacks}{$conn_id} = \%callbacks; | ||
| 147 | $self->{connections}{$conn_id} = $conn; | ||
| 148 | |||
| 149 | $self->_set_request_timer($conn_id) if $conn->{request}{request_timeout}; | ||
| 150 | $self->_set_init_state($conn_id); | ||
| 151 | return $conn; | ||
| 152 | } | ||
| 153 | |||
| 154 | sub run { $_[0]->_run(0, $_[1]) } | ||
| 155 | sub run_once { $_[0]->_run(EV::RUN_ONCE) } | ||
| 156 | sub run_tick { $_[0]->_run(EV::RUN_NOWAIT) } | ||
| 157 | |||
| 158 | ################################################################################ | ||
| 159 | # Routines to manipulate connections (also user facing) | ||
| 160 | ################################################################################ | ||
| 161 | |||
| 162 | sub yahc_reinit_conn { | ||
| 163 | my ($conn, $args) = @_; | ||
| 164 | $conn->{attempt} = 0; | ||
| 165 | $conn->{state} = YAHC::State::INITIALIZED(); | ||
| 166 | return unless defined $args && ref($args) eq 'HASH'; | ||
| 167 | |||
| 168 | my $request = $conn->{request}; | ||
| 169 | do { $request->{$_} = $args->{$_} if $args->{$_} } foreach (keys %$args); | ||
| 170 | $request->{_target} = _wrap_target_selection($args->{host}) if $args->{host}; | ||
| 171 | } | ||
| 172 | |||
| 173 | sub yahc_conn_last_error { | ||
| 174 | my $conn = shift; | ||
| 175 | return unless $conn->{errors} && @{ $conn->{errors} }; | ||
| 176 | return wantarray ? @{ $conn->{errors}[-1] } : $conn->{errors}[-1]; | ||
| 177 | } | ||
| 178 | |||
| 179 | sub yahc_conn_id { $_[0]->{id} } | ||
| 180 | sub yahc_conn_state { $_[0]->{state} } | ||
| 181 | sub yahc_conn_errors { $_[0]->{errors} } | ||
| 182 | sub yahc_conn_timeline { $_[0]->{timeline} } | ||
| 183 | sub yahc_conn_request { $_[0]->{request} } | ||
| 184 | sub yahc_conn_response { $_[0]->{response} } | ||
| 185 | |||
| 186 | sub yahc_conn_url { | ||
| 187 | my $target = $_[0]->{selected_target}; | ||
| 188 | my $request = $_[0]->{request}; | ||
| 189 | return unless $target; | ||
| 190 | |||
| 191 | my ($host, $ip, $port) = @{ $target }; | ||
| 192 | return $request->{scheme} . "://" | ||
| 193 | . ($host || $ip) | ||
| 194 | . ($port ne "80" ? ":$port" : '') | ||
| 195 | . ($request->{path} || "/") | ||
| 196 | . (defined $request->{query_string} ? ("?" . $request->{query_string}) : ""); | ||
| 197 | } | ||
| 198 | |||
| 199 | ################################################################################ | ||
| 200 | # Internals | ||
| 201 | ################################################################################ | ||
| 202 | |||
| 203 | sub _run { | ||
| 204 | my ($self, $how, $until_state, $until_state_connection_ids) = @_; | ||
| 205 | die 'YAHC: storage object is destroyed' unless $self->{storage}; | ||
| 206 | |||
| 207 | if ($self->{pid} != $$) { | ||
| 208 | _log_message('Reinitializing event loop after forking') if $self->{debug}; | ||
| 209 | $self->{pid} = $$; | ||
| 210 | $self->{loop}->loop_fork; | ||
| 211 | } | ||
| 212 | |||
| 213 | if (defined $until_state) { | ||
| 214 | my $until_state_str = _strstate($until_state); | ||
| 215 | die "YAHC: unknown until_state $until_state" if $until_state_str =~ m/unknown/; | ||
| 216 | |||
| 217 | my @connections; | ||
| 218 | if (defined $until_state_connection_ids) { | ||
| 219 | @connections = @{ $until_state_connection_ids }; | ||
| 220 | @connections = grep { exists $self->{connections}{$_} ? $self->{connections}{$_} : () } @connections; | ||
| 221 | } else { | ||
| 222 | @connections = values %{ $self->{connections} }; # all connections | ||
| 223 | } | ||
| 224 | |||
| 225 | $self->{stop_condition} = { | ||
| 226 | expected_state => $until_state, | ||
| 227 | connections => { map { $_->id => 1 } grep { $_->state < $until_state } @connections }, | ||
| 228 | }; | ||
| 229 | } else { | ||
| 230 | delete $self->{stop_condition}; | ||
| 231 | } | ||
| 232 | |||
| 233 | my $loop = $self->{loop}; | ||
| 234 | $loop->now_update; | ||
| 235 | return $loop->run($how || 0) unless $self->{debug}; # shortcut | ||
| 236 | |||
| 237 | my $iterations = $loop->iteration; | ||
| 238 | _log_message('pid %d entering event loop%s', $$, ($until_state ? " with until state " . _strstate($until_state) : '')); | ||
| 239 | $loop->run($how || 0); | ||
| 240 | _log_message('pid %d exited from event loop after %d iterations', $$, $loop->iteration - $iterations); | ||
| 241 | } | ||
| 242 | |||
| 243 | sub _break { | ||
| 244 | my ($self, $reason) = @_; | ||
| 245 | _log_message('pid %d breaking event loop because %s', $$, ($reason || 'no reason')) if $self->{debug}; | ||
| 246 | $self->{loop}->break(EV::BREAK_ONE) | ||
| 247 | } | ||
| 248 | |||
| 249 | sub _check_stop_condition { | ||
| 250 | my ($self, $conn) = @_; | ||
| 251 | my $stop_condition = $self->{stop_condition}; | ||
| 252 | return if !$stop_condition || $conn->{state} < $stop_condition->{expected_state}; | ||
| 253 | |||
| 254 | delete $stop_condition->{connections}{$conn->id}; | ||
| 255 | my $awaiting_connections = scalar keys %{ $stop_condition->{connections} }; | ||
| 256 | my $expected_state = $stop_condition->{expected_state}; | ||
| 257 | |||
| 258 | if ($awaiting_connections == 0) { | ||
| 259 | $self->_break(sprintf("until state '%s' is reached", _strstate($expected_state))); | ||
| 260 | } else { | ||
| 261 | _log_message("Still have %d connections awaiting state '%s'", | ||
| 262 | $awaiting_connections, _strstate($expected_state)) if $self->{debug}; | ||
| 263 | } | ||
| 264 | } | ||
| 265 | |||
| 266 | ################################################################################ | ||
| 267 | # IO routines | ||
| 268 | ################################################################################ | ||
| 269 | |||
| 270 | sub _set_init_state { | ||
| 271 | my ($self, $conn_id) = @_; | ||
| 272 | |||
| 273 | my $conn = $self->{connections}{$conn_id}; | ||
| 274 | my $watchers = $self->{watchers}{$conn_id}; | ||
| 275 | die "YAHC: unknown connection id $conn_id" unless $conn && $watchers; | ||
| 276 | |||
| 277 | $conn->{response} = { status_code => 0 }; | ||
| 278 | $conn->{state} = YAHC::State::INITIALIZED(); | ||
| 279 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 280 | $self->_call_state_callback($conn, 'init_callback') if $conn->{has_init_callback}; | ||
| 281 | |||
| 282 | my $continue = 1; | ||
| 283 | while ($continue) { | ||
| 284 | if (my $w = delete $watchers->{io}) { | ||
| 285 | $w->stop; | ||
| 286 | shutdown($w->fh, 2); | ||
| 287 | } | ||
| 288 | |||
| 289 | my $attempt = $conn->{attempt}++; | ||
| 290 | if ($attempt > $conn->{retries}) { | ||
| 291 | $self->_set_user_action_state($conn_id, YAHC::Error::CONNECT_ERROR(), "retries limit reached"); | ||
| 292 | return; | ||
| 293 | } | ||
| 294 | |||
| 295 | eval { | ||
| 296 | my ($host, $ip, $port) = _get_next_target($conn); | ||
| 297 | _register_in_timeline($conn, "Target $host:$port ($ip:$port) chosen for attempt #$attempt") if $conn->{keep_timeline}; | ||
| 298 | |||
| 299 | my $sock = _build_socket_and_connect($ip, $port, $conn->{request}); | ||
| 300 | $self->_set_wait_synack_state($conn_id, $sock, $ip, $host, $port); | ||
| 301 | $self->_set_connection_timer($conn_id) if $conn->{request}{connect_timeout}; | ||
| 302 | $continue = 0; | ||
| 303 | 1; | ||
| 304 | } or do { | ||
| 305 | my $error = $@ || 'zombie error'; | ||
| 306 | _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Connection attempt #$attempt for $conn_id has failed: $error"); | ||
| 307 | #$self->_set_set_init_state_timer($conn_id); # trigger background timer which will do reconnection attempt # TODO | ||
| 308 | #$continue = 0; | ||
| 309 | }; | ||
| 310 | } | ||
| 311 | } | ||
| 312 | |||
| 313 | sub _set_wait_synack_state { | ||
| 314 | my ($self, $conn_id, $sock, $ip, $host, $port) = @_; | ||
| 315 | |||
| 316 | my $conn = $self->{connections}{$conn_id}; | ||
| 317 | my $watchers = $self->{watchers}{$conn_id}; | ||
| 318 | die "YAHC: unknown connection id $conn_id" unless $conn && $watchers; | ||
| 319 | _assert_state($conn, YAHC::State::INITIALIZED()) if $conn->{debug}; | ||
| 320 | |||
| 321 | $conn->{state} = YAHC::State::WAIT_SYNACK(); | ||
| 322 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 323 | $self->_call_state_callback($conn, 'wait_synack_callback') if $conn->{has_wait_synack_callback}; | ||
| 324 | |||
| 325 | my $wait_synack_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 326 | my $sockopt = getsockopt($sock, SOL_SOCKET, SO_ERROR); | ||
| 327 | if (!$sockopt) { | ||
| 328 | _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Failed to do getsockopt(): $!"); | ||
| 329 | $self->_set_init_state($conn_id); | ||
| 330 | return; | ||
| 331 | } | ||
| 332 | |||
| 333 | if (my $err = unpack("L", $sockopt)) { | ||
| 334 | my $strerror = POSIX::strerror($err) || '<unknown POSIX error>'; | ||
| 335 | _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Failed to connect to $host:$port ($ip:$port): $strerror"); | ||
| 336 | $self->_set_init_state($conn_id); | ||
| 337 | return; | ||
| 338 | } | ||
| 339 | |||
| 340 | $conn->{state} = YAHC::State::CONNECTED(); | ||
| 341 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 342 | $self->_call_state_callback($conn, 'connected_callback') if $conn->{has_connected_callback}; | ||
| 343 | |||
| 344 | $self->_set_write_state($conn_id); | ||
| 345 | }); | ||
| 346 | |||
| 347 | $watchers->{io} = $self->{loop}->io($sock, EV::WRITE, $wait_synack_cb); | ||
| 348 | $self->_check_stop_condition($conn) if $self->{stop_condition}; | ||
| 349 | } | ||
| 350 | |||
| 351 | sub _set_write_state { | ||
| 352 | my ($self, $conn_id) = @_; | ||
| 353 | |||
| 354 | my $conn = $self->{connections}{$conn_id}; | ||
| 355 | my $watcher = $self->{watchers}{$conn_id}{io}; | ||
| 356 | die "YAHC: unknown connection id $conn_id" unless $conn && $watcher; | ||
| 357 | _assert_connected($conn) if $conn->{debug}; | ||
| 358 | |||
| 359 | $conn->{state} = YAHC::State::WRITING(); | ||
| 360 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 361 | $self->_call_state_callback($conn, 'writing_callback') if $conn->{has_writing_callback}; | ||
| 362 | |||
| 363 | my $fd = fileno($watcher->fh); | ||
| 364 | my $buf = _build_http_message($conn); | ||
| 365 | my $length = length($buf); | ||
| 366 | |||
| 367 | _register_in_timeline($conn, "sending request of $length bytes") if $conn->{keep_timeline}; | ||
| 368 | |||
| 369 | my $write_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 370 | my $wlen = POSIX::write($fd, $buf, $length); | ||
| 371 | |||
| 372 | if (!$wlen) { | ||
| 373 | return if $! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR; | ||
| 374 | |||
| 375 | my $error = !defined $wlen | ||
| 376 | ? "Failed to send TCP data: $!" | ||
| 377 | : "Bizzare!!! syswrite returned 0"; # wlen == 0 | ||
| 378 | |||
| 379 | _register_error($conn, YAHC::Error::WRITE_ERROR(), $error); | ||
| 380 | $self->_set_init_state($conn_id); | ||
| 381 | } else { | ||
| 382 | substr($buf, 0, $wlen, ''); | ||
| 383 | $length -= $wlen; | ||
| 384 | $self->_set_read_state($conn_id) if $length == 0; | ||
| 385 | } | ||
| 386 | }); | ||
| 387 | |||
| 388 | $watcher->cb($write_cb); | ||
| 389 | $watcher->events(EV::WRITE); | ||
| 390 | $self->_check_stop_condition($conn) if $self->{stop_condition}; | ||
| 391 | } | ||
| 392 | |||
| 393 | sub _set_read_state { | ||
| 394 | my ($self, $conn_id) = @_; | ||
| 395 | |||
| 396 | my $conn = $self->{connections}{$conn_id}; | ||
| 397 | my $watcher = $self->{watchers}{$conn_id}{io}; | ||
| 398 | die "YAHC: unknown connection id $conn_id" unless $conn && $watcher; | ||
| 399 | _assert_connected($conn) if $conn->{debug}; | ||
| 400 | |||
| 401 | $conn->{state} = YAHC::State::READING(); | ||
| 402 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 403 | $self->_call_state_callback($conn, 'reading_callback') if $conn->{has_reading_callback}; | ||
| 404 | |||
| 405 | my $buf = ''; | ||
| 406 | my $neck_pos = 0; | ||
| 407 | my $decapitated = 0; | ||
| 408 | my $content_length = 0; | ||
| 409 | my $fd = fileno($watcher->fh); | ||
| 410 | |||
| 411 | my $read_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 412 | my $rlen = POSIX::read($fd, my $b = '', TCP_READ_CHUNK); | ||
| 413 | |||
| 414 | if (!$rlen) { | ||
| 415 | return if $! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR; | ||
| 416 | if (not defined $rlen) { | ||
| 417 | _register_error($conn, YAHC::Error::READ_ERROR(), "Failed to receive TCP data: $!"); | ||
| 418 | } elsif ($content_length > 0) { # i.e. rlen == 0 and $content_length > 0 | ||
| 419 | register_error($conn, YAHC::Error::READ_ERROR(), "Premature EOF, expect %d bytes more", $content_length - length($buf)); | ||
| 420 | } else { # i.e. rlen == 0 | ||
| 421 | register_error($conn, YAHC::Error::READ_ERROR(), "Premature EOF"); | ||
| 422 | } | ||
| 423 | |||
| 424 | $self->_set_init_state($conn_id); | ||
| 425 | } else { | ||
| 426 | $buf .= $b; | ||
| 427 | if (!$decapitated && ($neck_pos = index($buf, "${CRLF}${CRLF}")) > 0) { | ||
| 428 | my $headers = _parse_http_headers($conn, substr($buf, 0, $neck_pos, '')); | ||
| 429 | if (not defined $headers) { | ||
| 430 | $self->_set_user_action_state($conn_id, YAHC::Error::RESPONSE_ERROR(), "unsuported HTTP reponse"); | ||
| 431 | return; | ||
| 432 | } | ||
| 433 | |||
| 434 | $decapitated = 1; | ||
| 435 | $content_length = $headers->{'Content-Length'}; | ||
| 436 | substr($buf, 0, 4, ''); # 4 = length("$CRLF$CRLF") | ||
| 437 | _register_in_timeline($conn, "headers parsed: content-length='%d' content-type='%s'", | ||
| 438 | $content_length, $headers->{'Content-Type'} || '<no-content-type>') if $conn->{keep_timeline}; | ||
| 439 | } | ||
| 440 | |||
| 441 | if ($decapitated && length($buf) >= $content_length) { | ||
| 442 | $buf = substr($buf, 0, $content_length) if length($buf) > $content_length; | ||
| 443 | $conn->{response}{body} = $buf; | ||
| 444 | $self->_set_user_action_state($conn_id); | ||
| 445 | } | ||
| 446 | } | ||
| 447 | }); | ||
| 448 | |||
| 449 | $watcher->cb($read_cb); | ||
| 450 | $watcher->events(EV::READ); | ||
| 451 | $self->_check_stop_condition($conn) if $self->{stop_condition}; | ||
| 452 | } | ||
| 453 | |||
| 454 | sub _set_user_action_state { | ||
| 455 | my ($self, $conn_id, $error, $strerror) = @_; | ||
| 456 | $error ||= YAHC::Error::NO_ERROR(); | ||
| 457 | $strerror ||= '<no strerror>'; | ||
| 458 | |||
| 459 | # this state may be used in critical places, | ||
| 460 | # so it should *NEVER* throw exception | ||
| 461 | my $conn = $self->{connections}{$conn_id} | ||
| 462 | or warn "YAHC: try to _set_user_action_state() for unknown connection $conn_id", | ||
| 463 | return; | ||
| 464 | |||
| 465 | $conn->{state} = YAHC::State::USER_ACTION(); | ||
| 466 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 467 | _register_error($conn, $error, $strerror) if $error; | ||
| 468 | |||
| 469 | return $self->_set_completed_state($conn_id) unless $conn->{has_callback}; | ||
| 470 | my $cb = $self->{callbacks}{$conn_id}{callback}; | ||
| 471 | |||
| 472 | eval { | ||
| 473 | _register_in_timeline($conn, "call callback%s", $error ? " error=$error, strerror='$strerror'" : '') if $conn->{keep_timeline}; | ||
| 474 | $cb->($conn, $error, $strerror); | ||
| 475 | 1; | ||
| 476 | } or do { | ||
| 477 | my $error = $@ || 'zombie error'; | ||
| 478 | _register_error($conn, YAHC::Error::CALLBACK_ERROR(), "Exception in callback: $error"); | ||
| 479 | warn "YAHC: exception in callback: $error"; | ||
| 480 | $self->_set_completed_state($conn_id); | ||
| 481 | return; | ||
| 482 | }; | ||
| 483 | |||
| 484 | my $state = $conn->{state}; | ||
| 485 | _register_in_timeline($conn, "after invoking callback state is %s", _strstate($state)) if $conn->{keep_timeline}; | ||
| 486 | |||
| 487 | if ($state == YAHC::State::INITIALIZED()) { | ||
| 488 | $self->_set_init_state($conn_id); # TODO eval | ||
| 489 | } elsif ($state == YAHC::State::USER_ACTION() || $state == YAHC::State::COMPLETED()) { | ||
| 490 | $self->_set_completed_state($conn_id); | ||
| 491 | } else { | ||
| 492 | _register_error($conn, YAHC::Error::CALLBACK_ERROR(), "callback set unsupported state"); | ||
| 493 | $self->_set_completed_state($conn_id); | ||
| 494 | } | ||
| 495 | } | ||
| 496 | |||
| 497 | sub _set_completed_state { | ||
| 498 | my ($self, $conn_id) = @_; | ||
| 499 | |||
| 500 | # this's a terminal state, | ||
| 501 | # so setting this state should *NEVER* fail | ||
| 502 | delete $self->{callbacks}{$conn_id}; | ||
| 503 | my $watchers = delete $self->{watchers}{$conn_id}; | ||
| 504 | my $conn = $self->{connections}{$conn_id} | ||
| 505 | or warn "YAHC: try to _set_completed_state() for unknown connection $conn_id", | ||
| 506 | return; | ||
| 507 | |||
| 508 | $conn->{state} = YAHC::State::COMPLETED(); | ||
| 509 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 510 | |||
| 511 | if ($conn->{has_completed_callback}) { | ||
| 512 | eval { | ||
| 513 | $self->{callbacks}{$conn_id}{completed_callback}->($conn); | ||
| 514 | 1; | ||
| 515 | } or do { | ||
| 516 | my $error = $@ || 'zombie error'; | ||
| 517 | _register_error($conn, YAHC::Error::CALLBACK_ERROR(), "Exception in callback: $error"); | ||
| 518 | warn "YAHC: exception in callback: $error"; | ||
| 519 | } | ||
| 520 | } | ||
| 521 | |||
| 522 | if (my $w = delete $watchers->{io}) { | ||
| 523 | $w->stop; | ||
| 524 | shutdown($w->fh, 2) | ||
| 525 | } | ||
| 526 | |||
| 527 | $_->stop foreach (values %{ $watchers || {} }); | ||
| 528 | |||
| 529 | eval { $self->_check_stop_condition($conn) } if $self->{stop_condition}; | ||
| 530 | } | ||
| 531 | |||
| 532 | sub _build_socket_and_connect { | ||
| 533 | my ($ip, $port, $timeouts) = @_; | ||
| 534 | |||
| 535 | my $sock; | ||
| 536 | socket($sock, PF_INET, SOCK_STREAM, 0) or die "YAHC: Failed to construct TCP socket: $!"; | ||
| 537 | |||
| 538 | my $flags = fcntl($sock, F_GETFL, 0) or die "YAHC: Failed to get fcntl F_GETFL flag: $!"; | ||
| 539 | fcntl($sock, F_SETFL, $flags | O_NONBLOCK) or die "YAHC: Failed to set fcntl O_NONBLOCK flag: $!"; | ||
| 540 | |||
| 541 | if (my $read_timeout = $timeouts->{read_timeout}) { | ||
| 542 | my $read_struct = pack('l!l!', $read_timeout, 0); | ||
| 543 | setsockopt($sock, SOL_SOCKET, SO_RCVTIMEO, $read_struct) | ||
| 544 | or die "YAHC: Failed to set setsockopt(SO_RCVTIMEO): $!"; | ||
| 545 | } | ||
| 546 | |||
| 547 | if (my $write_timeout = $timeouts->{write_timeout}) { | ||
| 548 | my $write_struct = pack('l!l!', $write_timeout, 0); | ||
| 549 | setsockopt($sock, SOL_SOCKET, SO_SNDTIMEO, $write_struct ) | ||
| 550 | or die "YAHC: Failed to set setsockopt(SO_SNDTIMEO): $!"; | ||
| 551 | } | ||
| 552 | |||
| 553 | my $ip_addr = inet_aton($ip); | ||
| 554 | my $addr = pack_sockaddr_in($port, $ip_addr); | ||
| 555 | if (!connect($sock, $addr) && $! != EINPROGRESS) { | ||
| 556 | die "YAHC: Failed to connect to $ip: $!"; | ||
| 557 | } | ||
| 558 | |||
| 559 | return $sock; | ||
| 560 | } | ||
| 561 | |||
| 562 | sub _get_next_target { | ||
| 563 | my $conn = shift; | ||
| 564 | my ($host, $ip, $port) = $conn->{request}{_target}->(); | ||
| 565 | |||
| 566 | # TODO STATE_RESOLVE_DNS | ||
| 567 | ($host, $port) = ($1, $2) if $host =~ m/^(.+):([0-9]+)$/o; | ||
| 568 | $ip = $host if $host =~ m/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/o; | ||
| 569 | $ip = inet_ntoa(gethostbyname($host) or die "Failed to resolve $host: $!") unless $ip; | ||
| 570 | $port ||= $conn->{request}{port} || HTTP_PORT; | ||
| 571 | |||
| 572 | return @{ $conn->{selected_target} = [ $host, $ip, $port ] }; | ||
| 573 | } | ||
| 574 | |||
| 575 | ################################################################################ | ||
| 576 | # Timers | ||
| 577 | ################################################################################ | ||
| 578 | |||
| 579 | sub _set_request_timer { | ||
| 580 | my ($self, $conn_id) = @_; | ||
| 581 | |||
| 582 | my $conn = $self->{connections}{$conn_id}; | ||
| 583 | my $watchers = $self->{watchers}{$conn_id}; | ||
| 584 | die "YAHC: unknown connection id $conn_id" unless $conn && $watchers; | ||
| 585 | |||
| 586 | if (my $timer = delete $watchers->{connection_timer}) { | ||
| 587 | $timer->stop; | ||
| 588 | } | ||
| 589 | |||
| 590 | my $timeout = $conn->{request}{request_timeout}; | ||
| 591 | return unless defined $timeout; | ||
| 592 | |||
| 593 | my $request_timer_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 594 | if ($conn->{state} < YAHC::State::USER_ACTION()) { | ||
| 595 | my $error = sprintf("Request timeout of %.3fs has reached", $timeout); | ||
| 596 | $self->_set_user_action_state($conn_id, YAHC::Error::REQUEST_TIMEOUT(), $error); | ||
| 597 | } else { | ||
| 598 | _register_in_timeline($conn, "delete request timer") if $conn->{keep_timeline}; | ||
| 599 | } | ||
| 600 | }); | ||
| 601 | |||
| 602 | _register_in_timeline($conn, "setting request timeout to %.3fs", $timeout) if $conn->{keep_timeline}; | ||
| 603 | $watchers->{request_timer} = $self->{loop}->timer($timeout, 0, $request_timer_cb); | ||
| 604 | $watchers->{request_timer}->priority(2); # set max priority | ||
| 605 | } | ||
| 606 | |||
| 607 | sub _set_connection_timer { | ||
| 608 | my ($self, $conn_id) = @_; | ||
| 609 | |||
| 610 | my $conn = $self->{connections}{$conn_id}; | ||
| 611 | my $watchers = $self->{watchers}{$conn_id}; | ||
| 612 | die "YAHC: unknown connection id $conn_id" unless $conn && $watchers; | ||
| 613 | |||
| 614 | if (my $timer = delete $watchers->{connection_timer}) { | ||
| 615 | $timer->stop; | ||
| 616 | } | ||
| 617 | |||
| 618 | my $timeout = $conn->{request}{connect_timeout}; | ||
| 619 | return unless $timeout; | ||
| 620 | |||
| 621 | my $connection_timer_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 622 | if ($conn->{state} < YAHC::State::CONNECTED()) { | ||
| 623 | _register_in_timeline($conn, "connection timeout of %.3fs has reached", $timeout) if $conn->{keep_timeline}; | ||
| 624 | $self->_set_init_state($conn_id); | ||
| 625 | } else { | ||
| 626 | _register_in_timeline($conn, "delete connection timer") if $conn->{keep_timeline}; | ||
| 627 | } | ||
| 628 | }); | ||
| 629 | |||
| 630 | _register_in_timeline($conn, "setting connection timeout to %.3fs", $timeout) if $conn->{keep_timeline}; | ||
| 631 | $watchers->{connection_timer} = $self->{loop}->timer($timeout, 0, $connection_timer_cb); | ||
| 632 | $watchers->{connection_timer}->priority(-2); # set lowest priority | ||
| 633 | } | ||
| 634 | |||
| 635 | ################################################################################ | ||
| 636 | # HTTP functions | ||
| 637 | ################################################################################ | ||
| 638 | |||
| 639 | # copy-paste from Hijk | ||
| 640 | sub _build_http_message { | ||
| 641 | my $conn = shift; | ||
| 642 | my $request = $conn->{request}; | ||
| 643 | my $path_and_qs = ($request->{path} || "/") . (defined $request->{query_string} ? ("?" . $request->{query_string}) : ""); | ||
| 644 | |||
| 645 | return join( | ||
| 646 | $CRLF, | ||
| 647 | ($request->{method} || "GET") . " $path_and_qs " . ($request->{protocol} || "HTTP/1.1"), | ||
| 648 | "Host: " . $conn->{selected_target}[0], | ||
| 649 | $request->{body} ? ("Content-Length: " . length($request->{body})) : (), | ||
| 650 | $request->{head} ? ( | ||
| 651 | map { | ||
| 652 | $request->{head}[2*$_] . ": " . $request->{head}[2*$_+1] | ||
| 653 | } 0..$#{$request->{head}}/2 | ||
| 654 | ) : (), | ||
| 655 | "", | ||
| 656 | $request->{body} ? $request->{body} : () | ||
| 657 | ) . $CRLF; | ||
| 658 | } | ||
| 659 | |||
| 660 | sub _parse_http_headers { | ||
| 661 | my $conn = shift; | ||
| 662 | my $proto = substr($_[0], 0, 8); | ||
| 663 | my $status_code = substr($_[0], 9, 3); | ||
| 664 | substr($_[0], 0, index($_[0], $CRLF) + 2, ''); # 2 = length($CRLF) | ||
| 665 | |||
| 666 | my %headers; | ||
| 667 | for (split /${CRLF}/o, $_[0]) { | ||
| 668 | my ($key, $value) = split(/: /, $_, 2); | ||
| 669 | $headers{$key} = $value; | ||
| 670 | } | ||
| 671 | |||
| 672 | $conn->{response} = { | ||
| 673 | proto => $proto, | ||
| 674 | status_code => $status_code, | ||
| 675 | headers => \%headers, | ||
| 676 | }; | ||
| 677 | |||
| 678 | return \%headers; | ||
| 679 | } | ||
| 680 | |||
| 681 | ################################################################################ | ||
| 682 | # Helpers | ||
| 683 | ################################################################################ | ||
| 684 | |||
| 685 | sub _wrap_target_selection { | ||
| 686 | my $host = shift; | ||
| 687 | my $ref = ref($host); | ||
| 688 | |||
| 689 | return sub { $host } if $ref eq ''; | ||
| 690 | return $host if $ref eq 'CODE'; | ||
| 691 | |||
| 692 | my $idx = 0; | ||
| 693 | return sub { $host->[$idx++ % @$host]; } if $ref eq 'ARRAY'; | ||
| 694 | die "YAHC: unsupported host format"; | ||
| 695 | } | ||
| 696 | |||
| 697 | sub _call_state_callback { | ||
| 698 | my ($self, $conn, $cb_name) = @_; | ||
| 699 | my $cb = $self->{callbacks}{$conn->{id}}{$cb_name}; | ||
| 700 | return unless $cb; | ||
| 701 | |||
| 702 | eval { | ||
| 703 | $cb->($conn); | ||
| 704 | 1; | ||
| 705 | } or do { | ||
| 706 | my $error = $@ || 'zombie error'; | ||
| 707 | _register_error($conn, YAHC::Error::CALLBACK_ERROR(), "Exception in callback: $error"); | ||
| 708 | warn "YAHC: exception in callback: $error"; | ||
| 709 | $self->_set_completed_state($conn->{id}); | ||
| 710 | }; | ||
| 711 | } | ||
| 712 | |||
| 713 | sub _get_safe_wrapper { | ||
| 714 | my ($self, $conn, $sub) = @_; | ||
| 715 | return sub { eval { | ||
| 716 | $sub->(@_); | ||
| 717 | 1; | ||
| 718 | } or do { | ||
| 719 | my $error = $@ || 'zombie error'; | ||
| 720 | _register_error($conn, YAHC::Error::INTERNAL_ERROR(), "Exception callback: $error"); | ||
| 721 | warn "YAHC: exception in callback: $error"; | ||
| 722 | $self->_set_completed_state($conn->{id}); | ||
| 723 | }}; | ||
| 724 | } | ||
| 725 | |||
| 726 | sub _register_in_timeline { | ||
| 727 | my ($conn, $format, @arguments) = @_; | ||
| 728 | my $event = sprintf("$format", @arguments); | ||
| 729 | $event =~ s/\s+$//g; | ||
| 730 | _log_message("YAHC connection '%s': %s", $conn->{id}, $event) if $conn->{debug}; | ||
| 731 | push @{ $conn->{timeline} ||= [] }, [ $event, $conn->{state}, Time::HiRes::time ] if $conn->{keep_timeline}; | ||
| 732 | } | ||
| 733 | |||
| 734 | sub _register_error { | ||
| 735 | my ($conn, $error, $format, @arguments) = @_; | ||
| 736 | my $strerror = sprintf("$format", @arguments); | ||
| 737 | $strerror =~ s/\s+$//g; | ||
| 738 | _register_in_timeline($conn, "error=$error ($strerror)") if $conn->{debug}; | ||
| 739 | push @{ $conn->{errors} ||= [] }, [ $error, $strerror, Time::HiRes::time ]; | ||
| 740 | } | ||
| 741 | |||
| 742 | sub _assert_state { | ||
| 743 | my ($conn, $expected_state) = @_; | ||
| 744 | return $conn->{state} == $expected_state; | ||
| 745 | die sprintf("YAHC connection '%s' is in unexpected state %s, expected %s", | ||
| 746 | $conn->{id}, _strstate($conn->{state}), _strstate($expected_state)); | ||
| 747 | } | ||
| 748 | |||
| 749 | sub _assert_connected { | ||
| 750 | my $conn = shift; | ||
| 751 | return if $conn->{state} >= YAHC::State::CONNECTED() && $conn->{state} < YAHC::State::COMPLETED(); | ||
| 752 | die sprintf("YAHC connection '%s' expected to be in connected state, but it's in %s", | ||
| 753 | $conn->{id}, _strstate($conn->{state})); | ||
| 754 | } | ||
| 755 | |||
| 756 | sub _strstate { | ||
| 757 | my $state = shift; | ||
| 758 | return 'STATE_INIT' if $state eq YAHC::State::INITIALIZED(); | ||
| 759 | return 'STATE_RESOLVE_DNS' if $state eq YAHC::State::RESOLVE_DNS(); | ||
| 760 | return 'STATE_WAIT_SYNACK' if $state eq YAHC::State::WAIT_SYNACK(); | ||
| 761 | return 'STATE_CONNECTED' if $state eq YAHC::State::CONNECTED(); | ||
| 762 | return 'STATE_WRITING' if $state eq YAHC::State::WRITING(); | ||
| 763 | return 'STATE_READING' if $state eq YAHC::State::READING(); | ||
| 764 | return 'STATE_USER_ACTION' if $state eq YAHC::State::USER_ACTION(); | ||
| 765 | return 'STATE_COMPLETED' if $state eq YAHC::State::COMPLETED(); | ||
| 766 | return "<unknown state $state>"; | ||
| 767 | } | ||
| 768 | |||
| 769 | sub _log_message { | ||
| 770 | my $format = shift; | ||
| 771 | printf STDERR "[%s] [$$] $format\n", POSIX::strftime('%F %T', localtime), @_; | ||
| 772 | } | ||
| 773 | |||
| 774 | 1; | ||
| 775 | |||
| 776 | __END__ |