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.102 by root, Sat Feb 19 06:46:14 2011 UTC vs.
Revision 1.132 by root, Thu Aug 30 17:05:45 2018 UTC

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.04'; 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.
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.
188 196
189If not specified, then the default proxy is used (see 197If not specified, then the default proxy is used (see
190C<AnyEvent::HTTP::set_proxy>). 198C<AnyEvent::HTTP::set_proxy>).
199
200Currently, if your proxy requires authorization, you have to specify an
201appropriate "Proxy-Authorization" header in every request.
191 202
192=item body => $string 203=item body => $string
193 204
194The 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
195this module might offer more options). 206this module might offer more options).
239context) - only connections using the same unique ID will be reused. 250context) - only connections using the same unique ID will be reused.
240 251
241=item on_prepare => $callback->($fh) 252=item on_prepare => $callback->($fh)
242 253
243In 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
244connect (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
245overrides the prepare callback passed to C<AnyEvent::Socket::tcp_connect> 256overrides the prepare callback passed to C<AnyEvent::Socket::tcp_connect>
246and 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
247timeout). See the description for the C<$prepare_cb> argument of 258timeout). See the description for the C<$prepare_cb> argument of
248C<AnyEvent::Socket::tcp_connect> for details. 259C<AnyEvent::Socket::tcp_connect> for details.
249 260
381 392
382Example: do a HTTP HEAD request on https://www.google.com/, use a 393Example: do a HTTP HEAD request on https://www.google.com/, use a
383timeout of 30 seconds. 394timeout of 30 seconds.
384 395
385 http_request 396 http_request
386 GET => "https://www.google.com", 397 HEAD => "https://www.google.com",
387 headers => { "user-agent" => "MySearchClient 1.0" }, 398 headers => { "user-agent" => "MySearchClient 1.0" },
388 timeout => 30, 399 timeout => 30,
389 sub { 400 sub {
390 my ($body, $hdr) = @_; 401 my ($body, $hdr) = @_;
391 use Data::Dumper; 402 use Data::Dumper;
443 454
444# expire cookies 455# expire cookies
445sub cookie_jar_expire($;$) { 456sub cookie_jar_expire($;$) {
446 my ($jar, $session_end) = @_; 457 my ($jar, $session_end) = @_;
447 458
448 %$jar = () if $jar->{version} != 1; 459 %$jar = () if $jar->{version} != 2;
449 460
450 my $anow = AE::now; 461 my $anow = AE::now;
451 462
452 while (my ($chost, $paths) = each %$jar) { 463 while (my ($chost, $paths) = each %$jar) {
453 next unless ref $paths; 464 next unless ref $paths;
473 484
474# extract cookies from jar 485# extract cookies from jar
475sub cookie_jar_extract($$$$) { 486sub cookie_jar_extract($$$$) {
476 my ($jar, $scheme, $host, $path) = @_; 487 my ($jar, $scheme, $host, $path) = @_;
477 488
478 %$jar = () if $jar->{version} != 1; 489 %$jar = () if $jar->{version} != 2;
490
491 $host = AnyEvent::Util::idn_to_ascii $host
492 if $host =~ /[^\x00-\x7f]/;
479 493
480 my @cookies; 494 my @cookies;
481 495
482 while (my ($chost, $paths) = each %$jar) { 496 while (my ($chost, $paths) = each %$jar) {
483 next unless ref $paths; 497 next unless ref $paths;
484 498
485 if ($chost =~ /^\./) { 499 # exact match or suffix including . match
486 next unless $chost eq substr $host, -length $chost; 500 $chost eq $host or ".$chost" eq substr $host, -1 - length $chost
487 } elsif ($chost =~ /\./) {
488 next unless $chost eq $host;
489 } else {
490 next; 501 or next;
491 }
492 502
493 while (my ($cpath, $cookies) = each %$paths) { 503 while (my ($cpath, $cookies) = each %$paths) {
494 next unless $cpath eq substr $path, 0, length $cpath; 504 next unless $cpath eq substr $path, 0, length $cpath;
495 505
496 while (my ($cookie, $kv) = each %$cookies) { 506 while (my ($cookie, $kv) = each %$cookies) {
517} 527}
518 528
519# parse set_cookie header into jar 529# parse set_cookie header into jar
520sub cookie_jar_set_cookie($$$$) { 530sub cookie_jar_set_cookie($$$$) {
521 my ($jar, $set_cookie, $host, $date) = @_; 531 my ($jar, $set_cookie, $host, $date) = @_;
532
533 %$jar = () if $jar->{version} != 2;
522 534
523 my $anow = int AE::now; 535 my $anow = int AE::now;
524 my $snow; # server-now 536 my $snow; # server-now
525 537
526 for ($set_cookie) { 538 for ($set_cookie) {
572 584
573 my $cdom; 585 my $cdom;
574 my $cpath = (delete $kv{path}) || "/"; 586 my $cpath = (delete $kv{path}) || "/";
575 587
576 if (exists $kv{domain}) { 588 if (exists $kv{domain}) {
577 $cdom = delete $kv{domain}; 589 $cdom = $kv{domain};
578 590
579 $cdom =~ s/^\.?/./; # make sure it starts with a "." 591 $cdom =~ s/^\.?/./; # make sure it starts with a "."
580 592
581 next if $cdom =~ /\.$/; 593 next if $cdom =~ /\.$/;
582 594
583 # this is not rfc-like and not netscape-like. go figure. 595 # this is not rfc-like and not netscape-like. go figure.
584 my $ndots = $cdom =~ y/.//; 596 my $ndots = $cdom =~ y/.//;
585 next if $ndots < ($cdom =~ /\.[^.][^.]\.[^.][^.]$/ ? 3 : 2); 597 next if $ndots < ($cdom =~ /\.[^.][^.]\.[^.][^.]$/ ? 3 : 2);
598
599 $cdom = substr $cdom, 1; # remove initial .
586 } else { 600 } else {
587 $cdom = $host; 601 $cdom = $host;
588 } 602 }
589 603
590 # store it 604 # store it
591 $jar->{version} = 1; 605 $jar->{version} = 2;
592 $jar->{lc $cdom}{$cpath}{$name} = \%kv; 606 $jar->{lc $cdom}{$cpath}{$name} = \%kv;
593 607
594 redo if /\G\s*,/gc; 608 redo if /\G\s*,/gc;
595 } 609 }
596} 610}
686 700
687 $cb->(undef, $hdr); 701 $cb->(undef, $hdr);
688 () 702 ()
689} 703}
690 704
705our %IDEMPOTENT = (
706 DELETE => 1,
707 GET => 1,
708 HEAD => 1,
709 OPTIONS => 1,
710 PUT => 1,
711 TRACE => 1,
712
713 ACL => 1,
714 "BASELINE-CONTROL" => 1,
715 BIND => 1,
716 CHECKIN => 1,
717 CHECKOUT => 1,
718 COPY => 1,
719 LABEL => 1,
720 LINK => 1,
721 MERGE => 1,
722 MKACTIVITY => 1,
723 MKCALENDAR => 1,
724 MKCOL => 1,
725 MKREDIRECTREF => 1,
726 MKWORKSPACE => 1,
727 MOVE => 1,
728 ORDERPATCH => 1,
729 PROPFIND => 1,
730 PROPPATCH => 1,
731 REBIND => 1,
732 REPORT => 1,
733 SEARCH => 1,
734 UNBIND => 1,
735 UNCHECKOUT => 1,
736 UNLINK => 1,
737 UNLOCK => 1,
738 UPDATE => 1,
739 UPDATEREDIRECTREF => 1,
740 "VERSION-CONTROL" => 1,
741);
742
691sub http_request($$@) { 743sub http_request($$@) {
692 my $cb = pop; 744 my $cb = pop;
693 my ($method, $url, %arg) = @_; 745 my ($method, $url, %arg) = @_;
694 746
695 my %hdr; 747 my %hdr;
724 776
725 my $uport = $uscheme eq "http" ? 80 777 my $uport = $uscheme eq "http" ? 80
726 : $uscheme eq "https" ? 443 778 : $uscheme eq "https" ? 443
727 : return $cb->(undef, { @pseudo, Status => 599, Reason => "Only http and https URL schemes supported" }); 779 : return $cb->(undef, { @pseudo, Status => 599, Reason => "Only http and https URL schemes supported" });
728 780
729 $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x 781 $uauthority =~ /^(?: .*\@ )? ([^\@]+?) (?: : (\d+) )?$/x
730 or return $cb->(undef, { @pseudo, Status => 599, Reason => "Unparsable URL" }); 782 or return $cb->(undef, { @pseudo, Status => 599, Reason => "Unparsable URL" });
731 783
732 my $uhost = lc $1; 784 my $uhost = lc $1;
733 $uport = $2 if defined $2; 785 $uport = $2 if defined $2;
734 786
770 $hdr{"user-agent"} = $USERAGENT unless exists $hdr{"user-agent"}; 822 $hdr{"user-agent"} = $USERAGENT unless exists $hdr{"user-agent"};
771 823
772 $hdr{"content-length"} = length $arg{body} 824 $hdr{"content-length"} = length $arg{body}
773 if length $arg{body} || $method ne "GET"; 825 if length $arg{body} || $method ne "GET";
774 826
775 my $idempotent = $method =~ /^(?:GET|HEAD|PUT|DELETE|OPTIONS|TRACE)$/; 827 my $idempotent = $IDEMPOTENT{$method};
776 828
777 # default value for keepalive is true iff the request is for an idempotent method 829 # default value for keepalive is true iff the request is for an idempotent method
778 my $keepalive = exists $arg{keepalive} ? !!$arg{keepalive} : $idempotent; 830 my $persistent = exists $arg{persistent} ? !!$arg{persistent} : $idempotent;
779 my $keepalive10 = exists $arg{keepalive10} ? $arg{keepalive10} : !$proxy; 831 my $keepalive = exists $arg{keepalive} ? !!$arg{keepalive} : !$proxy;
780 my $keptalive; # true if this is actually a recycled connection 832 my $was_persistent; # true if this is actually a recycled connection
781 833
782 # the key to use in the keepalive cache 834 # the key to use in the keepalive cache
783 my $ka_key = "$uhost\x00$arg{sessionid}"; 835 my $ka_key = "$uscheme\x00$uhost\x00$uport\x00$arg{sessionid}";
784 836
785 $hdr{connection} = ($keepalive ? $keepalive10 ? "keep-alive " : "" : "close ") . "Te"; #1.1 837 $hdr{connection} = ($persistent ? $keepalive ? "keep-alive, " : "" : "close, ") . "Te"; #1.1
786 $hdr{te} = "trailers" unless exists $hdr{te}; #1.1 838 $hdr{te} = "trailers" unless exists $hdr{te}; #1.1
787 839
788 my %state = (connect_guard => 1); 840 my %state = (connect_guard => 1);
789 841
790 my $ae_error = 595; # connecting 842 my $ae_error = 595; # connecting
800 # send request 852 # send request
801 $hdl->push_write ( 853 $hdl->push_write (
802 "$method $rpath HTTP/1.1\015\012" 854 "$method $rpath HTTP/1.1\015\012"
803 . (join "", map "\u$_: $hdr{$_}\015\012", grep defined $hdr{$_}, keys %hdr) 855 . (join "", map "\u$_: $hdr{$_}\015\012", grep defined $hdr{$_}, keys %hdr)
804 . "\015\012" 856 . "\015\012"
805 . (delete $arg{body}) 857 . $arg{body}
806 ); 858 );
807 859
808 # return if error occured during push_write() 860 # return if error occurred during push_write()
809 return unless %state; 861 return unless %state;
810 862
811 # reduce memory usage, save a kitten, also re-use it for the response headers. 863 # reduce memory usage, save a kitten, also re-use it for the response headers.
812 %hdr = (); 864 %hdr = ();
813 865
840 892
841 %hdr = (%$hdr, @pseudo); 893 %hdr = (%$hdr, @pseudo);
842 } 894 }
843 895
844 # redirect handling 896 # redirect handling
845 # microsoft and other shitheads don't give a shit for following standards, 897 # relative uri handling forced by microsoft and other shitheads.
846 # try to support some common forms of broken Location headers. 898 # we give our best and fall back to URI if available.
847 if ($hdr{location} !~ /^(?: $ | [^:\/?\#]+ : )/x) { 899 if (exists $hdr{location}) {
900 my $loc = $hdr{location};
901
902 if ($loc =~ m%^//%) { # //
903 $loc = "$uscheme:$loc";
904
905 } elsif ($loc eq "") {
906 $loc = $url;
907
908 } elsif ($loc !~ /^(?: $ | [^:\/?\#]+ : )/x) { # anything "simple"
848 $hdr{location} =~ s/^\.\/+//; 909 $loc =~ s/^\.\/+//;
849 910
850 my $url = "$rscheme://$uhost:$uport"; 911 if ($loc !~ m%^[.?#]%) {
912 my $prefix = "$uscheme://$uauthority";
851 913
852 unless ($hdr{location} =~ s/^\///) { 914 unless ($loc =~ s/^\///) {
853 $url .= $upath; 915 $prefix .= $upath;
854 $url =~ s/\/[^\/]*$//; 916 $prefix =~ s/\/[^\/]*$//;
917 }
918
919 $loc = "$prefix/$loc";
920
921 } elsif (eval { require URI }) { # uri
922 $loc = URI->new_abs ($loc, $url)->as_string;
923
924 } else {
925 return _error %state, $cb, { @pseudo, Status => 599, Reason => "Cannot parse Location (URI module missing)" };
926 #$hdr{Status} = 599;
927 #$hdr{Reason} = "Unparsable Redirect (URI module missing)";
928 #$recurse = 0;
929 }
855 } 930 }
856 931
857 $hdr{location} = "$url/$hdr{location}"; 932 $hdr{location} = $loc;
858 } 933 }
859 934
860 my $redirect; 935 my $redirect;
861 936
862 if ($recurse) { 937 if ($recurse) {
864 939
865 # industry standard is to redirect POST as GET for 940 # industry standard is to redirect POST as GET for
866 # 301, 302 and 303, in contrast to HTTP/1.0 and 1.1. 941 # 301, 302 and 303, in contrast to HTTP/1.0 and 1.1.
867 # also, the UA should ask the user for 301 and 307 and POST, 942 # also, the UA should ask the user for 301 and 307 and POST,
868 # industry standard seems to be to simply follow. 943 # industry standard seems to be to simply follow.
869 # we go with the industry standard. 944 # we go with the industry standard. 308 is defined
945 # by rfc7538
870 if ($status == 301 or $status == 302 or $status == 303) { 946 if ($status == 301 or $status == 302 or $status == 303) {
947 $redirect = 1;
871 # HTTP/1.1 is unclear on how to mutate the method 948 # HTTP/1.1 is unclear on how to mutate the method
872 $method = "GET" unless $method eq "HEAD"; 949 unless ($method eq "HEAD") {
873 $redirect = 1; 950 $method = "GET";
951 delete $arg{body};
952 }
874 } elsif ($status == 307) { 953 } elsif ($status == 307 or $status == 308) {
875 $redirect = 1; 954 $redirect = 1;
876 } 955 }
877 } 956 }
878 957
879 my $finish = sub { # ($data, $err_status, $err_reason[, $keepalive]) 958 my $finish = sub { # ($data, $err_status, $err_reason[, $persistent])
880 if ($state{handle}) { 959 if ($state{handle}) {
881 # handle keepalive 960 # handle keepalive
882 if ( 961 if (
883 $keepalive 962 $persistent
884 && $_[3] 963 && $_[3]
885 && ($hdr{HTTPVersion} < 1.1 964 && ($hdr{HTTPVersion} < 1.1
886 ? $hdr{connection} =~ /\bkeep-?alive\b/i 965 ? $hdr{connection} =~ /\bkeep-?alive\b/i
887 : $hdr{connection} !~ /\bclose\b/i) 966 : $hdr{connection} !~ /\bclose\b/i)
888 ) { 967 ) {
907 986
908 if ($redirect && exists $hdr{location}) { 987 if ($redirect && exists $hdr{location}) {
909 # we ignore any errors, as it is very common to receive 988 # we ignore any errors, as it is very common to receive
910 # Content-Length != 0 but no actual body 989 # Content-Length != 0 but no actual body
911 # we also access %hdr, as $_[1] might be an erro 990 # we also access %hdr, as $_[1] might be an erro
991 $state{recurse} =
912 http_request ( 992 http_request (
913 $method => $hdr{location}, 993 $method => $hdr{location},
914 %arg, 994 %arg,
915 recurse => $recurse - 1, 995 recurse => $recurse - 1,
916 Redirect => [$_[0], \%hdr], 996 Redirect => [$_[0], \%hdr],
997 sub {
998 %state = ();
917 $cb 999 &$cb
1000 },
918 ); 1001 );
919 } else { 1002 } else {
920 $cb->($_[0], \%hdr); 1003 $cb->($_[0], \%hdr);
921 } 1004 }
922 }; 1005 };
923 1006
951 $finish->(delete $state{handle}); 1034 $finish->(delete $state{handle});
952 1035
953 } elsif ($chunked) { 1036 } elsif ($chunked) {
954 my $cl = 0; 1037 my $cl = 0;
955 my $body = ""; 1038 my $body = "";
956 my $on_body = $arg{on_body} || sub { $body .= shift; 1 }; 1039 my $on_body = (!$redirect && $arg{on_body}) || sub { $body .= shift; 1 };
957 1040
958 $state{read_chunk} = sub { 1041 $state{read_chunk} = sub {
959 $_[1] =~ /^([0-9a-fA-F]+)/ 1042 $_[1] =~ /^([0-9a-fA-F]+)/
960 or $finish->(undef, $ae_error => "Garbled chunked transfer encoding"); 1043 or return $finish->(undef, $ae_error => "Garbled chunked transfer encoding");
961 1044
962 my $len = hex $1; 1045 my $len = hex $1;
963 1046
964 if ($len) { 1047 if ($len) {
965 $cl += $len; 1048 $cl += $len;
994 } 1077 }
995 }; 1078 };
996 1079
997 $_[0]->push_read (line => $state{read_chunk}); 1080 $_[0]->push_read (line => $state{read_chunk});
998 1081
999 } elsif ($arg{on_body}) { 1082 } elsif (!$redirect && $arg{on_body}) {
1000 if (defined $len) { 1083 if (defined $len) {
1001 $_[0]->on_read (sub { 1084 $_[0]->on_read (sub {
1002 $len -= length $_[0]{rbuf}; 1085 $len -= length $_[0]{rbuf};
1003 1086
1004 $arg{on_body}(delete $_[0]{rbuf}, \%hdr) 1087 $arg{on_body}(delete $_[0]{rbuf}, \%hdr)
1035 } 1118 }
1036 }; 1119 };
1037 1120
1038 # if keepalive is enabled, then the server closing the connection 1121 # if keepalive is enabled, then the server closing the connection
1039 # before a response can happen legally - we retry on idempotent methods. 1122 # before a response can happen legally - we retry on idempotent methods.
1040 if ($keptalive && $idempotent) { 1123 if ($was_persistent && $idempotent) {
1041 my $old_eof = $hdl->{on_eof}; 1124 my $old_eof = $hdl->{on_eof};
1042 $hdl->{on_eof} = sub { 1125 $hdl->{on_eof} = sub {
1043 _destroy_state %state; 1126 _destroy_state %state;
1044 1127
1128 %state = ();
1129 $state{recurse} =
1045 http_request ( 1130 http_request (
1046 $method => $url, 1131 $method => $url,
1047 %arg, 1132 %arg,
1048 keepalive => 0, 1133 recurse => $recurse - 1,
1134 persistent => 0,
1135 sub {
1136 %state = ();
1049 $cb 1137 &$cb
1138 }
1050 ); 1139 );
1051 }; 1140 };
1052 $hdl->on_read (sub { 1141 $hdl->on_read (sub {
1053 return unless %state; 1142 return unless %state;
1054 1143
1055 # as soon as we receive something, a connection close 1144 # as soon as we receive something, a connection close
1063 }; 1152 };
1064 1153
1065 my $prepare_handle = sub { 1154 my $prepare_handle = sub {
1066 my ($hdl) = $state{handle}; 1155 my ($hdl) = $state{handle};
1067 1156
1068 $hdl->timeout ($timeout);
1069 $hdl->on_error (sub { 1157 $hdl->on_error (sub {
1070 _error %state, $cb, { @pseudo, Status => $ae_error, Reason => $_[2] }; 1158 _error %state, $cb, { @pseudo, Status => $ae_error, Reason => $_[2] };
1071 }); 1159 });
1072 $hdl->on_eof (sub { 1160 $hdl->on_eof (sub {
1073 _error %state, $cb, { @pseudo, Status => $ae_error, Reason => "Unexpected end-of-file" }; 1161 _error %state, $cb, { @pseudo, Status => $ae_error, Reason => "Unexpected end-of-file" };
1074 }); 1162 });
1163 $hdl->timeout_reset;
1164 $hdl->timeout ($timeout);
1075 }; 1165 };
1076 1166
1077 # connected to proxy (or origin server) 1167 # connected to proxy (or origin server)
1078 my $connect_cb = sub { 1168 my $connect_cb = sub {
1079 my $fh = shift 1169 my $fh = shift
1095 1185
1096 # now handle proxy-CONNECT method 1186 # now handle proxy-CONNECT method
1097 if ($proxy && $uscheme eq "https") { 1187 if ($proxy && $uscheme eq "https") {
1098 # oh dear, we have to wrap it into a connect request 1188 # oh dear, we have to wrap it into a connect request
1099 1189
1190 my $auth = exists $hdr{"proxy-authorization"}
1191 ? "proxy-authorization: " . (delete $hdr{"proxy-authorization"}) . "\015\012"
1192 : "";
1193
1100 # maybe re-use $uauthority with patched port? 1194 # maybe re-use $uauthority with patched port?
1101 $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012\015\012"); 1195 $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012$auth\015\012");
1102 $state{handle}->push_read (line => $qr_nlnl, sub { 1196 $state{handle}->push_read (line => $qr_nlnl, sub {
1103 $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix 1197 $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix
1104 or return _error %state, $cb, { @pseudo, Status => 599, Reason => "Invalid proxy connect response ($_[1])" }; 1198 or return _error %state, $cb, { @pseudo, Status => 599, Reason => "Invalid proxy connect response ($_[1])" };
1105 1199
1106 if ($2 == 200) { 1200 if ($2 == 200) {
1109 } else { 1203 } else {
1110 _error %state, $cb, { @pseudo, Status => $2, Reason => $3 }; 1204 _error %state, $cb, { @pseudo, Status => $2, Reason => $3 };
1111 } 1205 }
1112 }); 1206 });
1113 } else { 1207 } else {
1208 delete $hdr{"proxy-authorization"} unless $proxy;
1209
1114 $handle_actual_request->(); 1210 $handle_actual_request->();
1115 } 1211 }
1116 }; 1212 };
1117 1213
1118 _get_slot $uhost, sub { 1214 _get_slot $uhost, sub {
1120 1216
1121 return unless $state{connect_guard}; 1217 return unless $state{connect_guard};
1122 1218
1123 # try to use an existing keepalive connection, but only if we, ourselves, plan 1219 # try to use an existing keepalive connection, but only if we, ourselves, plan
1124 # on a keepalive request (in theory, this should be a separate config option). 1220 # on a keepalive request (in theory, this should be a separate config option).
1125 if ($keepalive && $KA_CACHE{$ka_key}) { 1221 if ($persistent && $KA_CACHE{$ka_key}) {
1126 $keptalive = 1; 1222 $was_persistent = 1;
1223
1127 $state{handle} = ka_fetch $ka_key; 1224 $state{handle} = ka_fetch $ka_key;
1225# $state{handle}->destroyed
1226# and die "AnyEvent::HTTP: unexpectedly got a destructed handle (1), please report.";#d#
1128 $prepare_handle->(); 1227 $prepare_handle->();
1228# $state{handle}->destroyed
1229# and die "AnyEvent::HTTP: unexpectedly got a destructed handle (2), please report.";#d#
1129 $handle_actual_request->(); 1230 $handle_actual_request->();
1130 1231
1131 } else { 1232 } else {
1132 my $tcp_connect = $arg{tcp_connect} 1233 my $tcp_connect = $arg{tcp_connect}
1133 || do { require AnyEvent::Socket; \&AnyEvent::Socket::tcp_connect }; 1234 || do { require AnyEvent::Socket; \&AnyEvent::Socket::tcp_connect };
1175Sets the default proxy server to use. The proxy-url must begin with a 1276Sets the default proxy server to use. The proxy-url must begin with a
1176string of the form C<http://host:port>, croaks otherwise. 1277string of the form C<http://host:port>, croaks otherwise.
1177 1278
1178To clear an already-set proxy, use C<undef>. 1279To clear an already-set proxy, use C<undef>.
1179 1280
1180When AnyEvent::HTTP is laoded for the first time it will query the 1281When AnyEvent::HTTP is loaded for the first time it will query the
1181default proxy from the operating system, currently by looking at 1282default proxy from the operating system, currently by looking at
1182C<$ENV{http_proxy>}. 1283C<$ENV{http_proxy>}.
1183 1284
1184=item AnyEvent::HTTP::cookie_jar_expire $jar[, $session_end] 1285=item AnyEvent::HTTP::cookie_jar_expire $jar[, $session_end]
1185 1286
1187C<$session_end> is given and true, then additionally remove all session 1288C<$session_end> is given and true, then additionally remove all session
1188cookies. 1289cookies.
1189 1290
1190You should call this function (with a true C<$session_end>) before you 1291You should call this function (with a true C<$session_end>) before you
1191save cookies to disk, and you should call this function after loading them 1292save cookies to disk, and you should call this function after loading them
1192again. If you have a long-running program you can additonally call this 1293again. If you have a long-running program you can additionally call this
1193function from time to time. 1294function from time to time.
1194 1295
1195A cookie jar is initially an empty hash-reference that is managed by this 1296A cookie jar is initially an empty hash-reference that is managed by this
1196module. It's format is subject to change, but currently it is like this: 1297module. Its format is subject to change, but currently it is as follows:
1197 1298
1198The key C<version> has to contain C<1>, otherwise the hash gets 1299The key C<version> has to contain C<2>, otherwise the hash gets
1199emptied. All other keys are hostnames or IP addresses pointing to 1300cleared. All other keys are hostnames or IP addresses pointing to
1200hash-references. The key for these inner hash references is the 1301hash-references. The key for these inner hash references is the
1201server path for which this cookie is meant, and the values are again 1302server path for which this cookie is meant, and the values are again
1202hash-references. The keys of those hash-references is the cookie name, and 1303hash-references. Each key of those hash-references is a cookie name, and
1203the value, you guessed it, is another hash-reference, this time with the 1304the value, you guessed it, is another hash-reference, this time with the
1204key-value pairs from the cookie, except for C<expires> and C<max-age>, 1305key-value pairs from the cookie, except for C<expires> and C<max-age>,
1205which have been replaced by a C<_expires> key that contains the cookie 1306which have been replaced by a C<_expires> key that contains the cookie
1206expiry timestamp. 1307expiry timestamp. Session cookies are indicated by not having an
1308C<_expires> key.
1207 1309
1208Here is an example of a cookie jar with a single cookie, so you have a 1310Here is an example of a cookie jar with a single cookie, so you have a
1209chance of understanding the above paragraph: 1311chance of understanding the above paragraph:
1210 1312
1211 { 1313 {
1212 version => 1, 1314 version => 2,
1213 "10.0.0.1" => { 1315 "10.0.0.1" => {
1214 "/" => { 1316 "/" => {
1215 "mythweb_id" => { 1317 "mythweb_id" => {
1216 _expires => 1293917923, 1318 _expires => 1293917923,
1217 value => "ooRung9dThee3ooyXooM1Ohm", 1319 value => "ooRung9dThee3ooyXooM1Ohm",
1235 1337
1236The default value for the C<recurse> request parameter (default: C<10>). 1338The default value for the C<recurse> request parameter (default: C<10>).
1237 1339
1238=item $AnyEvent::HTTP::TIMEOUT 1340=item $AnyEvent::HTTP::TIMEOUT
1239 1341
1240The default timeout for conenction operations (default: C<300>). 1342The default timeout for connection operations (default: C<300>).
1241 1343
1242=item $AnyEvent::HTTP::USERAGENT 1344=item $AnyEvent::HTTP::USERAGENT
1243 1345
1244The default value for the C<User-Agent> header (the default is 1346The default value for the C<User-Agent> header (the default is
1245C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>). 1347C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>).
1246 1348
1247=item $AnyEvent::HTTP::MAX_PER_HOST 1349=item $AnyEvent::HTTP::MAX_PER_HOST
1248 1350
1249The maximum number of concurrent connections to the same host (identified 1351The maximum number of concurrent connections to the same host (identified
1250by the hostname). If the limit is exceeded, then the additional requests 1352by the hostname). If the limit is exceeded, then additional requests
1251are queued until previous connections are closed. Both persistent and 1353are queued until previous connections are closed. Both persistent and
1252non-persistent connections are counted in this limit. 1354non-persistent connections are counted in this limit.
1253 1355
1254The default value for this is C<4>, and it is highly advisable to not 1356The default value for this is C<4>, and it is highly advisable to not
1255increase it much. 1357increase it much.
1256 1358
1257For comparison: the RFC's recommend 4 non-persistent or 2 persistent 1359For comparison: the RFC's recommend 4 non-persistent or 2 persistent
1258connections, older browsers used 2, newers (such as firefox 3) typically 1360connections, older browsers used 2, newer ones (such as firefox 3)
1259use 6, and Opera uses 8 because like, they have the fastest browser and 1361typically use 6, and Opera uses 8 because like, they have the fastest
1260give a shit for everybody else on the planet. 1362browser and give a shit for everybody else on the planet.
1261 1363
1262=item $AnyEvent::HTTP::PERSISTENT_TIMEOUT 1364=item $AnyEvent::HTTP::PERSISTENT_TIMEOUT
1263 1365
1264The time after which idle persistent conenctions get closed by 1366The time after which idle persistent connections get closed by
1265AnyEvent::HTTP (default: C<3>). 1367AnyEvent::HTTP (default: C<3>).
1266 1368
1267=item $AnyEvent::HTTP::ACTIVE 1369=item $AnyEvent::HTTP::ACTIVE
1268 1370
1269The number of active connections. This is not the number of currently 1371The number of active connections. This is not the number of currently
1310 # other formats fail in the loop below 1412 # other formats fail in the loop below
1311 1413
1312 for (0..11) { 1414 for (0..11) {
1313 if ($m eq $month[$_]) { 1415 if ($m eq $month[$_]) {
1314 require Time::Local; 1416 require Time::Local;
1315 return Time::Local::timegm ($S, $M, $H, $d, $_, $y); 1417 return eval { Time::Local::timegm ($S, $M, $H, $d, $_, $y) };
1316 } 1418 }
1317 } 1419 }
1318 1420
1319 undef 1421 undef
1320} 1422}
1334 set_proxy $ENV{http_proxy}; 1436 set_proxy $ENV{http_proxy};
1335}; 1437};
1336 1438
1337=head2 SHOWCASE 1439=head2 SHOWCASE
1338 1440
1339This section contaisn some more elaborate "real-world" examples or code 1441This section contains some more elaborate "real-world" examples or code
1340snippets. 1442snippets.
1341 1443
1342=head2 HTTP/1.1 FILE DOWNLOAD 1444=head2 HTTP/1.1 FILE DOWNLOAD
1343 1445
1344Downloading files with HTTP can be quite tricky, especially when something 1446Downloading files with HTTP can be quite tricky, especially when something
1348last modified time to check for file content changes, and works with many 1450last modified time to check for file content changes, and works with many
1349HTTP/1.0 servers as well, and usually falls back to a complete re-download 1451HTTP/1.0 servers as well, and usually falls back to a complete re-download
1350on older servers. 1452on older servers.
1351 1453
1352It calls the completion callback with either C<undef>, which means a 1454It calls the completion callback with either C<undef>, which means a
1353nonretryable error occured, C<0> when the download was partial and should 1455nonretryable error occurred, C<0> when the download was partial and should
1354be retried, and C<1> if it was successful. 1456be retried, and C<1> if it was successful.
1355 1457
1356 use AnyEvent::HTTP; 1458 use AnyEvent::HTTP;
1357 1459
1358 sub download($$$) { 1460 sub download($$$) {
1362 or die "$file: $!"; 1464 or die "$file: $!";
1363 1465
1364 my %hdr; 1466 my %hdr;
1365 my $ofs = 0; 1467 my $ofs = 0;
1366 1468
1367 warn stat $fh;
1368 warn -s _;
1369 if (stat $fh and -s _) { 1469 if (stat $fh and -s _) {
1370 $ofs = -s _; 1470 $ofs = -s _;
1371 warn "-s is ", $ofs;#d# 1471 warn "-s is ", $ofs;
1372 $hdr{"if-unmodified-since"} = AnyEvent::HTTP::format_date +(stat _)[9]; 1472 $hdr{"if-unmodified-since"} = AnyEvent::HTTP::format_date +(stat _)[9];
1373 $hdr{"range"} = "bytes=$ofs-"; 1473 $hdr{"range"} = "bytes=$ofs-";
1374 } 1474 }
1375 1475
1376 http_get $url, 1476 http_get $url,
1401 my (undef, $hdr) = @_; 1501 my (undef, $hdr) = @_;
1402 1502
1403 my $status = $hdr->{Status}; 1503 my $status = $hdr->{Status};
1404 1504
1405 if (my $time = AnyEvent::HTTP::parse_date $hdr->{"last-modified"}) { 1505 if (my $time = AnyEvent::HTTP::parse_date $hdr->{"last-modified"}) {
1406 utime $fh, $time, $time; 1506 utime $time, $time, $fh;
1407 } 1507 }
1408 1508
1409 if ($status == 200 || $status == 206 || $status == 416) { 1509 if ($status == 200 || $status == 206 || $status == 416) {
1410 # download ok || resume ok || file already fully downloaded 1510 # download ok || resume ok || file already fully downloaded
1411 $cb->(1, $hdr); 1511 $cb->(1, $hdr);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines