ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-HTTP/HTTP.pm
(Generate patch)

Comparing AnyEvent-HTTP/HTTP.pm (file contents):
Revision 1.92 by root, Tue Jan 4 08:17:59 2011 UTC vs.
Revision 1.134 by root, Fri Sep 7 22:11:31 2018 UTC

15This module is an L<AnyEvent> user, you need to make sure that you use and 15This module is an L<AnyEvent> user, you need to make sure that you use and
16run a supported event loop. 16run a supported event loop.
17 17
18This module implements a simple, stateless and non-blocking HTTP 18This module implements a simple, stateless and non-blocking HTTP
19client. It supports GET, POST and other request methods, cookies and more, 19client. It supports GET, POST and other request methods, cookies and more,
20all on a very low level. It can follow redirects supports proxies and 20all on a very low level. It can follow redirects, supports proxies, and
21automatically limits the number of connections to the values specified in 21automatically limits the number of connections to the values specified in
22the RFC. 22the RFC.
23 23
24It should generally be a "good client" that is enough for most HTTP 24It should generally be a "good client" that is enough for most HTTP
25tasks. Simple tasks should be simple, but complex tasks should still be 25tasks. Simple tasks should be simple, but complex tasks should still be
46use AnyEvent::Util (); 46use AnyEvent::Util ();
47use AnyEvent::Handle (); 47use AnyEvent::Handle ();
48 48
49use base Exporter::; 49use base Exporter::;
50 50
51our $VERSION = '2.0'; 51our $VERSION = 2.24;
52 52
53our @EXPORT = qw(http_get http_post http_head http_request); 53our @EXPORT = qw(http_get http_post http_head http_request);
54 54
55our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)"; 55our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)";
56our $MAX_RECURSE = 10; 56our $MAX_RECURSE = 10;
89C<http_request> returns a "cancellation guard" - you have to keep the 89C<http_request> returns a "cancellation guard" - you have to keep the
90object at least alive until the callback get called. If the object gets 90object at least alive until the callback get called. If the object gets
91destroyed before the callback is called, the request will be cancelled. 91destroyed before the callback is called, the request will be cancelled.
92 92
93The callback will be called with the response body data as first argument 93The callback will be called with the response body data as first argument
94(or C<undef> if an error occured), and a hash-ref with response headers 94(or C<undef> if an error occurred), and a hash-ref with response headers
95(and trailers) as second argument. 95(and trailers) as second argument.
96 96
97All the headers in that hash are lowercased. In addition to the response 97All the headers in that hash are lowercased. In addition to the response
98headers, the "pseudo-headers" (uppercase to avoid clashing with possible 98headers, the "pseudo-headers" (uppercase to avoid clashing with possible
99response headers) C<HTTPVersion>, C<Status> and C<Reason> contain the 99response headers) C<HTTPVersion>, C<Status> and C<Reason> contain the
123C<590>-C<599> and the C<Reason> pseudo-header will contain an error 123C<590>-C<599> and the C<Reason> pseudo-header will contain an error
124message. Currently the following status codes are used: 124message. Currently the following status codes are used:
125 125
126=over 4 126=over 4
127 127
128=item 595 - errors during connection etsbalishment, proxy handshake. 128=item 595 - errors during connection establishment, proxy handshake.
129 129
130=item 596 - errors during TLS negotiation, request sending and header processing. 130=item 596 - errors during TLS negotiation, request sending and header processing.
131 131
132=item 597 - errors during body receiving or processing. 132=item 597 - errors during body receiving or processing.
133 133
154 154
155=over 4 155=over 4
156 156
157=item recurse => $count (default: $MAX_RECURSE) 157=item recurse => $count (default: $MAX_RECURSE)
158 158
159Whether to recurse requests or not, e.g. on redirects, authentication 159Whether to recurse requests or not, e.g. on redirects, authentication and
160retries and so on, and how often to do so. 160other retries and so on, and how often to do so.
161
162Only redirects to http and https URLs are supported. While most common
163redirection forms are handled entirely within this module, some require
164the use of the optional L<URI> module. If it is required but missing, then
165the request will fail with an error.
161 166
162=item headers => hashref 167=item headers => hashref
163 168
164The request headers to use. Currently, C<http_request> may provide its own 169The request headers to use. Currently, C<http_request> may provide its own
165C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers and 170C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers and
169 174
170You really should provide your own C<User-Agent:> header value that is 175You really should provide your own C<User-Agent:> header value that is
171appropriate for your program - I wouldn't be surprised if the default 176appropriate for your program - I wouldn't be surprised if the default
172AnyEvent string gets blocked by webservers sooner or later. 177AnyEvent string gets blocked by webservers sooner or later.
173 178
179Also, make sure that your headers names and values do not contain any
180embedded newlines.
181
174=item timeout => $seconds 182=item timeout => $seconds
175 183
176The time-out to use for various stages - each connect attempt will reset 184The time-out to use for various stages - each connect attempt will reset
177the timeout, as will read or write activity, i.e. this is not an overall 185the timeout, as will read or write activity, i.e. this is not an overall
178timeout. 186timeout.
179 187
180Default timeout is 5 minutes. 188Default timeout is 5 minutes.
181 189
182=item proxy => [$host, $port[, $scheme]] or undef 190=item proxy => [$host, $port[, $scheme]] or undef
183 191
184Use the given http proxy for all requests. If not specified, then the 192Use the given http proxy for all requests, or no proxy if C<undef> is
185default proxy (as specified by C<$ENV{http_proxy}>) is used. 193used.
186 194
187C<$scheme> must be either missing or must be C<http> for HTTP. 195C<$scheme> must be either missing or must be C<http> for HTTP.
196
197If not specified, then the default proxy is used (see
198C<AnyEvent::HTTP::set_proxy>).
199
200Currently, if your proxy requires authorization, you have to specify an
201appropriate "Proxy-Authorization" header in every request.
188 202
189=item body => $string 203=item body => $string
190 204
191The request body, usually empty. Will be sent as-is (future versions of 205The request body, usually empty. Will be sent as-is (future versions of
192this module might offer more options). 206this module might offer more options).
236context) - only connections using the same unique ID will be reused. 250context) - only connections using the same unique ID will be reused.
237 251
238=item on_prepare => $callback->($fh) 252=item on_prepare => $callback->($fh)
239 253
240In rare cases you need to "tune" the socket before it is used to 254In rare cases you need to "tune" the socket before it is used to
241connect (for exmaple, to bind it on a given IP address). This parameter 255connect (for example, to bind it on a given IP address). This parameter
242overrides the prepare callback passed to C<AnyEvent::Socket::tcp_connect> 256overrides the prepare callback passed to C<AnyEvent::Socket::tcp_connect>
243and behaves exactly the same way (e.g. it has to provide a 257and behaves exactly the same way (e.g. it has to provide a
244timeout). See the description for the C<$prepare_cb> argument of 258timeout). See the description for the C<$prepare_cb> argument of
245C<AnyEvent::Socket::tcp_connect> for details. 259C<AnyEvent::Socket::tcp_connect> for details.
246 260
249In even rarer cases you want total control over how AnyEvent::HTTP 263In even rarer cases you want total control over how AnyEvent::HTTP
250establishes connections. Normally it uses L<AnyEvent::Socket::tcp_connect> 264establishes connections. Normally it uses L<AnyEvent::Socket::tcp_connect>
251to do this, but you can provide your own C<tcp_connect> function - 265to do this, but you can provide your own C<tcp_connect> function -
252obviously, it has to follow the same calling conventions, except that it 266obviously, it has to follow the same calling conventions, except that it
253may always return a connection guard object. 267may always return a connection guard object.
268
269The connections made by this hook will be treated as equivalent to
270connecitons made the built-in way, specifically, they will be put into
271and taken from the persistent conneciton cache. If your C<$tcp_connect>
272function is incompatible with this kind of re-use, consider switching off
273C<persistent> connections and/or providing a C<session> identifier.
254 274
255There are probably lots of weird uses for this function, starting from 275There are probably lots of weird uses for this function, starting from
256tracing the hosts C<http_request> actually tries to connect, to (inexact 276tracing the hosts C<http_request> actually tries to connect, to (inexact
257but fast) host => IP address caching or even socks protocol support. 277but fast) host => IP address caching or even socks protocol support.
258 278
328=item persistent => $boolean 348=item persistent => $boolean
329 349
330Try to create/reuse a persistent connection. When this flag is set 350Try to create/reuse a persistent connection. When this flag is set
331(default: true for idempotent requests, false for all others), then 351(default: true for idempotent requests, false for all others), then
332C<http_request> tries to re-use an existing (previously-created) 352C<http_request> tries to re-use an existing (previously-created)
333persistent connection to the host and, failing that, tries to create a new 353persistent connection to same host (i.e. identical URL scheme, hostname,
334one. 354port and session) and, failing that, tries to create a new one.
335 355
336Requests failing in certain ways will be automatically retried once, which 356Requests failing in certain ways will be automatically retried once, which
337is dangerous for non-idempotent requests, which is why it defaults to off 357is dangerous for non-idempotent requests, which is why it defaults to off
338for them. The reason for this is because the bozos who designed HTTP/1.1 358for them. The reason for this is because the bozos who designed HTTP/1.1
339made it impossible to distinguish between a fatal error and a normal 359made it impossible to distinguish between a fatal error and a normal
378 398
379Example: do a HTTP HEAD request on https://www.google.com/, use a 399Example: do a HTTP HEAD request on https://www.google.com/, use a
380timeout of 30 seconds. 400timeout of 30 seconds.
381 401
382 http_request 402 http_request
383 GET => "https://www.google.com", 403 HEAD => "https://www.google.com",
384 headers => { "user-agent" => "MySearchClient 1.0" }, 404 headers => { "user-agent" => "MySearchClient 1.0" },
385 timeout => 30, 405 timeout => 30,
386 sub { 406 sub {
387 my ($body, $hdr) = @_; 407 my ($body, $hdr) = @_;
388 use Data::Dumper; 408 use Data::Dumper;
440 460
441# expire cookies 461# expire cookies
442sub cookie_jar_expire($;$) { 462sub cookie_jar_expire($;$) {
443 my ($jar, $session_end) = @_; 463 my ($jar, $session_end) = @_;
444 464
445 %$jar = () if $jar->{version} != 1; 465 %$jar = () if $jar->{version} != 2;
446 466
447 my $anow = AE::now; 467 my $anow = AE::now;
448 468
449 while (my ($chost, $paths) = each %$jar) { 469 while (my ($chost, $paths) = each %$jar) {
450 next unless ref $paths; 470 next unless ref $paths;
470 490
471# extract cookies from jar 491# extract cookies from jar
472sub cookie_jar_extract($$$$) { 492sub cookie_jar_extract($$$$) {
473 my ($jar, $scheme, $host, $path) = @_; 493 my ($jar, $scheme, $host, $path) = @_;
474 494
475 %$jar = () if $jar->{version} != 1; 495 %$jar = () if $jar->{version} != 2;
496
497 $host = AnyEvent::Util::idn_to_ascii $host
498 if $host =~ /[^\x00-\x7f]/;
476 499
477 my @cookies; 500 my @cookies;
478 501
479 while (my ($chost, $paths) = each %$jar) { 502 while (my ($chost, $paths) = each %$jar) {
480 next unless ref $paths; 503 next unless ref $paths;
481 504
482 if ($chost =~ /^\./) { 505 # exact match or suffix including . match
483 next unless $chost eq substr $host, -length $chost; 506 $chost eq $host or ".$chost" eq substr $host, -1 - length $chost
484 } elsif ($chost =~ /\./) {
485 next unless $chost eq $host;
486 } else {
487 next; 507 or next;
488 }
489 508
490 while (my ($cpath, $cookies) = each %$paths) { 509 while (my ($cpath, $cookies) = each %$paths) {
491 next unless $cpath eq substr $path, 0, length $cpath; 510 next unless $cpath eq substr $path, 0, length $cpath;
492 511
493 while (my ($cookie, $kv) = each %$cookies) { 512 while (my ($cookie, $kv) = each %$cookies) {
514} 533}
515 534
516# parse set_cookie header into jar 535# parse set_cookie header into jar
517sub cookie_jar_set_cookie($$$$) { 536sub cookie_jar_set_cookie($$$$) {
518 my ($jar, $set_cookie, $host, $date) = @_; 537 my ($jar, $set_cookie, $host, $date) = @_;
538
539 %$jar = () if $jar->{version} != 2;
519 540
520 my $anow = int AE::now; 541 my $anow = int AE::now;
521 my $snow; # server-now 542 my $snow; # server-now
522 543
523 for ($set_cookie) { 544 for ($set_cookie) {
529 while ( 550 while (
530 m{ 551 m{
531 \G\s* 552 \G\s*
532 (?: 553 (?:
533 expires \s*=\s* ([A-Z][a-z][a-z]+,\ [^,;]+) 554 expires \s*=\s* ([A-Z][a-z][a-z]+,\ [^,;]+)
534 | ([^=;,[:space:]]+) (?: \s*=\s* (?: "((?:[^\\"]+|\\.)*)" | ([^=;,[:space:]]*) ) )? 555 | ([^=;,[:space:]]+) (?: \s*=\s* (?: "((?:[^\\"]+|\\.)*)" | ([^;,[:space:]]*) ) )?
535 ) 556 )
536 }gcxsi 557 }gcxsi
537 ) { 558 ) {
538 my $name = $2; 559 my $name = $2;
539 my $value = $4; 560 my $value = $4;
546 # quoted 567 # quoted
547 $value = $3; 568 $value = $3;
548 $value =~ s/\\(.)/$1/gs; 569 $value =~ s/\\(.)/$1/gs;
549 } 570 }
550 571
551 push @kv, lc $name, $value; 572 push @kv, @kv ? lc $name : $name, $value;
552 573
553 last unless /\G\s*;/gc; 574 last unless /\G\s*;/gc;
554 } 575 }
555 576
556 last unless @kv; 577 last unless @kv;
569 590
570 my $cdom; 591 my $cdom;
571 my $cpath = (delete $kv{path}) || "/"; 592 my $cpath = (delete $kv{path}) || "/";
572 593
573 if (exists $kv{domain}) { 594 if (exists $kv{domain}) {
574 $cdom = delete $kv{domain}; 595 $cdom = $kv{domain};
575 596
576 $cdom =~ s/^\.?/./; # make sure it starts with a "." 597 $cdom =~ s/^\.?/./; # make sure it starts with a "."
577 598
578 next if $cdom =~ /\.$/; 599 next if $cdom =~ /\.$/;
579 600
580 # this is not rfc-like and not netscape-like. go figure. 601 # this is not rfc-like and not netscape-like. go figure.
581 my $ndots = $cdom =~ y/.//; 602 my $ndots = $cdom =~ y/.//;
582 next if $ndots < ($cdom =~ /\.[^.][^.]\.[^.][^.]$/ ? 3 : 2); 603 next if $ndots < ($cdom =~ /\.[^.][^.]\.[^.][^.]$/ ? 3 : 2);
604
605 $cdom = substr $cdom, 1; # remove initial .
583 } else { 606 } else {
584 $cdom = $host; 607 $cdom = $host;
585 } 608 }
586 609
587 # store it 610 # store it
588 $jar->{version} = 1; 611 $jar->{version} = 2;
589 $jar->{lc $cdom}{$cpath}{$name} = \%kv; 612 $jar->{lc $cdom}{$cpath}{$name} = \%kv;
590 613
591 redo if /\G\s*,/gc; 614 redo if /\G\s*,/gc;
592 } 615 }
593} 616}
683 706
684 $cb->(undef, $hdr); 707 $cb->(undef, $hdr);
685 () 708 ()
686} 709}
687 710
711our %IDEMPOTENT = (
712 DELETE => 1,
713 GET => 1,
714 HEAD => 1,
715 OPTIONS => 1,
716 PUT => 1,
717 TRACE => 1,
718
719 ACL => 1,
720 "BASELINE-CONTROL" => 1,
721 BIND => 1,
722 CHECKIN => 1,
723 CHECKOUT => 1,
724 COPY => 1,
725 LABEL => 1,
726 LINK => 1,
727 MERGE => 1,
728 MKACTIVITY => 1,
729 MKCALENDAR => 1,
730 MKCOL => 1,
731 MKREDIRECTREF => 1,
732 MKWORKSPACE => 1,
733 MOVE => 1,
734 ORDERPATCH => 1,
735 PROPFIND => 1,
736 PROPPATCH => 1,
737 REBIND => 1,
738 REPORT => 1,
739 SEARCH => 1,
740 UNBIND => 1,
741 UNCHECKOUT => 1,
742 UNLINK => 1,
743 UNLOCK => 1,
744 UPDATE => 1,
745 UPDATEREDIRECTREF => 1,
746 "VERSION-CONTROL" => 1,
747);
748
688sub http_request($$@) { 749sub http_request($$@) {
689 my $cb = pop; 750 my $cb = pop;
690 my ($method, $url, %arg) = @_; 751 my ($method, $url, %arg) = @_;
691 752
692 my %hdr; 753 my %hdr;
709 my $recurse = exists $arg{recurse} ? delete $arg{recurse} : $MAX_RECURSE; 770 my $recurse = exists $arg{recurse} ? delete $arg{recurse} : $MAX_RECURSE;
710 771
711 return $cb->(undef, { @pseudo, Status => 599, Reason => "Too many redirections" }) 772 return $cb->(undef, { @pseudo, Status => 599, Reason => "Too many redirections" })
712 if $recurse < 0; 773 if $recurse < 0;
713 774
714 my $proxy = $arg{proxy} || $PROXY; 775 my $proxy = exists $arg{proxy} ? $arg{proxy} : $PROXY;
715 my $timeout = $arg{timeout} || $TIMEOUT; 776 my $timeout = $arg{timeout} || $TIMEOUT;
716 777
717 my ($uscheme, $uauthority, $upath, $query, undef) = # ignore fragment 778 my ($uscheme, $uauthority, $upath, $query, undef) = # ignore fragment
718 $url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:(\?[^#]*))?(?:#(.*))?|; 779 $url =~ m|^([^:]+):(?://([^/?#]*))?([^?#]*)(?:(\?[^#]*))?(?:#(.*))?$|;
719 780
720 $uscheme = lc $uscheme; 781 $uscheme = lc $uscheme;
721 782
722 my $uport = $uscheme eq "http" ? 80 783 my $uport = $uscheme eq "http" ? 80
723 : $uscheme eq "https" ? 443 784 : $uscheme eq "https" ? 443
724 : return $cb->(undef, { @pseudo, Status => 599, Reason => "Only http and https URL schemes supported" }); 785 : return $cb->(undef, { @pseudo, Status => 599, Reason => "Only http and https URL schemes supported" });
725 786
726 $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x 787 $uauthority =~ /^(?: .*\@ )? ([^\@]+?) (?: : (\d+) )?$/x
727 or return $cb->(undef, { @pseudo, Status => 599, Reason => "Unparsable URL" }); 788 or return $cb->(undef, { @pseudo, Status => 599, Reason => "Unparsable URL" });
728 789
729 my $uhost = lc $1; 790 my $uhost = lc $1;
730 $uport = $2 if defined $2; 791 $uport = $2 if defined $2;
731 792
767 $hdr{"user-agent"} = $USERAGENT unless exists $hdr{"user-agent"}; 828 $hdr{"user-agent"} = $USERAGENT unless exists $hdr{"user-agent"};
768 829
769 $hdr{"content-length"} = length $arg{body} 830 $hdr{"content-length"} = length $arg{body}
770 if length $arg{body} || $method ne "GET"; 831 if length $arg{body} || $method ne "GET";
771 832
772 my $idempotent = $method =~ /^(?:GET|HEAD|PUT|DELETE|OPTIONS|TRACE)$/; 833 my $idempotent = $IDEMPOTENT{$method};
773 834
774 # default value for keepalive is true iff the request is for an idempotent method 835 # default value for keepalive is true iff the request is for an idempotent method
775 my $keepalive = exists $arg{keepalive} ? !!$arg{keepalive} : $idempotent; 836 my $persistent = exists $arg{persistent} ? !!$arg{persistent} : $idempotent;
776 my $keepalive10 = exists $arg{keepalive10} ? $arg{keepalive10} : !$proxy; 837 my $keepalive = exists $arg{keepalive} ? !!$arg{keepalive} : !$proxy;
777 my $keptalive; # true if this is actually a recycled connection 838 my $was_persistent; # true if this is actually a recycled connection
778 839
779 # the key to use in the keepalive cache 840 # the key to use in the keepalive cache
780 my $ka_key = "$uhost\x00$arg{sessionid}"; 841 my $ka_key = "$uscheme\x00$uhost\x00$uport\x00$arg{sessionid}";
781 842
782 $hdr{connection} = ($keepalive ? $keepalive10 ? "keep-alive " : "" : "close ") . "Te"; #1.1 843 $hdr{connection} = ($persistent ? $keepalive ? "keep-alive, " : "" : "close, ") . "Te"; #1.1
783 $hdr{te} = "trailers" unless exists $hdr{te}; #1.1 844 $hdr{te} = "trailers" unless exists $hdr{te}; #1.1
784 845
785 my %state = (connect_guard => 1); 846 my %state = (connect_guard => 1);
786 847
787 my $ae_error = 595; # connecting 848 my $ae_error = 595; # connecting
797 # send request 858 # send request
798 $hdl->push_write ( 859 $hdl->push_write (
799 "$method $rpath HTTP/1.1\015\012" 860 "$method $rpath HTTP/1.1\015\012"
800 . (join "", map "\u$_: $hdr{$_}\015\012", grep defined $hdr{$_}, keys %hdr) 861 . (join "", map "\u$_: $hdr{$_}\015\012", grep defined $hdr{$_}, keys %hdr)
801 . "\015\012" 862 . "\015\012"
802 . (delete $arg{body}) 863 . $arg{body}
803 ); 864 );
804 865
805 # return if error occured during push_write() 866 # return if error occurred during push_write()
806 return unless %state; 867 return unless %state;
807 868
808 # reduce memory usage, save a kitten, also re-use it for the response headers. 869 # reduce memory usage, save a kitten, also re-use it for the response headers.
809 %hdr = (); 870 %hdr = ();
810 871
837 898
838 %hdr = (%$hdr, @pseudo); 899 %hdr = (%$hdr, @pseudo);
839 } 900 }
840 901
841 # redirect handling 902 # redirect handling
842 # microsoft and other shitheads don't give a shit for following standards, 903 # relative uri handling forced by microsoft and other shitheads.
843 # try to support some common forms of broken Location headers. 904 # we give our best and fall back to URI if available.
844 if ($hdr{location} !~ /^(?: $ | [^:\/?\#]+ : )/x) { 905 if (exists $hdr{location}) {
906 my $loc = $hdr{location};
907
908 if ($loc =~ m%^//%) { # //
909 $loc = "$uscheme:$loc";
910
911 } elsif ($loc eq "") {
912 $loc = $url;
913
914 } elsif ($loc !~ /^(?: $ | [^:\/?\#]+ : )/x) { # anything "simple"
845 $hdr{location} =~ s/^\.\/+//; 915 $loc =~ s/^\.\/+//;
846 916
847 my $url = "$rscheme://$uhost:$uport"; 917 if ($loc !~ m%^[.?#]%) {
918 my $prefix = "$uscheme://$uauthority";
848 919
849 unless ($hdr{location} =~ s/^\///) { 920 unless ($loc =~ s/^\///) {
850 $url .= $upath; 921 $prefix .= $upath;
851 $url =~ s/\/[^\/]*$//; 922 $prefix =~ s/\/[^\/]*$//;
923 }
924
925 $loc = "$prefix/$loc";
926
927 } elsif (eval { require URI }) { # uri
928 $loc = URI->new_abs ($loc, $url)->as_string;
929
930 } else {
931 return _error %state, $cb, { @pseudo, Status => 599, Reason => "Cannot parse Location (URI module missing)" };
932 #$hdr{Status} = 599;
933 #$hdr{Reason} = "Unparsable Redirect (URI module missing)";
934 #$recurse = 0;
935 }
852 } 936 }
853 937
854 $hdr{location} = "$url/$hdr{location}"; 938 $hdr{location} = $loc;
855 } 939 }
856 940
857 my $redirect; 941 my $redirect;
858 942
859 if ($recurse) { 943 if ($recurse) {
861 945
862 # industry standard is to redirect POST as GET for 946 # industry standard is to redirect POST as GET for
863 # 301, 302 and 303, in contrast to HTTP/1.0 and 1.1. 947 # 301, 302 and 303, in contrast to HTTP/1.0 and 1.1.
864 # also, the UA should ask the user for 301 and 307 and POST, 948 # also, the UA should ask the user for 301 and 307 and POST,
865 # industry standard seems to be to simply follow. 949 # industry standard seems to be to simply follow.
866 # we go with the industry standard. 950 # we go with the industry standard. 308 is defined
951 # by rfc7538
867 if ($status == 301 or $status == 302 or $status == 303) { 952 if ($status == 301 or $status == 302 or $status == 303) {
953 $redirect = 1;
868 # HTTP/1.1 is unclear on how to mutate the method 954 # HTTP/1.1 is unclear on how to mutate the method
869 $method = "GET" unless $method eq "HEAD"; 955 unless ($method eq "HEAD") {
870 $redirect = 1; 956 $method = "GET";
957 delete $arg{body};
958 }
871 } elsif ($status == 307) { 959 } elsif ($status == 307 or $status == 308) {
872 $redirect = 1; 960 $redirect = 1;
873 } 961 }
874 } 962 }
875 963
876 my $finish = sub { # ($data, $err_status, $err_reason[, $keepalive]) 964 my $finish = sub { # ($data, $err_status, $err_reason[, $persistent])
877 if ($state{handle}) { 965 if ($state{handle}) {
878 # handle keepalive 966 # handle keepalive
879 if ( 967 if (
880 $keepalive 968 $persistent
881 && $_[3] 969 && $_[3]
882 && ($hdr{HTTPVersion} < 1.1 970 && ($hdr{HTTPVersion} < 1.1
883 ? $hdr{connection} =~ /\bkeep-?alive\b/i 971 ? $hdr{connection} =~ /\bkeep-?alive\b/i
884 : $hdr{connection} !~ /\bclose\b/i) 972 : $hdr{connection} !~ /\bclose\b/i)
885 ) { 973 ) {
904 992
905 if ($redirect && exists $hdr{location}) { 993 if ($redirect && exists $hdr{location}) {
906 # we ignore any errors, as it is very common to receive 994 # we ignore any errors, as it is very common to receive
907 # Content-Length != 0 but no actual body 995 # Content-Length != 0 but no actual body
908 # we also access %hdr, as $_[1] might be an erro 996 # we also access %hdr, as $_[1] might be an erro
997 $state{recurse} =
909 http_request ( 998 http_request (
910 $method => $hdr{location}, 999 $method => $hdr{location},
911 %arg, 1000 %arg,
912 recurse => $recurse - 1, 1001 recurse => $recurse - 1,
913 Redirect => [$_[0], \%hdr], 1002 Redirect => [$_[0], \%hdr],
1003 sub {
1004 %state = ();
914 $cb 1005 &$cb
1006 },
915 ); 1007 );
916 } else { 1008 } else {
917 $cb->($_[0], \%hdr); 1009 $cb->($_[0], \%hdr);
918 } 1010 }
919 }; 1011 };
920 1012
948 $finish->(delete $state{handle}); 1040 $finish->(delete $state{handle});
949 1041
950 } elsif ($chunked) { 1042 } elsif ($chunked) {
951 my $cl = 0; 1043 my $cl = 0;
952 my $body = ""; 1044 my $body = "";
953 my $on_body = $arg{on_body} || sub { $body .= shift; 1 }; 1045 my $on_body = (!$redirect && $arg{on_body}) || sub { $body .= shift; 1 };
954 1046
955 $state{read_chunk} = sub { 1047 $state{read_chunk} = sub {
956 $_[1] =~ /^([0-9a-fA-F]+)/ 1048 $_[1] =~ /^([0-9a-fA-F]+)/
957 or $finish->(undef, $ae_error => "Garbled chunked transfer encoding"); 1049 or return $finish->(undef, $ae_error => "Garbled chunked transfer encoding");
958 1050
959 my $len = hex $1; 1051 my $len = hex $1;
960 1052
961 if ($len) { 1053 if ($len) {
962 $cl += $len; 1054 $cl += $len;
991 } 1083 }
992 }; 1084 };
993 1085
994 $_[0]->push_read (line => $state{read_chunk}); 1086 $_[0]->push_read (line => $state{read_chunk});
995 1087
996 } elsif ($arg{on_body}) { 1088 } elsif (!$redirect && $arg{on_body}) {
997 if (defined $len) { 1089 if (defined $len) {
998 $_[0]->on_read (sub { 1090 $_[0]->on_read (sub {
999 $len -= length $_[0]{rbuf}; 1091 $len -= length $_[0]{rbuf};
1000 1092
1001 $arg{on_body}(delete $_[0]{rbuf}, \%hdr) 1093 $arg{on_body}(delete $_[0]{rbuf}, \%hdr)
1032 } 1124 }
1033 }; 1125 };
1034 1126
1035 # if keepalive is enabled, then the server closing the connection 1127 # if keepalive is enabled, then the server closing the connection
1036 # before a response can happen legally - we retry on idempotent methods. 1128 # before a response can happen legally - we retry on idempotent methods.
1037 if ($keptalive && $idempotent) { 1129 if ($was_persistent && $idempotent) {
1038 my $old_eof = $hdl->{on_eof}; 1130 my $old_eof = $hdl->{on_eof};
1039 $hdl->{on_eof} = sub { 1131 $hdl->{on_eof} = sub {
1040 _destroy_state %state; 1132 _destroy_state %state;
1041 1133
1134 %state = ();
1135 $state{recurse} =
1042 http_request ( 1136 http_request (
1043 $method => $url, 1137 $method => $url,
1044 %arg, 1138 %arg,
1045 keepalive => 0, 1139 recurse => $recurse - 1,
1140 persistent => 0,
1141 sub {
1142 %state = ();
1046 $cb 1143 &$cb
1144 }
1047 ); 1145 );
1048 }; 1146 };
1049 $hdl->on_read (sub { 1147 $hdl->on_read (sub {
1050 return unless %state; 1148 return unless %state;
1051 1149
1052 # as soon as we receive something, a connection close 1150 # as soon as we receive something, a connection close
1060 }; 1158 };
1061 1159
1062 my $prepare_handle = sub { 1160 my $prepare_handle = sub {
1063 my ($hdl) = $state{handle}; 1161 my ($hdl) = $state{handle};
1064 1162
1065 $hdl->timeout ($timeout);
1066 $hdl->on_error (sub { 1163 $hdl->on_error (sub {
1067 _error %state, $cb, { @pseudo, Status => $ae_error, Reason => $_[2] }; 1164 _error %state, $cb, { @pseudo, Status => $ae_error, Reason => $_[2] };
1068 }); 1165 });
1069 $hdl->on_eof (sub { 1166 $hdl->on_eof (sub {
1070 _error %state, $cb, { @pseudo, Status => $ae_error, Reason => "Unexpected end-of-file" }; 1167 _error %state, $cb, { @pseudo, Status => $ae_error, Reason => "Unexpected end-of-file" };
1071 }); 1168 });
1169 $hdl->timeout_reset;
1170 $hdl->timeout ($timeout);
1072 }; 1171 };
1073 1172
1074 # connected to proxy (or origin server) 1173 # connected to proxy (or origin server)
1075 my $connect_cb = sub { 1174 my $connect_cb = sub {
1076 my $fh = shift 1175 my $fh = shift
1092 1191
1093 # now handle proxy-CONNECT method 1192 # now handle proxy-CONNECT method
1094 if ($proxy && $uscheme eq "https") { 1193 if ($proxy && $uscheme eq "https") {
1095 # oh dear, we have to wrap it into a connect request 1194 # oh dear, we have to wrap it into a connect request
1096 1195
1196 my $auth = exists $hdr{"proxy-authorization"}
1197 ? "proxy-authorization: " . (delete $hdr{"proxy-authorization"}) . "\015\012"
1198 : "";
1199
1097 # maybe re-use $uauthority with patched port? 1200 # maybe re-use $uauthority with patched port?
1098 $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012\015\012"); 1201 $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012$auth\015\012");
1099 $state{handle}->push_read (line => $qr_nlnl, sub { 1202 $state{handle}->push_read (line => $qr_nlnl, sub {
1100 $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix 1203 $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix
1101 or return _error %state, $cb, { @pseudo, Status => 599, Reason => "Invalid proxy connect response ($_[1])" }; 1204 or return _error %state, $cb, { @pseudo, Status => 599, Reason => "Invalid proxy connect response ($_[1])" };
1102 1205
1103 if ($2 == 200) { 1206 if ($2 == 200) {
1106 } else { 1209 } else {
1107 _error %state, $cb, { @pseudo, Status => $2, Reason => $3 }; 1210 _error %state, $cb, { @pseudo, Status => $2, Reason => $3 };
1108 } 1211 }
1109 }); 1212 });
1110 } else { 1213 } else {
1214 delete $hdr{"proxy-authorization"} unless $proxy;
1215
1111 $handle_actual_request->(); 1216 $handle_actual_request->();
1112 } 1217 }
1113 }; 1218 };
1114 1219
1115 _get_slot $uhost, sub { 1220 _get_slot $uhost, sub {
1117 1222
1118 return unless $state{connect_guard}; 1223 return unless $state{connect_guard};
1119 1224
1120 # try to use an existing keepalive connection, but only if we, ourselves, plan 1225 # try to use an existing keepalive connection, but only if we, ourselves, plan
1121 # on a keepalive request (in theory, this should be a separate config option). 1226 # on a keepalive request (in theory, this should be a separate config option).
1122 if ($keepalive && $KA_CACHE{$ka_key}) { 1227 if ($persistent && $KA_CACHE{$ka_key}) {
1123 $keptalive = 1; 1228 $was_persistent = 1;
1229
1124 $state{handle} = ka_fetch $ka_key; 1230 $state{handle} = ka_fetch $ka_key;
1231# $state{handle}->destroyed
1232# and die "AnyEvent::HTTP: unexpectedly got a destructed handle (1), please report.";#d#
1125 $prepare_handle->(); 1233 $prepare_handle->();
1234# $state{handle}->destroyed
1235# and die "AnyEvent::HTTP: unexpectedly got a destructed handle (2), please report.";#d#
1126 $handle_actual_request->(); 1236 $handle_actual_request->();
1127 1237
1128 } else { 1238 } else {
1129 my $tcp_connect = $arg{tcp_connect} 1239 my $tcp_connect = $arg{tcp_connect}
1130 || do { require AnyEvent::Socket; \&AnyEvent::Socket::tcp_connect }; 1240 || do { require AnyEvent::Socket; \&AnyEvent::Socket::tcp_connect };
1172Sets the default proxy server to use. The proxy-url must begin with a 1282Sets the default proxy server to use. The proxy-url must begin with a
1173string of the form C<http://host:port>, croaks otherwise. 1283string of the form C<http://host:port>, croaks otherwise.
1174 1284
1175To clear an already-set proxy, use C<undef>. 1285To clear an already-set proxy, use C<undef>.
1176 1286
1287When AnyEvent::HTTP is loaded for the first time it will query the
1288default proxy from the operating system, currently by looking at
1289C<$ENV{http_proxy>}.
1290
1177=item AnyEvent::HTTP::cookie_jar_expire $jar[, $session_end] 1291=item AnyEvent::HTTP::cookie_jar_expire $jar[, $session_end]
1178 1292
1179Remove all cookies from the cookie jar that have been expired. If 1293Remove all cookies from the cookie jar that have been expired. If
1180C<$session_end> is given and true, then additionally remove all session 1294C<$session_end> is given and true, then additionally remove all session
1181cookies. 1295cookies.
1182 1296
1183You should call this function (with a true C<$session_end>) before you 1297You should call this function (with a true C<$session_end>) before you
1184save cookies to disk, and you should call this function after loading them 1298save cookies to disk, and you should call this function after loading them
1185again. If you have a long-running program you can additonally call this 1299again. If you have a long-running program you can additionally call this
1186function from time to time. 1300function from time to time.
1187 1301
1188A cookie jar is initially an empty hash-reference that is managed by this 1302A cookie jar is initially an empty hash-reference that is managed by this
1189module. It's format is subject to change, but currently it is like this: 1303module. Its format is subject to change, but currently it is as follows:
1190 1304
1191The key C<version> has to contain C<1>, otherwise the hash gets 1305The key C<version> has to contain C<2>, otherwise the hash gets
1192emptied. All other keys are hostnames or IP addresses pointing to 1306cleared. All other keys are hostnames or IP addresses pointing to
1193hash-references. The key for these inner hash references is the 1307hash-references. The key for these inner hash references is the
1194server path for which this cookie is meant, and the values are again 1308server path for which this cookie is meant, and the values are again
1195hash-references. The keys of those hash-references is the cookie name, and 1309hash-references. Each key of those hash-references is a cookie name, and
1196the value, you guessed it, is another hash-reference, this time with the 1310the value, you guessed it, is another hash-reference, this time with the
1197key-value pairs from the cookie, except for C<expires> and C<max-age>, 1311key-value pairs from the cookie, except for C<expires> and C<max-age>,
1198which have been replaced by a C<_expires> key that contains the cookie 1312which have been replaced by a C<_expires> key that contains the cookie
1199expiry timestamp. 1313expiry timestamp. Session cookies are indicated by not having an
1314C<_expires> key.
1200 1315
1201Here is an example of a cookie jar with a single cookie, so you have a 1316Here is an example of a cookie jar with a single cookie, so you have a
1202chance of understanding the above paragraph: 1317chance of understanding the above paragraph:
1203 1318
1204 { 1319 {
1205 version => 1, 1320 version => 2,
1206 "10.0.0.1" => { 1321 "10.0.0.1" => {
1207 "/" => { 1322 "/" => {
1208 "mythweb_id" => { 1323 "mythweb_id" => {
1209 _expires => 1293917923, 1324 _expires => 1293917923,
1210 value => "ooRung9dThee3ooyXooM1Ohm", 1325 value => "ooRung9dThee3ooyXooM1Ohm",
1228 1343
1229The default value for the C<recurse> request parameter (default: C<10>). 1344The default value for the C<recurse> request parameter (default: C<10>).
1230 1345
1231=item $AnyEvent::HTTP::TIMEOUT 1346=item $AnyEvent::HTTP::TIMEOUT
1232 1347
1233The default timeout for conenction operations (default: C<300>). 1348The default timeout for connection operations (default: C<300>).
1234 1349
1235=item $AnyEvent::HTTP::USERAGENT 1350=item $AnyEvent::HTTP::USERAGENT
1236 1351
1237The default value for the C<User-Agent> header (the default is 1352The default value for the C<User-Agent> header (the default is
1238C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>). 1353C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>).
1239 1354
1240=item $AnyEvent::HTTP::MAX_PER_HOST 1355=item $AnyEvent::HTTP::MAX_PER_HOST
1241 1356
1242The maximum number of concurrent connections to the same host (identified 1357The maximum number of concurrent connections to the same host (identified
1243by the hostname). If the limit is exceeded, then the additional requests 1358by the hostname). If the limit is exceeded, then additional requests
1244are queued until previous connections are closed. Both persistent and 1359are queued until previous connections are closed. Both persistent and
1245non-persistent connections are counted in this limit. 1360non-persistent connections are counted in this limit.
1246 1361
1247The default value for this is C<4>, and it is highly advisable to not 1362The default value for this is C<4>, and it is highly advisable to not
1248increase it much. 1363increase it much.
1249 1364
1250For comparison: the RFC's recommend 4 non-persistent or 2 persistent 1365For comparison: the RFC's recommend 4 non-persistent or 2 persistent
1251connections, older browsers used 2, newers (such as firefox 3) typically 1366connections, older browsers used 2, newer ones (such as firefox 3)
1252use 6, and Opera uses 8 because like, they have the fastest browser and 1367typically use 6, and Opera uses 8 because like, they have the fastest
1253give a shit for everybody else on the planet. 1368browser and give a shit for everybody else on the planet.
1254 1369
1255=item $AnyEvent::HTTP::PERSISTENT_TIMEOUT 1370=item $AnyEvent::HTTP::PERSISTENT_TIMEOUT
1256 1371
1257The time after which idle persistent conenctions get closed by 1372The time after which idle persistent connections get closed by
1258AnyEvent::HTTP (default: C<3>). 1373AnyEvent::HTTP (default: C<3>).
1259 1374
1260=item $AnyEvent::HTTP::ACTIVE 1375=item $AnyEvent::HTTP::ACTIVE
1261 1376
1262The number of active connections. This is not the number of currently 1377The number of active connections. This is not the number of currently
1303 # other formats fail in the loop below 1418 # other formats fail in the loop below
1304 1419
1305 for (0..11) { 1420 for (0..11) {
1306 if ($m eq $month[$_]) { 1421 if ($m eq $month[$_]) {
1307 require Time::Local; 1422 require Time::Local;
1308 return Time::Local::timegm ($S, $M, $H, $d, $_, $y); 1423 return eval { Time::Local::timegm ($S, $M, $H, $d, $_, $y) };
1309 } 1424 }
1310 } 1425 }
1311 1426
1312 undef 1427 undef
1313} 1428}
1325# initialise proxy from environment 1440# initialise proxy from environment
1326eval { 1441eval {
1327 set_proxy $ENV{http_proxy}; 1442 set_proxy $ENV{http_proxy};
1328}; 1443};
1329 1444
1445=head2 SHOWCASE
1446
1447This section contains some more elaborate "real-world" examples or code
1448snippets.
1449
1450=head2 HTTP/1.1 FILE DOWNLOAD
1451
1452Downloading files with HTTP can be quite tricky, especially when something
1453goes wrong and you want to resume.
1454
1455Here is a function that initiates and resumes a download. It uses the
1456last modified time to check for file content changes, and works with many
1457HTTP/1.0 servers as well, and usually falls back to a complete re-download
1458on older servers.
1459
1460It calls the completion callback with either C<undef>, which means a
1461nonretryable error occurred, C<0> when the download was partial and should
1462be retried, and C<1> if it was successful.
1463
1464 use AnyEvent::HTTP;
1465
1466 sub download($$$) {
1467 my ($url, $file, $cb) = @_;
1468
1469 open my $fh, "+<", $file
1470 or die "$file: $!";
1471
1472 my %hdr;
1473 my $ofs = 0;
1474
1475 if (stat $fh and -s _) {
1476 $ofs = -s _;
1477 warn "-s is ", $ofs;
1478 $hdr{"if-unmodified-since"} = AnyEvent::HTTP::format_date +(stat _)[9];
1479 $hdr{"range"} = "bytes=$ofs-";
1480 }
1481
1482 http_get $url,
1483 headers => \%hdr,
1484 on_header => sub {
1485 my ($hdr) = @_;
1486
1487 if ($hdr->{Status} == 200 && $ofs) {
1488 # resume failed
1489 truncate $fh, $ofs = 0;
1490 }
1491
1492 sysseek $fh, $ofs, 0;
1493
1494 1
1495 },
1496 on_body => sub {
1497 my ($data, $hdr) = @_;
1498
1499 if ($hdr->{Status} =~ /^2/) {
1500 length $data == syswrite $fh, $data
1501 or return; # abort on write errors
1502 }
1503
1504 1
1505 },
1506 sub {
1507 my (undef, $hdr) = @_;
1508
1509 my $status = $hdr->{Status};
1510
1511 if (my $time = AnyEvent::HTTP::parse_date $hdr->{"last-modified"}) {
1512 utime $time, $time, $fh;
1513 }
1514
1515 if ($status == 200 || $status == 206 || $status == 416) {
1516 # download ok || resume ok || file already fully downloaded
1517 $cb->(1, $hdr);
1518
1519 } elsif ($status == 412) {
1520 # file has changed while resuming, delete and retry
1521 unlink $file;
1522 $cb->(0, $hdr);
1523
1524 } elsif ($status == 500 or $status == 503 or $status =~ /^59/) {
1525 # retry later
1526 $cb->(0, $hdr);
1527
1528 } else {
1529 $cb->(undef, $hdr);
1530 }
1531 }
1532 ;
1533 }
1534
1535 download "http://server/somelargefile", "/tmp/somelargefile", sub {
1536 if ($_[0]) {
1537 print "OK!\n";
1538 } elsif (defined $_[0]) {
1539 print "please retry later\n";
1540 } else {
1541 print "ERROR\n";
1542 }
1543 };
1544
1330=head2 SOCKS PROXIES 1545=head3 SOCKS PROXIES
1331 1546
1332Socks proxies are not directly supported by AnyEvent::HTTP. You can 1547Socks proxies are not directly supported by AnyEvent::HTTP. You can
1333compile your perl to support socks, or use an external program such as 1548compile your perl to support socks, or use an external program such as
1334F<socksify> (dante) or F<tsocks> to make your program use a socks proxy 1549F<socksify> (dante) or F<tsocks> to make your program use a socks proxy
1335transparently. 1550transparently.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines