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.41 by root, Sun Jul 5 23:50:59 2009 UTC vs.
Revision 1.51 by root, Fri Aug 14 15:21:33 2009 UTC

41use strict; 41use strict;
42no warnings; 42no warnings;
43 43
44use Errno (); 44use Errno ();
45 45
46use AnyEvent 4.452 (); 46use AnyEvent 5.0 ();
47use AnyEvent::Util (); 47use AnyEvent::Util ();
48use AnyEvent::Socket (); 48use AnyEvent::Socket ();
49use AnyEvent::Handle (); 49use AnyEvent::Handle ();
50 50
51use base Exporter::; 51use base Exporter::;
52 52
53our $VERSION = '1.12'; 53our $VERSION = '1.43';
54 54
55our @EXPORT = qw(http_get http_post http_head http_request); 55our @EXPORT = qw(http_get http_post http_head http_request);
56 56
57our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)"; 57our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)";
58our $MAX_RECURSE = 10; 58our $MAX_RECURSE = 10;
59our $MAX_PERSISTENT = 8; 59our $MAX_PERSISTENT = 8;
60our $PERSISTENT_TIMEOUT = 2; 60our $PERSISTENT_TIMEOUT = 2;
61our $TIMEOUT = 300; 61our $TIMEOUT = 300;
62 62
63# changing these is evil 63# changing these is evil
64our $MAX_PERSISTENT_PER_HOST = 2; 64our $MAX_PERSISTENT_PER_HOST = 0;
65our $MAX_PER_HOST = 4; 65our $MAX_PER_HOST = 4;
66 66
67our $PROXY; 67our $PROXY;
68our $ACTIVE = 0; 68our $ACTIVE = 0;
69 69
94When called in void context, nothing is returned. In other contexts, 94When called in void context, nothing is returned. In other contexts,
95C<http_request> returns a "cancellation guard" - you have to keep the 95C<http_request> returns a "cancellation guard" - you have to keep the
96object at least alive until the callback get called. If the object gets 96object at least alive until the callback get called. If the object gets
97destroyed before the callbakc is called, the request will be cancelled. 97destroyed before the callbakc is called, the request will be cancelled.
98 98
99The callback will be called with the response data as first argument 99The callback will be called with the response body data as first argument
100(or C<undef> if it wasn't available due to errors), and a hash-ref with 100(or C<undef> if an error occured), and a hash-ref with response headers as
101response headers as second argument. 101second argument.
102 102
103All the headers in that hash are lowercased. In addition to the response 103All the headers in that hash are lowercased. In addition to the response
104headers, the "pseudo-headers" C<HTTPVersion>, C<Status> and C<Reason> 104headers, the "pseudo-headers" C<HTTPVersion>, C<Status> and C<Reason>
105contain the three parts of the HTTP Status-Line of the same name. The 105contain the three parts of the HTTP Status-Line of the same name. The
106pseudo-header C<URL> contains the original URL (which can differ from the 106pseudo-header C<URL> contains the original URL (which can differ from the
138 138
139=item headers => hashref 139=item headers => hashref
140 140
141The request headers to use. Currently, C<http_request> may provide its 141The request headers to use. Currently, C<http_request> may provide its
142own C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers 142own C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers
143and will provide defaults for C<User-Agent:> and C<Referer:>. 143and will provide defaults for C<User-Agent:> and C<Referer:> (this can be
144suppressed by using C<undef> for these headers in which case they won't be
145sent at all).
144 146
145=item timeout => $seconds 147=item timeout => $seconds
146 148
147The time-out to use for various stages - each connect attempt will reset 149The time-out to use for various stages - each connect attempt will reset
148the timeout, as will read or write activity. Default timeout is 5 minutes. 150the timeout, as will read or write activity, i.e. this is not an overall
151timeout.
152
153Default timeout is 5 minutes.
149 154
150=item proxy => [$host, $port[, $scheme]] or undef 155=item proxy => [$host, $port[, $scheme]] or undef
151 156
152Use the given http proxy for all requests. If not specified, then the 157Use the given http proxy for all requests. If not specified, then the
153default proxy (as specified by C<$ENV{http_proxy}>) is used. 158default proxy (as specified by C<$ENV{http_proxy}>) is used.
154 159
155C<$scheme> must be either missing or C<http> for HTTP, or C<https> for 160C<$scheme> must be either missing, C<http> for HTTP or C<https> for
156HTTPS. 161HTTPS.
157 162
158=item body => $string 163=item body => $string
159 164
160The request body, usually empty. Will be-sent as-is (future versions of 165The request body, usually empty. Will be-sent as-is (future versions of
186verification) TLS context. 191verification) TLS context.
187 192
188The default for this option is C<low>, which could be interpreted as "give 193The default for this option is C<low>, which could be interpreted as "give
189me the page, no matter what". 194me the page, no matter what".
190 195
196=item on_prepare => $callback->($fh)
197
198In rare cases you need to "tune" the socket before it is used to
199connect (for exmaple, to bind it on a given IP address). This parameter
200overrides the prepare callback passed to C<AnyEvent::Socket::tcp_connect>
201and behaves exactly the same way (e.g. it has to provide a
202timeout). See the description for the C<$prepare_cb> argument of
203C<AnyEvent::Socket::tcp_connect> for details.
204
191=item on_header => $callback->($hdr) 205=item on_header => $callback->($headers)
192 206
193When specified, this callback will be called with the header hash as soon 207When specified, this callback will be called with the header hash as soon
194as headers have been successfully received from the remote server (not on 208as headers have been successfully received from the remote server (not on
195locally-generated errors). 209locally-generated errors).
196 210
200 214
201This callback is useful, among other things, to quickly reject unwanted 215This callback is useful, among other things, to quickly reject unwanted
202content, which, if it is supposed to be rare, can be faster than first 216content, which, if it is supposed to be rare, can be faster than first
203doing a C<HEAD> request. 217doing a C<HEAD> request.
204 218
219Example: cancel the request unless the content-type is "text/html".
220
221 on_header => sub {
222 $_[0]{"content-type"} =~ /^text\/html\s*(?:;|$)/
223 },
224
205=item on_body => $callback->($data, $hdr) 225=item on_body => $callback->($partial_body, $headers)
206 226
207When specified, all body data will be "filtered" through this callback. 227When specified, all body data will be passed to this callback instead of
228to the completion callback. The completion callback will get the empty
229string instead of the body data.
208 230
209The callback will incrementally receive body data, and is supposed to 231It has to return either true (in which case AnyEvent::HTTP will continue),
210return it or a modified version of it (empty strings are valid returns). 232or false, in which case AnyEvent::HTTP will cancel the download (and call
233the completion callback with an error code of C<598>).
211 234
212If the callback returns C<undef>, then the request will be cancelled. 235This callback is useful when the data is too large to be held in memory
213 236(so the callback writes it to a file) or when only some information should
214This callback is useful when you want to do some processing on the data, 237be extracted, or when the body should be processed incrementally.
215or the data is too large to be held in memory (so the callback writes it
216to a file and returns the empty string) and so on.
217 238
218It is usually preferred over doing your own body handling via 239It is usually preferred over doing your own body handling via
219C<want_body_handle>. 240C<want_body_handle>, but in case of streaming APIs, where HTTP is
241only used to create a connection, C<want_body_handle> is the better
242alternative, as it allows you to install your own event handler, reducing
243resource usage.
220 244
221=item want_body_handle => $enable 245=item want_body_handle => $enable
222 246
223When enabled (default is disabled), the behaviour of AnyEvent::HTTP 247When enabled (default is disabled), the behaviour of AnyEvent::HTTP
224changes considerably: after parsing the headers, and instead of 248changes considerably: after parsing the headers, and instead of
236This is useful with some push-type services, where, after the initial 260This is useful with some push-type services, where, after the initial
237headers, an interactive protocol is used (typical example would be the 261headers, an interactive protocol is used (typical example would be the
238push-style twitter API which starts a JSON/XML stream). 262push-style twitter API which starts a JSON/XML stream).
239 263
240If you think you need this, first have a look at C<on_body>, to see if 264If you think you need this, first have a look at C<on_body>, to see if
241that doesn'T solve your problem in a better way. 265that doesn't solve your problem in a better way.
242 266
243=back 267=back
244 268
245Example: make a simple HTTP GET request for http://www.nethype.de/ 269Example: make a simple HTTP GET request for http://www.nethype.de/
246 270
302 push @{ $CO_SLOT{$_[0]}[1] }, $_[1]; 326 push @{ $CO_SLOT{$_[0]}[1] }, $_[1];
303 327
304 _slot_schedule $_[0]; 328 _slot_schedule $_[0];
305} 329}
306 330
307our $qr_nl = qr<\015?\012>; 331our $qr_nl = qr{\015?\012};
308our $qr_nlnl = qr<\015?\012\015?\012>; 332our $qr_nlnl = qr{(?<![^\012])\015?\012};
309 333
310our $TLS_CTX_LOW = { cache => 1, sslv2 => 1 }; 334our $TLS_CTX_LOW = { cache => 1, sslv2 => 1 };
311our $TLS_CTX_HIGH = { cache => 1, verify => 1, verify_peername => "https" }; 335our $TLS_CTX_HIGH = { cache => 1, verify => 1, verify_peername => "https" };
312 336
313sub http_request($$@) { 337sub http_request($$@) {
347 $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x 371 $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x
348 or return $cb->(undef, { Status => 599, Reason => "Unparsable URL", URL => $url }); 372 or return $cb->(undef, { Status => 599, Reason => "Unparsable URL", URL => $url });
349 373
350 my $uhost = $1; 374 my $uhost = $1;
351 $uport = $2 if defined $2; 375 $uport = $2 if defined $2;
376
377 $hdr{host} = defined $2 ? "$uhost:$2" : "$uhost";
352 378
353 $uhost =~ s/^\[(.*)\]$/$1/; 379 $uhost =~ s/^\[(.*)\]$/$1/;
354 $upath .= "?$query" if length $query; 380 $upath .= "?$query" if length $query;
355 381
356 $upath =~ s%^/?%/%; 382 $upath =~ s%^/?%/%;
389 my ($rhost, $rport, $rscheme, $rpath); # request host, port, path 415 my ($rhost, $rport, $rscheme, $rpath); # request host, port, path
390 416
391 if ($proxy) { 417 if ($proxy) {
392 ($rpath, $rhost, $rport, $rscheme) = ($url, @$proxy); 418 ($rpath, $rhost, $rport, $rscheme) = ($url, @$proxy);
393 419
420 $rscheme = "http" unless defined $rscheme;
421
394 # don't support https requests over https-proxy transport, 422 # don't support https requests over https-proxy transport,
395 # can't be done with tls as spec'ed, unless you double-encrypt. 423 # can't be done with tls as spec'ed, unless you double-encrypt.
396 $rscheme = "http" if $uscheme eq "https" && $rscheme eq "https"; 424 $rscheme = "http" if $uscheme eq "https" && $rscheme eq "https";
397 } else { 425 } else {
398 ($rhost, $rport, $rscheme, $rpath) = ($uhost, $uport, $uscheme, $upath); 426 ($rhost, $rport, $rscheme, $rpath) = ($uhost, $uport, $uscheme, $upath);
399 } 427 }
400 428
401 $hdr{"user-agent"} ||= $USERAGENT; 429 # leave out fragment and query string, just a heuristic
402 $hdr{referer} ||= "$uscheme://$uauthority$upath"; # leave out fragment and query string, just a heuristic 430 $hdr{referer} ||= "$uscheme://$uauthority$upath" unless exists $hdr{referer};
431 $hdr{"user-agent"} ||= $USERAGENT unless exists $hdr{"user-agent"};
403 432
404 $hdr{host} = "$uhost:$uport";
405 $hdr{"content-length"} = length $arg{body}; 433 $hdr{"content-length"} = length $arg{body};
406 434
407 my %state = (connect_guard => 1); 435 my %state = (connect_guard => 1);
408 436
409 _get_slot $uhost, sub { 437 _get_slot $uhost, sub {
411 439
412 return unless $state{connect_guard}; 440 return unless $state{connect_guard};
413 441
414 $state{connect_guard} = AnyEvent::Socket::tcp_connect $rhost, $rport, sub { 442 $state{connect_guard} = AnyEvent::Socket::tcp_connect $rhost, $rport, sub {
415 $state{fh} = shift 443 $state{fh} = shift
444 or do {
445 my $err = "$!";
446 %state = ();
416 or return (%state = (), $cb->(undef, { Status => 599, Reason => "$!", URL => $url })); 447 return $cb->(undef, { Status => 599, Reason => $err, URL => $url });
448 };
449
417 pop; # free memory, save a tree 450 pop; # free memory, save a tree
418 451
419 return unless delete $state{connect_guard}; 452 return unless delete $state{connect_guard};
420 453
421 # get handle 454 # get handle
454 $state{handle}->starttls ("connect") if $uscheme eq "https" && !exists $state{handle}{tls}; 487 $state{handle}->starttls ("connect") if $uscheme eq "https" && !exists $state{handle}{tls};
455 488
456 # send request 489 # send request
457 $state{handle}->push_write ( 490 $state{handle}->push_write (
458 "$method $rpath HTTP/1.0\015\012" 491 "$method $rpath HTTP/1.0\015\012"
459 . (join "", map "\u$_: $hdr{$_}\015\012", keys %hdr) 492 . (join "", map "\u$_: $hdr{$_}\015\012", grep defined $hdr{$_}, keys %hdr)
460 . "\015\012" 493 . "\015\012"
461 . (delete $arg{body}) 494 . (delete $arg{body})
462 ); 495 );
463 496
464 %hdr = (); # reduce memory usage, save a kitten 497 %hdr = (); # reduce memory usage, save a kitten
475 URL => ",$url" 508 URL => ",$url"
476 ); 509 );
477 510
478 # headers, could be optimized a bit 511 # headers, could be optimized a bit
479 $state{handle}->unshift_read (line => $qr_nlnl, sub { 512 $state{handle}->unshift_read (line => $qr_nlnl, sub {
480 for ("$_[1]\012") { 513 for ("$_[1]") {
481 y/\015//d; # weed out any \015, as they show up in the weirdest of places. 514 y/\015//d; # weed out any \015, as they show up in the weirdest of places.
482 515
483 # things seen, not parsed: 516 # things seen, not parsed:
484 # p3pP="NON CUR OTPi OUR NOR UNI" 517 # p3pP="NON CUR OTPi OUR NOR UNI"
485 518
486 $hdr{lc $1} .= ",$2" 519 $hdr{lc $1} .= ",$2"
487 while /\G 520 while /\G
488 ([^:\000-\037]+): 521 ([^:\000-\037]*):
489 [\011\040]* 522 [\011\040]*
490 ((?: [^\012]+ | \012[\011\040] )*) 523 ((?: [^\012]+ | \012[\011\040] )*)
491 \012 524 \012
492 /gxc; 525 /gxc;
493 526
582 615
583 redo if /\G\s*,/gc; 616 redo if /\G\s*,/gc;
584 } 617 }
585 } 618 }
586 619
587 if ($redirect) { 620 if ($redirect && exists $hdr{location}) {
588 # we ignore any errors, as it is very common to receive 621 # we ignore any errors, as it is very common to receive
589 # Content-Length != 0 but no actual body 622 # Content-Length != 0 but no actual body
590 # we also access %hdr, as $_[1] might be an erro 623 # we also access %hdr, as $_[1] might be an erro
591 http_request ($method => $hdr{location}, %arg, recurse => $recurse - 1, $cb); 624 http_request ($method => $hdr{location}, %arg, recurse => $recurse - 1, $cb);
592 } else { 625 } else {
597 my $len = $hdr{"content-length"}; 630 my $len = $hdr{"content-length"};
598 631
599 if (!$redirect && $arg{on_header} && !$arg{on_header}(\%hdr)) { 632 if (!$redirect && $arg{on_header} && !$arg{on_header}(\%hdr)) {
600 $finish->(undef, { Status => 598, Reason => "Request cancelled by on_header", URL => $url }); 633 $finish->(undef, { Status => 598, Reason => "Request cancelled by on_header", URL => $url });
601 } elsif ( 634 } elsif (
602 $hdr{Status} =~ /^(?:1..|204|304)$/ 635 $hdr{Status} =~ /^(?:1..|[23]04)$/
603 or $method eq "HEAD" 636 or $method eq "HEAD"
604 or (defined $len && !$len) 637 or (defined $len && !$len)
605 ) { 638 ) {
606 # no body 639 # no body
607 $finish->("", \%hdr); 640 $finish->("", \%hdr);
647 $finish->((substr delete $_[0]{rbuf}, 0, $len, ""), \%hdr) 680 $finish->((substr delete $_[0]{rbuf}, 0, $len, ""), \%hdr)
648 if $len <= length $_[0]{rbuf}; 681 if $len <= length $_[0]{rbuf};
649 }); 682 });
650 } else { 683 } else {
651 $_[0]->on_error (sub { 684 $_[0]->on_error (sub {
652 $! == Errno::EPIPE 685 $! == Errno::EPIPE || !$!
653 ? $finish->(delete $_[0]{rbuf}, \%hdr) 686 ? $finish->(delete $_[0]{rbuf}, \%hdr)
654 : $finish->(undef, { Status => 599, Reason => $_[2], URL => $url }); 687 : $finish->(undef, { Status => 599, Reason => $_[2], URL => $url });
655 }); 688 });
656 $_[0]->on_read (sub { }); 689 $_[0]->on_read (sub { });
657 } 690 }
681 }); 714 });
682 } else { 715 } else {
683 &$handle_actual_request; 716 &$handle_actual_request;
684 } 717 }
685 718
686 }, sub { 719 }, $arg{on_prepare} || sub { $timeout };
687 $timeout
688 };
689 }; 720 };
690 721
691 defined wantarray && AnyEvent::Util::guard { %state = () } 722 defined wantarray && AnyEvent::Util::guard { %state = () }
692} 723}
693 724
725=item $AnyEvent::HTTP::USERAGENT 756=item $AnyEvent::HTTP::USERAGENT
726 757
727The default value for the C<User-Agent> header (the default is 758The default value for the C<User-Agent> header (the default is
728C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>). 759C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>).
729 760
730=item $AnyEvent::HTTP::MAX_PERSISTENT 761=item $AnyEvent::HTTP::MAX_PER_HOST
731 762
732The maximum number of persistent connections to keep open (default: 8). 763The maximum number of concurrent connections to the same host (identified
764by the hostname). If the limit is exceeded, then the additional requests
765are queued until previous connections are closed.
733 766
734Not implemented currently. 767The default value for this is C<4>, and it is highly advisable to not
735 768increase it.
736=item $AnyEvent::HTTP::PERSISTENT_TIMEOUT
737
738The maximum time to cache a persistent connection, in seconds (default: 2).
739
740Not implemented currently.
741 769
742=item $AnyEvent::HTTP::ACTIVE 770=item $AnyEvent::HTTP::ACTIVE
743 771
744The number of active connections. This is not the number of currently 772The number of active connections. This is not the number of currently
745running requests, but the number of currently open and non-idle TCP 773running requests, but the number of currently open and non-idle TCP

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines