… | |
… | |
41 | use strict; |
41 | use strict; |
42 | no warnings; |
42 | no warnings; |
43 | |
43 | |
44 | use Errno (); |
44 | use Errno (); |
45 | |
45 | |
46 | use AnyEvent 4.8 (); |
46 | use AnyEvent 5.0 (); |
47 | use AnyEvent::Util (); |
47 | use AnyEvent::Util (); |
48 | use AnyEvent::Socket (); |
48 | use AnyEvent::Socket (); |
49 | use AnyEvent::Handle (); |
49 | use AnyEvent::Handle (); |
50 | |
50 | |
51 | use base Exporter::; |
51 | use base Exporter::; |
52 | |
52 | |
53 | our $VERSION = '1.4'; |
53 | our $VERSION = '1.46'; |
54 | |
54 | |
55 | our @EXPORT = qw(http_get http_post http_head http_request); |
55 | our @EXPORT = qw(http_get http_post http_head http_request); |
56 | |
56 | |
57 | our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)"; |
57 | our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)"; |
58 | our $MAX_RECURSE = 10; |
58 | our $MAX_RECURSE = 10; |
… | |
… | |
92 | must be an absolute http or https URL. |
92 | must be an absolute http or https URL. |
93 | |
93 | |
94 | When called in void context, nothing is returned. In other contexts, |
94 | When called in void context, nothing is returned. In other contexts, |
95 | C<http_request> returns a "cancellation guard" - you have to keep the |
95 | C<http_request> returns a "cancellation guard" - you have to keep the |
96 | object at least alive until the callback get called. If the object gets |
96 | object at least alive until the callback get called. If the object gets |
97 | destroyed before the callbakc is called, the request will be cancelled. |
97 | destroyed before the callback is called, the request will be cancelled. |
98 | |
98 | |
99 | The callback will be called with the response body data as first argument |
99 | The callback will be called with the response body data as first argument |
100 | (or C<undef> if an error occured), and a hash-ref with response headers as |
100 | (or C<undef> if an error occured), and a hash-ref with response headers as |
101 | second argument. |
101 | second argument. |
102 | |
102 | |
103 | All the headers in that hash are lowercased. In addition to the response |
103 | All the headers in that hash are lowercased. In addition to the response |
104 | headers, the "pseudo-headers" C<HTTPVersion>, C<Status> and C<Reason> |
104 | headers, the "pseudo-headers" (uppercase to avoid clashing with possible |
|
|
105 | response headers) C<HTTPVersion>, C<Status> and C<Reason> contain the |
105 | contain the three parts of the HTTP Status-Line of the same name. The |
106 | three parts of the HTTP Status-Line of the same name. |
|
|
107 | |
106 | pseudo-header C<URL> contains the original URL (which can differ from the |
108 | The pseudo-header C<URL> contains the actual URL (which can differ from |
107 | requested URL when following redirects). |
109 | the requested URL when following redirects - for example, you might get |
|
|
110 | an error that your URL scheme is not supported even though your URL is a |
|
|
111 | valid http URL because it redirected to an ftp URL, in which case you can |
|
|
112 | look at the URL pseudo header). |
|
|
113 | |
|
|
114 | The pseudo-header C<Redirect> only exists when the request was a result |
|
|
115 | of an internal redirect. In that case it is an array reference with |
|
|
116 | the C<($data, $headers)> from the redirect response. Note that this |
|
|
117 | response could in turn be the result of a redirect itself, and C<< |
|
|
118 | $headers->{Redirect}[1]{Redirect} >> will then contain the original |
|
|
119 | response, and so on. |
108 | |
120 | |
109 | If the server sends a header multiple times, then their contents will be |
121 | If the server sends a header multiple times, then their contents will be |
110 | joined together with a comma (C<,>), as per the HTTP spec. |
122 | joined together with a comma (C<,>), as per the HTTP spec. |
111 | |
123 | |
112 | If an internal error occurs, such as not being able to resolve a hostname, |
124 | If an internal error occurs, such as not being able to resolve a hostname, |
… | |
… | |
138 | |
150 | |
139 | =item headers => hashref |
151 | =item headers => hashref |
140 | |
152 | |
141 | The request headers to use. Currently, C<http_request> may provide its |
153 | The request headers to use. Currently, C<http_request> may provide its |
142 | own C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers |
154 | own C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers |
143 | and will provide defaults for C<User-Agent:> and C<Referer:>. |
155 | and will provide defaults for C<User-Agent:> and C<Referer:> (this can be |
|
|
156 | suppressed by using C<undef> for these headers in which case they won't be |
|
|
157 | sent at all). |
144 | |
158 | |
145 | =item timeout => $seconds |
159 | =item timeout => $seconds |
146 | |
160 | |
147 | The time-out to use for various stages - each connect attempt will reset |
161 | The time-out to use for various stages - each connect attempt will reset |
148 | the timeout, as will read or write activity. Default timeout is 5 minutes. |
162 | the timeout, as will read or write activity, i.e. this is not an overall |
|
|
163 | timeout. |
|
|
164 | |
|
|
165 | Default timeout is 5 minutes. |
149 | |
166 | |
150 | =item proxy => [$host, $port[, $scheme]] or undef |
167 | =item proxy => [$host, $port[, $scheme]] or undef |
151 | |
168 | |
152 | Use the given http proxy for all requests. If not specified, then the |
169 | Use the given http proxy for all requests. If not specified, then the |
153 | default proxy (as specified by C<$ENV{http_proxy}>) is used. |
170 | default proxy (as specified by C<$ENV{http_proxy}>) is used. |
154 | |
171 | |
155 | C<$scheme> must be either missing or C<http> for HTTP, or C<https> for |
172 | C<$scheme> must be either missing, C<http> for HTTP or C<https> for |
156 | HTTPS. |
173 | HTTPS. |
157 | |
174 | |
158 | =item body => $string |
175 | =item body => $string |
159 | |
176 | |
160 | The request body, usually empty. Will be-sent as-is (future versions of |
177 | The request body, usually empty. Will be-sent as-is (future versions of |
… | |
… | |
186 | verification) TLS context. |
203 | verification) TLS context. |
187 | |
204 | |
188 | The default for this option is C<low>, which could be interpreted as "give |
205 | The default for this option is C<low>, which could be interpreted as "give |
189 | me the page, no matter what". |
206 | me the page, no matter what". |
190 | |
207 | |
|
|
208 | =item on_prepare => $callback->($fh) |
|
|
209 | |
|
|
210 | In rare cases you need to "tune" the socket before it is used to |
|
|
211 | connect (for exmaple, to bind it on a given IP address). This parameter |
|
|
212 | overrides the prepare callback passed to C<AnyEvent::Socket::tcp_connect> |
|
|
213 | and behaves exactly the same way (e.g. it has to provide a |
|
|
214 | timeout). See the description for the C<$prepare_cb> argument of |
|
|
215 | C<AnyEvent::Socket::tcp_connect> for details. |
|
|
216 | |
191 | =item on_header => $callback->($headers) |
217 | =item on_header => $callback->($headers) |
192 | |
218 | |
193 | When specified, this callback will be called with the header hash as soon |
219 | When specified, this callback will be called with the header hash as soon |
194 | as headers have been successfully received from the remote server (not on |
220 | as headers have been successfully received from the remote server (not on |
195 | locally-generated errors). |
221 | locally-generated errors). |
… | |
… | |
221 | This callback is useful when the data is too large to be held in memory |
247 | This callback is useful when the data is too large to be held in memory |
222 | (so the callback writes it to a file) or when only some information should |
248 | (so the callback writes it to a file) or when only some information should |
223 | be extracted, or when the body should be processed incrementally. |
249 | be extracted, or when the body should be processed incrementally. |
224 | |
250 | |
225 | It is usually preferred over doing your own body handling via |
251 | It is usually preferred over doing your own body handling via |
226 | C<want_body_handle>. |
252 | C<want_body_handle>, but in case of streaming APIs, where HTTP is |
|
|
253 | only used to create a connection, C<want_body_handle> is the better |
|
|
254 | alternative, as it allows you to install your own event handler, reducing |
|
|
255 | resource usage. |
227 | |
256 | |
228 | =item want_body_handle => $enable |
257 | =item want_body_handle => $enable |
229 | |
258 | |
230 | When enabled (default is disabled), the behaviour of AnyEvent::HTTP |
259 | When enabled (default is disabled), the behaviour of AnyEvent::HTTP |
231 | changes considerably: after parsing the headers, and instead of |
260 | changes considerably: after parsing the headers, and instead of |
… | |
… | |
243 | This is useful with some push-type services, where, after the initial |
272 | This is useful with some push-type services, where, after the initial |
244 | headers, an interactive protocol is used (typical example would be the |
273 | headers, an interactive protocol is used (typical example would be the |
245 | push-style twitter API which starts a JSON/XML stream). |
274 | push-style twitter API which starts a JSON/XML stream). |
246 | |
275 | |
247 | If you think you need this, first have a look at C<on_body>, to see if |
276 | If you think you need this, first have a look at C<on_body>, to see if |
248 | that doesn'T solve your problem in a better way. |
277 | that doesn't solve your problem in a better way. |
249 | |
278 | |
250 | =back |
279 | =back |
251 | |
280 | |
252 | Example: make a simple HTTP GET request for http://www.nethype.de/ |
281 | Example: make a simple HTTP GET request for http://www.nethype.de/ |
253 | |
282 | |
… | |
… | |
309 | push @{ $CO_SLOT{$_[0]}[1] }, $_[1]; |
338 | push @{ $CO_SLOT{$_[0]}[1] }, $_[1]; |
310 | |
339 | |
311 | _slot_schedule $_[0]; |
340 | _slot_schedule $_[0]; |
312 | } |
341 | } |
313 | |
342 | |
314 | our $qr_nl = qr<\015?\012>; |
343 | our $qr_nlnl = qr{(?<![^\012])\015?\012}; |
315 | our $qr_nlnl = qr<\015?\012\015?\012>; |
|
|
316 | |
344 | |
317 | our $TLS_CTX_LOW = { cache => 1, sslv2 => 1 }; |
345 | our $TLS_CTX_LOW = { cache => 1, sslv2 => 1 }; |
318 | our $TLS_CTX_HIGH = { cache => 1, verify => 1, verify_peername => "https" }; |
346 | our $TLS_CTX_HIGH = { cache => 1, verify => 1, verify_peername => "https" }; |
319 | |
347 | |
320 | sub http_request($$@) { |
348 | sub http_request($$@) { |
… | |
… | |
332 | while (my ($k, $v) = each %$hdr) { |
360 | while (my ($k, $v) = each %$hdr) { |
333 | $hdr{lc $k} = $v; |
361 | $hdr{lc $k} = $v; |
334 | } |
362 | } |
335 | } |
363 | } |
336 | |
364 | |
|
|
365 | # pseudo headers for all subsequent responses |
|
|
366 | my @pseudo = (URL => $url); |
|
|
367 | push @pseudo, Redirect => delete $arg{Redirect} if exists $arg{Redirect}; |
|
|
368 | |
337 | my $recurse = exists $arg{recurse} ? delete $arg{recurse} : $MAX_RECURSE; |
369 | my $recurse = exists $arg{recurse} ? delete $arg{recurse} : $MAX_RECURSE; |
338 | |
370 | |
339 | return $cb->(undef, { Status => 599, Reason => "Too many redirections", URL => $url }) |
371 | return $cb->(undef, { Status => 599, Reason => "Too many redirections", @pseudo }) |
340 | if $recurse < 0; |
372 | if $recurse < 0; |
341 | |
373 | |
342 | my $proxy = $arg{proxy} || $PROXY; |
374 | my $proxy = $arg{proxy} || $PROXY; |
343 | my $timeout = $arg{timeout} || $TIMEOUT; |
375 | my $timeout = $arg{timeout} || $TIMEOUT; |
344 | |
376 | |
345 | my ($uscheme, $uauthority, $upath, $query, $fragment) = |
377 | my ($uscheme, $uauthority, $upath, $query, $fragment) = |
346 | $url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?|; |
378 | $url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:(\?[^#]*))?(?:#(.*))?|; |
347 | |
379 | |
348 | $uscheme = lc $uscheme; |
380 | $uscheme = lc $uscheme; |
349 | |
381 | |
350 | my $uport = $uscheme eq "http" ? 80 |
382 | my $uport = $uscheme eq "http" ? 80 |
351 | : $uscheme eq "https" ? 443 |
383 | : $uscheme eq "https" ? 443 |
352 | : return $cb->(undef, { Status => 599, Reason => "Only http and https URL schemes supported", URL => $url }); |
384 | : return $cb->(undef, { Status => 599, Reason => "Only http and https URL schemes supported", @pseudo }); |
353 | |
385 | |
354 | $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x |
386 | $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x |
355 | or return $cb->(undef, { Status => 599, Reason => "Unparsable URL", URL => $url }); |
387 | or return $cb->(undef, { Status => 599, Reason => "Unparsable URL", @pseudo }); |
356 | |
388 | |
357 | my $uhost = $1; |
389 | my $uhost = $1; |
358 | $uport = $2 if defined $2; |
390 | $uport = $2 if defined $2; |
359 | |
391 | |
360 | $hdr{host} = defined $2 ? "$uhost:$2" : "$uhost"; |
392 | $hdr{host} = defined $2 ? "$uhost:$2" : "$uhost" |
|
|
393 | unless exists $hdr{host}; |
361 | |
394 | |
362 | $uhost =~ s/^\[(.*)\]$/$1/; |
395 | $uhost =~ s/^\[(.*)\]$/$1/; |
363 | $upath .= "?$query" if length $query; |
396 | $upath .= $query if length $query; |
364 | |
397 | |
365 | $upath =~ s%^/?%/%; |
398 | $upath =~ s%^/?%/%; |
366 | |
399 | |
367 | # cookie processing |
400 | # cookie processing |
368 | if (my $jar = $arg{cookie_jar}) { |
401 | if (my $jar = $arg{cookie_jar}) { |
… | |
… | |
398 | my ($rhost, $rport, $rscheme, $rpath); # request host, port, path |
431 | my ($rhost, $rport, $rscheme, $rpath); # request host, port, path |
399 | |
432 | |
400 | if ($proxy) { |
433 | if ($proxy) { |
401 | ($rpath, $rhost, $rport, $rscheme) = ($url, @$proxy); |
434 | ($rpath, $rhost, $rport, $rscheme) = ($url, @$proxy); |
402 | |
435 | |
|
|
436 | $rscheme = "http" unless defined $rscheme; |
|
|
437 | |
403 | # don't support https requests over https-proxy transport, |
438 | # don't support https requests over https-proxy transport, |
404 | # can't be done with tls as spec'ed, unless you double-encrypt. |
439 | # can't be done with tls as spec'ed, unless you double-encrypt. |
405 | $rscheme = "http" if $uscheme eq "https" && $rscheme eq "https"; |
440 | $rscheme = "http" if $uscheme eq "https" && $rscheme eq "https"; |
406 | } else { |
441 | } else { |
407 | ($rhost, $rport, $rscheme, $rpath) = ($uhost, $uport, $uscheme, $upath); |
442 | ($rhost, $rport, $rscheme, $rpath) = ($uhost, $uport, $uscheme, $upath); |
408 | } |
443 | } |
409 | |
444 | |
410 | $hdr{"user-agent"} ||= $USERAGENT; |
445 | # leave out fragment and query string, just a heuristic |
411 | $hdr{referer} ||= "$uscheme://$uauthority$upath"; # leave out fragment and query string, just a heuristic |
446 | $hdr{referer} ||= "$uscheme://$uauthority$upath" unless exists $hdr{referer}; |
|
|
447 | $hdr{"user-agent"} ||= $USERAGENT unless exists $hdr{"user-agent"}; |
412 | |
448 | |
413 | $hdr{"content-length"} = length $arg{body}; |
449 | $hdr{"content-length"} = length $arg{body} |
|
|
450 | if length $arg{body} || $method ne "GET"; |
414 | |
451 | |
415 | my %state = (connect_guard => 1); |
452 | my %state = (connect_guard => 1); |
416 | |
453 | |
417 | _get_slot $uhost, sub { |
454 | _get_slot $uhost, sub { |
418 | $state{slot_guard} = shift; |
455 | $state{slot_guard} = shift; |
… | |
… | |
422 | $state{connect_guard} = AnyEvent::Socket::tcp_connect $rhost, $rport, sub { |
459 | $state{connect_guard} = AnyEvent::Socket::tcp_connect $rhost, $rport, sub { |
423 | $state{fh} = shift |
460 | $state{fh} = shift |
424 | or do { |
461 | or do { |
425 | my $err = "$!"; |
462 | my $err = "$!"; |
426 | %state = (); |
463 | %state = (); |
427 | return $cb->(undef, { Status => 599, Reason => $err, URL => $url }); |
464 | return $cb->(undef, { Status => 599, Reason => $err, @pseudo }); |
428 | }; |
465 | }; |
429 | |
466 | |
430 | pop; # free memory, save a tree |
467 | pop; # free memory, save a tree |
431 | |
468 | |
432 | return unless delete $state{connect_guard}; |
469 | return unless delete $state{connect_guard}; |
433 | |
470 | |
434 | # get handle |
471 | # get handle |
435 | $state{handle} = new AnyEvent::Handle |
472 | $state{handle} = new AnyEvent::Handle |
436 | fh => $state{fh}, |
473 | fh => $state{fh}, |
|
|
474 | peername => $rhost, |
|
|
475 | tls_ctx => $arg{tls_ctx}, |
|
|
476 | # these need to be reconfigured on keepalive handles |
437 | timeout => $timeout, |
477 | timeout => $timeout, |
438 | peername => $rhost, |
478 | on_error => sub { |
439 | tls_ctx => $arg{tls_ctx}; |
479 | %state = (); |
|
|
480 | $cb->(undef, { Status => 599, Reason => $_[2], @pseudo }); |
|
|
481 | }, |
|
|
482 | on_eof => sub { |
|
|
483 | %state = (); |
|
|
484 | $cb->(undef, { Status => 599, Reason => "Unexpected end-of-file", @pseudo }); |
|
|
485 | }, |
|
|
486 | ; |
440 | |
487 | |
441 | # limit the number of persistent connections |
488 | # limit the number of persistent connections |
442 | # keepalive not yet supported |
489 | # keepalive not yet supported |
443 | if ($KA_COUNT{$_[1]} < $MAX_PERSISTENT_PER_HOST) { |
490 | # if ($KA_COUNT{$_[1]} < $MAX_PERSISTENT_PER_HOST) { |
444 | ++$KA_COUNT{$_[1]}; |
491 | # ++$KA_COUNT{$_[1]}; |
445 | $state{handle}{ka_count_guard} = AnyEvent::Util::guard { |
492 | # $state{handle}{ka_count_guard} = AnyEvent::Util::guard { |
446 | --$KA_COUNT{$_[1]} |
493 | # --$KA_COUNT{$_[1]} |
447 | }; |
494 | # }; |
448 | $hdr{connection} = "keep-alive"; |
495 | # $hdr{connection} = "keep-alive"; |
449 | } else { |
496 | # } else { |
450 | delete $hdr{connection}; |
497 | delete $hdr{connection}; |
451 | } |
498 | # } |
452 | |
|
|
453 | # (re-)configure handle |
|
|
454 | $state{handle}->on_error (sub { |
|
|
455 | %state = (); |
|
|
456 | $cb->(undef, { Status => 599, Reason => $_[2], URL => $url }); |
|
|
457 | }); |
|
|
458 | $state{handle}->on_eof (sub { |
|
|
459 | %state = (); |
|
|
460 | $cb->(undef, { Status => 599, Reason => "Unexpected end-of-file", URL => $url }); |
|
|
461 | }); |
|
|
462 | |
499 | |
463 | $state{handle}->starttls ("connect") if $rscheme eq "https"; |
500 | $state{handle}->starttls ("connect") if $rscheme eq "https"; |
464 | |
501 | |
465 | # handle actual, non-tunneled, request |
502 | # handle actual, non-tunneled, request |
466 | my $handle_actual_request = sub { |
503 | my $handle_actual_request = sub { |
467 | $state{handle}->starttls ("connect") if $uscheme eq "https" && !exists $state{handle}{tls}; |
504 | $state{handle}->starttls ("connect") if $uscheme eq "https" && !exists $state{handle}{tls}; |
468 | |
505 | |
469 | # send request |
506 | # send request |
470 | $state{handle}->push_write ( |
507 | $state{handle}->push_write ( |
471 | "$method $rpath HTTP/1.0\015\012" |
508 | "$method $rpath HTTP/1.0\015\012" |
472 | . (join "", map "\u$_: $hdr{$_}\015\012", keys %hdr) |
509 | . (join "", map "\u$_: $hdr{$_}\015\012", grep defined $hdr{$_}, keys %hdr) |
473 | . "\015\012" |
510 | . "\015\012" |
474 | . (delete $arg{body}) |
511 | . (delete $arg{body}) |
475 | ); |
512 | ); |
476 | |
513 | |
|
|
514 | # return if error occured during push_write() |
|
|
515 | return unless %state; |
|
|
516 | |
477 | %hdr = (); # reduce memory usage, save a kitten |
517 | %hdr = (); # reduce memory usage, save a kitten, also make it possible to re-use |
478 | |
518 | |
479 | # status line |
519 | # status line and headers |
480 | $state{handle}->push_read (line => $qr_nl, sub { |
520 | $state{handle}->push_read (line => $qr_nlnl, sub { |
481 | $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix |
|
|
482 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid server response ($_[1])", URL => $url })); |
|
|
483 | |
|
|
484 | my %hdr = ( # response headers |
|
|
485 | HTTPVersion => ",$1", |
|
|
486 | Status => ",$2", |
|
|
487 | Reason => ",$3", |
|
|
488 | URL => ",$url" |
|
|
489 | ); |
|
|
490 | |
|
|
491 | # headers, could be optimized a bit |
|
|
492 | $state{handle}->unshift_read (line => $qr_nlnl, sub { |
|
|
493 | for ("$_[1]\012") { |
521 | for ("$_[1]") { |
494 | y/\015//d; # weed out any \015, as they show up in the weirdest of places. |
522 | y/\015//d; # weed out any \015, as they show up in the weirdest of places. |
495 | |
523 | |
|
|
524 | /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )? \015?\012/igxc |
|
|
525 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid server response", @pseudo })); |
|
|
526 | |
|
|
527 | push @pseudo, |
|
|
528 | HTTPVersion => $1, |
|
|
529 | Status => $2, |
|
|
530 | Reason => $3, |
|
|
531 | ; |
|
|
532 | |
496 | # things seen, not parsed: |
533 | # things seen, not parsed: |
497 | # p3pP="NON CUR OTPi OUR NOR UNI" |
534 | # p3pP="NON CUR OTPi OUR NOR UNI" |
498 | |
535 | |
499 | $hdr{lc $1} .= ",$2" |
536 | $hdr{lc $1} .= ",$2" |
500 | while /\G |
537 | while /\G |
501 | ([^:\000-\037]*): |
538 | ([^:\000-\037]*): |
502 | [\011\040]* |
539 | [\011\040]* |
503 | ((?: [^\012]+ | \012[\011\040] )*) |
540 | ((?: [^\012]+ | \012[\011\040] )*) |
504 | \012 |
541 | \012 |
505 | /gxc; |
542 | /gxc; |
506 | |
543 | |
507 | /\G$/ |
544 | /\G$/ |
508 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Garbled response headers", URL => $url })); |
545 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Garbled response headers", @pseudo })); |
|
|
546 | } |
|
|
547 | |
|
|
548 | # remove the "," prefix we added to all headers above |
|
|
549 | substr $_, 0, 1, "" |
|
|
550 | for values %hdr; |
|
|
551 | |
|
|
552 | # patch in all pseudo headers |
|
|
553 | %hdr = (%hdr, @pseudo); |
|
|
554 | |
|
|
555 | # redirect handling |
|
|
556 | # microsoft and other shitheads don't give a shit for following standards, |
|
|
557 | # try to support some common forms of broken Location headers. |
|
|
558 | if ($hdr{location} !~ /^(?: $ | [^:\/?\#]+ : )/x) { |
|
|
559 | $hdr{location} =~ s/^\.\/+//; |
|
|
560 | |
|
|
561 | my $url = "$rscheme://$uhost:$uport"; |
|
|
562 | |
|
|
563 | unless ($hdr{location} =~ s/^\///) { |
|
|
564 | $url .= $upath; |
|
|
565 | $url =~ s/\/[^\/]*$//; |
509 | } |
566 | } |
510 | |
567 | |
511 | substr $_, 0, 1, "" |
|
|
512 | for values %hdr; |
|
|
513 | |
|
|
514 | # redirect handling |
|
|
515 | # microsoft and other shitheads don't give a shit for following standards, |
|
|
516 | # try to support some common forms of broken Location headers. |
|
|
517 | if ($hdr{location} !~ /^(?: $ | [^:\/?\#]+ : )/x) { |
|
|
518 | $hdr{location} =~ s/^\.\/+//; |
|
|
519 | |
|
|
520 | my $url = "$rscheme://$uhost:$uport"; |
|
|
521 | |
|
|
522 | unless ($hdr{location} =~ s/^\///) { |
|
|
523 | $url .= $upath; |
|
|
524 | $url =~ s/\/[^\/]*$//; |
|
|
525 | } |
|
|
526 | |
|
|
527 | $hdr{location} = "$url/$hdr{location}"; |
568 | $hdr{location} = "$url/$hdr{location}"; |
|
|
569 | } |
|
|
570 | |
|
|
571 | my $redirect; |
|
|
572 | |
|
|
573 | if ($recurse) { |
|
|
574 | my $status = $hdr{Status}; |
|
|
575 | |
|
|
576 | # industry standard is to redirect POST as GET for |
|
|
577 | # 301, 302 and 303, in contrast to http/1.0 and 1.1. |
|
|
578 | # also, the UA should ask the user for 301 and 307 and POST, |
|
|
579 | # industry standard seems to be to simply follow. |
|
|
580 | # we go with the industry standard. |
|
|
581 | if ($status == 301 or $status == 302 or $status == 303) { |
|
|
582 | # HTTP/1.1 is unclear on how to mutate the method |
|
|
583 | $method = "GET" unless $method eq "HEAD"; |
|
|
584 | $redirect = 1; |
|
|
585 | } elsif ($status == 307) { |
|
|
586 | $redirect = 1; |
528 | } |
587 | } |
|
|
588 | } |
529 | |
589 | |
530 | my $redirect; |
590 | my $finish = sub { |
|
|
591 | $state{handle}->destroy if $state{handle}; |
|
|
592 | %state = (); |
531 | |
593 | |
|
|
594 | # set-cookie processing |
532 | if ($recurse) { |
595 | if ($arg{cookie_jar}) { |
533 | if ($hdr{Status} =~ /^30[12]$/ && $method ne "POST") { |
596 | for ($_[1]{"set-cookie"}) { |
534 | # apparently, mozilla et al. just change POST to GET here |
597 | # parse NAME=VALUE |
535 | # more research is needed before we do the same |
598 | my @kv; |
|
|
599 | |
|
|
600 | while (/\G\s* ([^=;,[:space:]]+) \s*=\s* (?: "((?:[^\\"]+|\\.)*)" | ([^=;,[:space:]]*) )/gcxs) { |
536 | $redirect = 1; |
601 | my $name = $1; |
537 | } elsif ($hdr{Status} == 303) { |
602 | my $value = $3; |
538 | # even http/1.1 is unclear on how to mutate the method |
603 | |
539 | $method = "GET" unless $method eq "HEAD"; |
604 | unless ($value) { |
|
|
605 | $value = $2; |
|
|
606 | $value =~ s/\\(.)/$1/gs; |
|
|
607 | } |
|
|
608 | |
|
|
609 | push @kv, $name => $value; |
|
|
610 | |
|
|
611 | last unless /\G\s*;/gc; |
|
|
612 | } |
|
|
613 | |
|
|
614 | last unless @kv; |
|
|
615 | |
|
|
616 | my $name = shift @kv; |
|
|
617 | my %kv = (value => shift @kv, @kv); |
|
|
618 | |
|
|
619 | my $cdom; |
|
|
620 | my $cpath = (delete $kv{path}) || "/"; |
|
|
621 | |
|
|
622 | if (exists $kv{domain}) { |
|
|
623 | $cdom = delete $kv{domain}; |
|
|
624 | |
|
|
625 | $cdom =~ s/^\.?/./; # make sure it starts with a "." |
|
|
626 | |
|
|
627 | next if $cdom =~ /\.$/; |
|
|
628 | |
|
|
629 | # this is not rfc-like and not netscape-like. go figure. |
|
|
630 | my $ndots = $cdom =~ y/.//; |
|
|
631 | next if $ndots < ($cdom =~ /\.[^.][^.]\.[^.][^.]$/ ? 3 : 2); |
|
|
632 | } else { |
|
|
633 | $cdom = $uhost; |
|
|
634 | } |
|
|
635 | |
540 | $redirect = 1; |
636 | # store it |
541 | } elsif ($hdr{Status} == 307 && $method =~ /^(?:GET|HEAD)$/) { |
637 | $arg{cookie_jar}{version} = 1; |
542 | $redirect = 1; |
638 | $arg{cookie_jar}{$cdom}{$cpath}{$name} = \%kv; |
|
|
639 | |
|
|
640 | redo if /\G\s*,/gc; |
543 | } |
641 | } |
544 | } |
642 | } |
545 | |
643 | |
546 | my $finish = sub { |
644 | if ($redirect && exists $hdr{location}) { |
547 | $state{handle}->destroy if $state{handle}; |
645 | # we ignore any errors, as it is very common to receive |
548 | %state = (); |
646 | # Content-Length != 0 but no actual body |
549 | |
647 | # we also access %hdr, as $_[1] might be an erro |
550 | # set-cookie processing |
648 | http_request ( |
551 | if ($arg{cookie_jar}) { |
649 | $method => $hdr{location}, |
552 | for ($_[1]{"set-cookie"}) { |
|
|
553 | # parse NAME=VALUE |
|
|
554 | my @kv; |
|
|
555 | |
|
|
556 | while (/\G\s* ([^=;,[:space:]]+) \s*=\s* (?: "((?:[^\\"]+|\\.)*)" | ([^=;,[:space:]]*) )/gcxs) { |
|
|
557 | my $name = $1; |
|
|
558 | my $value = $3; |
|
|
559 | |
|
|
560 | unless ($value) { |
|
|
561 | $value = $2; |
|
|
562 | $value =~ s/\\(.)/$1/gs; |
|
|
563 | } |
650 | %arg, |
|
|
651 | recurse => $recurse - 1, |
|
|
652 | Redirect => \@_, |
|
|
653 | $cb); |
|
|
654 | } else { |
|
|
655 | $cb->($_[0], $_[1]); |
|
|
656 | } |
|
|
657 | }; |
564 | |
658 | |
565 | push @kv, $name => $value; |
659 | my $len = $hdr{"content-length"}; |
566 | |
660 | |
567 | last unless /\G\s*;/gc; |
661 | if (!$redirect && $arg{on_header} && !$arg{on_header}(\%hdr)) { |
|
|
662 | $finish->(undef, { Status => 598, Reason => "Request cancelled by on_header", @pseudo }); |
|
|
663 | } elsif ( |
|
|
664 | $hdr{Status} =~ /^(?:1..|[23]04)$/ |
|
|
665 | or $method eq "HEAD" |
|
|
666 | or (defined $len && !$len) |
|
|
667 | ) { |
|
|
668 | # no body |
|
|
669 | $finish->("", \%hdr); |
|
|
670 | } else { |
|
|
671 | # body handling, four different code paths |
|
|
672 | # for want_body_handle, on_body (2x), normal (2x) |
|
|
673 | # we might read too much here, but it does not matter yet (no pers. connections) |
|
|
674 | if (!$redirect && $arg{want_body_handle}) { |
|
|
675 | $_[0]->on_eof (undef); |
|
|
676 | $_[0]->on_error (undef); |
|
|
677 | $_[0]->on_read (undef); |
|
|
678 | |
|
|
679 | $finish->(delete $state{handle}, \%hdr); |
|
|
680 | |
|
|
681 | } elsif ($arg{on_body}) { |
|
|
682 | $_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], @pseudo }) }); |
|
|
683 | if ($len) { |
|
|
684 | $_[0]->on_eof (undef); |
|
|
685 | $_[0]->on_read (sub { |
|
|
686 | $len -= length $_[0]{rbuf}; |
|
|
687 | |
|
|
688 | $arg{on_body}(delete $_[0]{rbuf}, \%hdr) |
|
|
689 | or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", @pseudo }); |
|
|
690 | |
568 | } |
691 | $len > 0 |
569 | |
692 | or $finish->("", \%hdr); |
570 | last unless @kv; |
|
|
571 | |
|
|
572 | my $name = shift @kv; |
|
|
573 | my %kv = (value => shift @kv, @kv); |
|
|
574 | |
|
|
575 | my $cdom; |
|
|
576 | my $cpath = (delete $kv{path}) || "/"; |
|
|
577 | |
|
|
578 | if (exists $kv{domain}) { |
|
|
579 | $cdom = delete $kv{domain}; |
|
|
580 | |
|
|
581 | $cdom =~ s/^\.?/./; # make sure it starts with a "." |
|
|
582 | |
|
|
583 | next if $cdom =~ /\.$/; |
|
|
584 | |
|
|
585 | # this is not rfc-like and not netscape-like. go figure. |
|
|
586 | my $ndots = $cdom =~ y/.//; |
|
|
587 | next if $ndots < ($cdom =~ /\.[^.][^.]\.[^.][^.]$/ ? 3 : 2); |
|
|
588 | } else { |
|
|
589 | $cdom = $uhost; |
|
|
590 | } |
|
|
591 | |
|
|
592 | # store it |
|
|
593 | $arg{cookie_jar}{version} = 1; |
|
|
594 | $arg{cookie_jar}{$cdom}{$cpath}{$name} = \%kv; |
|
|
595 | |
|
|
596 | redo if /\G\s*,/gc; |
|
|
597 | } |
693 | }); |
|
|
694 | } else { |
|
|
695 | $_[0]->on_eof (sub { |
|
|
696 | $finish->("", \%hdr); |
|
|
697 | }); |
|
|
698 | $_[0]->on_read (sub { |
|
|
699 | $arg{on_body}(delete $_[0]{rbuf}, \%hdr) |
|
|
700 | or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", @pseudo }); |
|
|
701 | }); |
598 | } |
702 | } |
|
|
703 | } else { |
|
|
704 | $_[0]->on_eof (undef); |
599 | |
705 | |
600 | if ($redirect) { |
706 | if ($len) { |
601 | # we ignore any errors, as it is very common to receive |
707 | $_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], @pseudo }) }); |
602 | # Content-Length != 0 but no actual body |
708 | $_[0]->on_read (sub { |
603 | # we also access %hdr, as $_[1] might be an erro |
709 | $finish->((substr delete $_[0]{rbuf}, 0, $len, ""), \%hdr) |
604 | http_request ($method => $hdr{location}, %arg, recurse => $recurse - 1, $cb); |
710 | if $len <= length $_[0]{rbuf}; |
|
|
711 | }); |
605 | } else { |
712 | } else { |
606 | $cb->($_[0], $_[1]); |
|
|
607 | } |
|
|
608 | }; |
|
|
609 | |
|
|
610 | my $len = $hdr{"content-length"}; |
|
|
611 | |
|
|
612 | if (!$redirect && $arg{on_header} && !$arg{on_header}(\%hdr)) { |
|
|
613 | $finish->(undef, { Status => 598, Reason => "Request cancelled by on_header", URL => $url }); |
|
|
614 | } elsif ( |
|
|
615 | $hdr{Status} =~ /^(?:1..|[23]04)$/ |
|
|
616 | or $method eq "HEAD" |
|
|
617 | or (defined $len && !$len) |
|
|
618 | ) { |
|
|
619 | # no body |
|
|
620 | $finish->("", \%hdr); |
|
|
621 | } else { |
|
|
622 | # body handling, four different code paths |
|
|
623 | # for want_body_handle, on_body (2x), normal (2x) |
|
|
624 | # we might read too much here, but it does not matter yet (no pers. connections) |
|
|
625 | if (!$redirect && $arg{want_body_handle}) { |
|
|
626 | $_[0]->on_eof (undef); |
|
|
627 | $_[0]->on_error (undef); |
|
|
628 | $_[0]->on_read (undef); |
|
|
629 | |
|
|
630 | $finish->(delete $state{handle}, \%hdr); |
|
|
631 | |
|
|
632 | } elsif ($arg{on_body}) { |
|
|
633 | $_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], URL => $url }) }); |
|
|
634 | if ($len) { |
|
|
635 | $_[0]->on_eof (undef); |
|
|
636 | $_[0]->on_read (sub { |
|
|
637 | $len -= length $_[0]{rbuf}; |
|
|
638 | |
|
|
639 | $arg{on_body}(delete $_[0]{rbuf}, \%hdr) |
|
|
640 | or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", URL => $url }); |
|
|
641 | |
|
|
642 | $len > 0 |
|
|
643 | or $finish->("", \%hdr); |
|
|
644 | }); |
|
|
645 | } else { |
|
|
646 | $_[0]->on_eof (sub { |
|
|
647 | $finish->("", \%hdr); |
|
|
648 | }); |
|
|
649 | $_[0]->on_read (sub { |
|
|
650 | $arg{on_body}(delete $_[0]{rbuf}, \%hdr) |
|
|
651 | or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", URL => $url }); |
|
|
652 | }); |
|
|
653 | } |
|
|
654 | } else { |
|
|
655 | $_[0]->on_eof (undef); |
|
|
656 | |
|
|
657 | if ($len) { |
|
|
658 | $_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], URL => $url }) }); |
|
|
659 | $_[0]->on_read (sub { |
|
|
660 | $finish->((substr delete $_[0]{rbuf}, 0, $len, ""), \%hdr) |
|
|
661 | if $len <= length $_[0]{rbuf}; |
|
|
662 | }); |
|
|
663 | } else { |
|
|
664 | $_[0]->on_error (sub { |
713 | $_[0]->on_error (sub { |
665 | $! == Errno::EPIPE || !$! |
714 | ($! == Errno::EPIPE || !$!) |
666 | ? $finish->(delete $_[0]{rbuf}, \%hdr) |
715 | ? $finish->(delete $_[0]{rbuf}, \%hdr) |
667 | : $finish->(undef, { Status => 599, Reason => $_[2], URL => $url }); |
716 | : $finish->(undef, { Status => 599, Reason => $_[2], @pseudo }); |
668 | }); |
717 | }); |
669 | $_[0]->on_read (sub { }); |
718 | $_[0]->on_read (sub { }); |
670 | } |
|
|
671 | } |
719 | } |
672 | } |
720 | } |
673 | }); |
721 | } |
674 | }); |
722 | }); |
675 | }; |
723 | }; |
676 | |
724 | |
677 | # now handle proxy-CONNECT method |
725 | # now handle proxy-CONNECT method |
678 | if ($proxy && $uscheme eq "https") { |
726 | if ($proxy && $uscheme eq "https") { |
… | |
… | |
680 | |
728 | |
681 | # maybe re-use $uauthority with patched port? |
729 | # maybe re-use $uauthority with patched port? |
682 | $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012Host: $uhost\015\012\015\012"); |
730 | $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012Host: $uhost\015\012\015\012"); |
683 | $state{handle}->push_read (line => $qr_nlnl, sub { |
731 | $state{handle}->push_read (line => $qr_nlnl, sub { |
684 | $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix |
732 | $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix |
685 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid proxy connect response ($_[1])", URL => $url })); |
733 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid proxy connect response ($_[1])", @pseudo })); |
686 | |
734 | |
687 | if ($2 == 200) { |
735 | if ($2 == 200) { |
688 | $rpath = $upath; |
736 | $rpath = $upath; |
689 | &$handle_actual_request; |
737 | &$handle_actual_request; |
690 | } else { |
738 | } else { |
691 | %state = (); |
739 | %state = (); |
692 | $cb->(undef, { Status => $2, Reason => $3, URL => $url }); |
740 | $cb->(undef, { Status => $2, Reason => $3, @pseudo }); |
693 | } |
741 | } |
694 | }); |
742 | }); |
695 | } else { |
743 | } else { |
696 | &$handle_actual_request; |
744 | &$handle_actual_request; |
697 | } |
745 | } |
698 | |
746 | |
699 | }, sub { |
747 | }, $arg{on_prepare} || sub { $timeout }; |
700 | $timeout |
|
|
701 | }; |
|
|
702 | }; |
748 | }; |
703 | |
749 | |
704 | defined wantarray && AnyEvent::Util::guard { %state = () } |
750 | defined wantarray && AnyEvent::Util::guard { %state = () } |
705 | } |
751 | } |
706 | |
752 | |
… | |
… | |
720 | &http_request |
766 | &http_request |
721 | } |
767 | } |
722 | |
768 | |
723 | =back |
769 | =back |
724 | |
770 | |
|
|
771 | =head2 DNS CACHING |
|
|
772 | |
|
|
773 | AnyEvent::HTTP uses the AnyEvent::Socket::tcp_connect function for |
|
|
774 | the actual connection, which in turn uses AnyEvent::DNS to resolve |
|
|
775 | hostnames. The latter is a simple stub resolver and does no caching |
|
|
776 | on its own. If you want DNS caching, you currently have to provide |
|
|
777 | your own default resolver (by storing a suitable resolver object in |
|
|
778 | C<$AnyEvent::DNS::RESOLVER>). |
|
|
779 | |
725 | =head2 GLOBAL FUNCTIONS AND VARIABLES |
780 | =head2 GLOBAL FUNCTIONS AND VARIABLES |
726 | |
781 | |
727 | =over 4 |
782 | =over 4 |
728 | |
783 | |
729 | =item AnyEvent::HTTP::set_proxy "proxy-url" |
784 | =item AnyEvent::HTTP::set_proxy "proxy-url" |
730 | |
785 | |
731 | Sets the default proxy server to use. The proxy-url must begin with a |
786 | Sets the default proxy server to use. The proxy-url must begin with a |
732 | string of the form C<http://host:port> (optionally C<https:...>). |
787 | string of the form C<http://host:port> (optionally C<https:...>), croaks |
|
|
788 | otherwise. |
|
|
789 | |
|
|
790 | To clear an already-set proxy, use C<undef>. |
733 | |
791 | |
734 | =item $AnyEvent::HTTP::MAX_RECURSE |
792 | =item $AnyEvent::HTTP::MAX_RECURSE |
735 | |
793 | |
736 | The default value for the C<recurse> request parameter (default: C<10>). |
794 | The default value for the C<recurse> request parameter (default: C<10>). |
737 | |
795 | |
… | |
… | |
740 | The default value for the C<User-Agent> header (the default is |
798 | The default value for the C<User-Agent> header (the default is |
741 | C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>). |
799 | C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>). |
742 | |
800 | |
743 | =item $AnyEvent::HTTP::MAX_PER_HOST |
801 | =item $AnyEvent::HTTP::MAX_PER_HOST |
744 | |
802 | |
745 | The maximum number of concurrent conenctions to the same host (identified |
803 | The maximum number of concurrent connections to the same host (identified |
746 | by the hostname). If the limit is exceeded, then the additional requests |
804 | by the hostname). If the limit is exceeded, then the additional requests |
747 | are queued until previous connections are closed. |
805 | are queued until previous connections are closed. |
748 | |
806 | |
749 | The default value for this is C<4>, and it is highly advisable to not |
807 | The default value for this is C<4>, and it is highly advisable to not |
750 | increase it. |
808 | increase it. |
… | |
… | |
758 | =back |
816 | =back |
759 | |
817 | |
760 | =cut |
818 | =cut |
761 | |
819 | |
762 | sub set_proxy($) { |
820 | sub set_proxy($) { |
|
|
821 | if (length $_[0]) { |
763 | $PROXY = [$2, $3 || 3128, $1] if $_[0] =~ m%^(https?):// ([^:/]+) (?: : (\d*) )?%ix; |
822 | $_[0] =~ m%^(https?):// ([^:/]+) (?: : (\d*) )?%ix |
|
|
823 | or Carp::croak "$_[0]: invalid proxy URL"; |
|
|
824 | $PROXY = [$2, $3 || 3128, $1] |
|
|
825 | } else { |
|
|
826 | undef $PROXY; |
|
|
827 | } |
764 | } |
828 | } |
765 | |
829 | |
766 | # initialise proxy from environment |
830 | # initialise proxy from environment |
|
|
831 | eval { |
767 | set_proxy $ENV{http_proxy}; |
832 | set_proxy $ENV{http_proxy}; |
|
|
833 | }; |
768 | |
834 | |
769 | =head1 SEE ALSO |
835 | =head1 SEE ALSO |
770 | |
836 | |
771 | L<AnyEvent>. |
837 | L<AnyEvent>. |
772 | |
838 | |