ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-HTTP/HTTP.pm
Revision: 1.40
Committed: Sun Jul 5 01:45:01 2009 UTC (14 years, 10 months ago) by root
Branch: MAIN
Changes since 1.39: +39 -20 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 =head1 NAME
2
3 AnyEvent::HTTP - simple but non-blocking HTTP/HTTPS client
4
5 =head1 SYNOPSIS
6
7 use AnyEvent::HTTP;
8
9 http_get "http://www.nethype.de/", sub { print $_[1] };
10
11 # ... do something else here
12
13 =head1 DESCRIPTION
14
15 This module is an L<AnyEvent> user, you need to make sure that you use and
16 run a supported event loop.
17
18 This module implements a simple, stateless and non-blocking HTTP
19 client. It supports GET, POST and other request methods, cookies and more,
20 all on a very low level. It can follow redirects supports proxies and
21 automatically limits the number of connections to the values specified in
22 the RFC.
23
24 It should generally be a "good client" that is enough for most HTTP
25 tasks. Simple tasks should be simple, but complex tasks should still be
26 possible as the user retains control over request and response headers.
27
28 The caller is responsible for authentication management, cookies (if
29 the simplistic implementation in this module doesn't suffice), referer
30 and other high-level protocol details for which this module offers only
31 limited support.
32
33 =head2 METHODS
34
35 =over 4
36
37 =cut
38
39 package AnyEvent::HTTP;
40
41 use strict;
42 no warnings;
43
44 use Carp;
45
46 use AnyEvent 4.452 ();
47 use AnyEvent::Util ();
48 use AnyEvent::Socket ();
49 use AnyEvent::Handle ();
50
51 use base Exporter::;
52
53 our $VERSION = '1.12';
54
55 our @EXPORT = qw(http_get http_post http_head http_request);
56
57 our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)";
58 our $MAX_RECURSE = 10;
59 our $MAX_PERSISTENT = 8;
60 our $PERSISTENT_TIMEOUT = 2;
61 our $TIMEOUT = 300;
62
63 # changing these is evil
64 our $MAX_PERSISTENT_PER_HOST = 2;
65 our $MAX_PER_HOST = 4;
66
67 our $PROXY;
68 our $ACTIVE = 0;
69
70 my %KA_COUNT; # number of open keep-alive connections per host
71 my %CO_SLOT; # number of open connections, and wait queue, per host
72
73 =item http_get $url, key => value..., $cb->($data, $headers)
74
75 Executes an HTTP-GET request. See the http_request function for details on
76 additional parameters and the return value.
77
78 =item http_head $url, key => value..., $cb->($data, $headers)
79
80 Executes an HTTP-HEAD request. See the http_request function for details
81 on additional parameters and the return value.
82
83 =item http_post $url, $body, key => value..., $cb->($data, $headers)
84
85 Executes an HTTP-POST request with a request body of C<$body>. See the
86 http_request function for details on additional parameters and the return
87 value.
88
89 =item http_request $method => $url, key => value..., $cb->($data, $headers)
90
91 Executes a HTTP request of type C<$method> (e.g. C<GET>, C<POST>). The URL
92 must be an absolute http or https URL.
93
94 When called in void context, nothing is returned. In other contexts,
95 C<http_request> returns a "cancellation guard" - you have to keep the
96 object at least alive until the callback get called. If the object gets
97 destroyed before the callbakc is called, the request will be cancelled.
98
99 The callback will be called with the response data as first argument
100 (or C<undef> if it wasn't available due to errors), and a hash-ref with
101 response headers as second argument.
102
103 All the headers in that hash are lowercased. In addition to the response
104 headers, the "pseudo-headers" C<HTTPVersion>, C<Status> and C<Reason>
105 contain the three parts of the HTTP Status-Line of the same name. The
106 pseudo-header C<URL> contains the original URL (which can differ from the
107 requested URL when following redirects).
108
109 If the server sends a header multiple times, then their contents will be
110 joined together with a comma (C<,>), as per the HTTP spec.
111
112 If an internal error occurs, such as not being able to resolve a hostname,
113 then C<$data> will be C<undef>, C<< $headers->{Status} >> will be C<599>
114 and the C<Reason> pseudo-header will contain an error message.
115
116 A typical callback might look like this:
117
118 sub {
119 my ($body, $hdr) = @_;
120
121 if ($hdr->{Status} =~ /^2/) {
122 ... everything should be ok
123 } else {
124 print "error, $hdr->{Status} $hdr->{Reason}\n";
125 }
126 }
127
128 Additional parameters are key-value pairs, and are fully optional. They
129 include:
130
131 =over 4
132
133 =item recurse => $count (default: $MAX_RECURSE)
134
135 Whether to recurse requests or not, e.g. on redirects, authentication
136 retries and so on, and how often to do so.
137
138 =item headers => hashref
139
140 The request headers to use. Currently, C<http_request> may provide its
141 own C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers
142 and will provide defaults for C<User-Agent:> and C<Referer:>.
143
144 =item timeout => $seconds
145
146 The time-out to use for various stages - each connect attempt will reset
147 the timeout, as will read or write activity. Default timeout is 5 minutes.
148
149 =item proxy => [$host, $port[, $scheme]] or undef
150
151 Use the given http proxy for all requests. If not specified, then the
152 default proxy (as specified by C<$ENV{http_proxy}>) is used.
153
154 C<$scheme> must be either missing or C<http> for HTTP, or C<https> for
155 HTTPS.
156
157 =item body => $string
158
159 The request body, usually empty. Will be-sent as-is (future versions of
160 this module might offer more options).
161
162 =item cookie_jar => $hash_ref
163
164 Passing this parameter enables (simplified) cookie-processing, loosely
165 based on the original netscape specification.
166
167 The C<$hash_ref> must be an (initially empty) hash reference which will
168 get updated automatically. It is possible to save the cookie_jar to
169 persistent storage with something like JSON or Storable, but this is not
170 recommended, as expiry times are currently being ignored.
171
172 Note that this cookie implementation is not of very high quality, nor
173 meant to be complete. If you want complete cookie management you have to
174 do that on your own. C<cookie_jar> is meant as a quick fix to get some
175 cookie-using sites working. Cookies are a privacy disaster, do not use
176 them unless required to.
177
178 =item tls_ctx => $scheme | $tls_ctx
179
180 Specifies the AnyEvent::TLS context to be used for https connections. This
181 parameter follows the same rules as the C<tls_ctx> parameter to
182 L<AnyEvent::Handle>, but additionally, the two strings C<low> or
183 C<high> can be specified, which give you a predefined low-security (no
184 verification, highest compatibility) and high-security (CA and common-name
185 verification) TLS context.
186
187 The default for this option is C<low>, which could be interpreted as "give
188 me the page, no matter what".
189
190 =back
191
192 Example: make a simple HTTP GET request for http://www.nethype.de/
193
194 http_request GET => "http://www.nethype.de/", sub {
195 my ($body, $hdr) = @_;
196 print "$body\n";
197 };
198
199 Example: make a HTTP HEAD request on https://www.google.com/, use a
200 timeout of 30 seconds.
201
202 http_request
203 GET => "https://www.google.com",
204 timeout => 30,
205 sub {
206 my ($body, $hdr) = @_;
207 use Data::Dumper;
208 print Dumper $hdr;
209 }
210 ;
211
212 Example: make another simple HTTP GET request, but immediately try to
213 cancel it.
214
215 my $request = http_request GET => "http://www.nethype.de/", sub {
216 my ($body, $hdr) = @_;
217 print "$body\n";
218 };
219
220 undef $request;
221
222 =cut
223
224 sub _slot_schedule;
225 sub _slot_schedule($) {
226 my $host = shift;
227
228 while ($CO_SLOT{$host}[0] < $MAX_PER_HOST) {
229 if (my $cb = shift @{ $CO_SLOT{$host}[1] }) {
230 # somebody wants that slot
231 ++$CO_SLOT{$host}[0];
232 ++$ACTIVE;
233
234 $cb->(AnyEvent::Util::guard {
235 --$ACTIVE;
236 --$CO_SLOT{$host}[0];
237 _slot_schedule $host;
238 });
239 } else {
240 # nobody wants the slot, maybe we can forget about it
241 delete $CO_SLOT{$host} unless $CO_SLOT{$host}[0];
242 last;
243 }
244 }
245 }
246
247 # wait for a free slot on host, call callback
248 sub _get_slot($$) {
249 push @{ $CO_SLOT{$_[0]}[1] }, $_[1];
250
251 _slot_schedule $_[0];
252 }
253
254 our $qr_nl = qr<\015?\012>;
255 our $qr_nlnl = qr<\015?\012\015?\012>;
256
257 our $TLS_CTX_LOW = { cache => 1, dh => undef, sslv2 => 1 };
258 our $TLS_CTX_HIGH = { cache => 1, verify => 1, verify_cn => "https", dh => "skip4096" };
259
260 sub http_request($$@) {
261 my $cb = pop;
262 my ($method, $url, %arg) = @_;
263
264 my %hdr;
265
266 $arg{tls_ctx} = $TLS_CTX_LOW if $arg{tls_ctx} eq "low" || !exists $arg{tls_ctx};
267 $arg{tls_ctx} = $TLS_CTX_HIGH if $arg{tls_ctx} eq "high";
268
269 $method = uc $method;
270
271 if (my $hdr = $arg{headers}) {
272 while (my ($k, $v) = each %$hdr) {
273 $hdr{lc $k} = $v;
274 }
275 }
276
277 my $recurse = exists $arg{recurse} ? delete $arg{recurse} : $MAX_RECURSE;
278
279 return $cb->(undef, { Status => 599, Reason => "Too many redirections", URL => $url })
280 if $recurse < 0;
281
282 my $proxy = $arg{proxy} || $PROXY;
283 my $timeout = $arg{timeout} || $TIMEOUT;
284
285 $hdr{"user-agent"} ||= $USERAGENT;
286
287 my ($uscheme, $uauthority, $upath, $query, $fragment) =
288 $url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?|;
289
290 $uscheme = lc $uscheme;
291
292 my $uport = $uscheme eq "http" ? 80
293 : $uscheme eq "https" ? 443
294 : return $cb->(undef, { Status => 599, Reason => "Only http and https URL schemes supported (not '$uscheme')", URL => $url });
295
296 $hdr{referer} ||= "$uscheme://$uauthority$upath"; # leave out fragment and query string, just a heuristic
297
298 $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x
299 or return $cb->(undef, { Status => 599, Reason => "Unparsable URL", URL => $url });
300
301 my $uhost = $1;
302 $uport = $2 if defined $2;
303
304 $uhost =~ s/^\[(.*)\]$/$1/;
305 $upath .= "?$query" if length $query;
306
307 $upath =~ s%^/?%/%;
308
309 # cookie processing
310 if (my $jar = $arg{cookie_jar}) {
311 %$jar = () if $jar->{version} != 1;
312
313 my @cookie;
314
315 while (my ($chost, $v) = each %$jar) {
316 if ($chost =~ /^\./) {
317 next unless $chost eq substr $uhost, -length $chost;
318 } elsif ($chost =~ /\./) {
319 next unless $chost eq $uhost;
320 } else {
321 next;
322 }
323
324 while (my ($cpath, $v) = each %$v) {
325 next unless $cpath eq substr $upath, 0, length $cpath;
326
327 while (my ($k, $v) = each %$v) {
328 next if $uscheme ne "https" && exists $v->{secure};
329 my $value = $v->{value};
330 $value =~ s/([\\"])/\\$1/g;
331 push @cookie, "$k=\"$value\"";
332 }
333 }
334 }
335
336 $hdr{cookie} = join "; ", @cookie
337 if @cookie;
338 }
339
340 my ($rhost, $rport, $rscheme, $rpath); # request host, port, path
341
342 if ($proxy) {
343 ($rpath, $rhost, $rport, $rscheme) = ($url, @$proxy);
344
345 # don't support https requests over https-proxy transport,
346 # can't be done with tls as spec'ed, unless you double-encrypt.
347 $rscheme = "http" if $uscheme eq "https" && $rscheme eq "https";
348 } else {
349 ($rhost, $rport, $rscheme, $rpath) = ($uhost, $uport, $uscheme, $upath);
350 }
351
352 $hdr{host} = $uhost;
353 $hdr{"content-length"} = length $arg{body};
354
355 my %state = (connect_guard => 1);
356
357 _get_slot $uhost, sub {
358 $state{slot_guard} = shift;
359
360 return unless $state{connect_guard};
361
362 $state{connect_guard} = AnyEvent::Socket::tcp_connect $rhost, $rport, sub {
363 $state{fh} = shift
364 or return (%state = (), $cb->(undef, { Status => 599, Reason => "$!", URL => $url }));
365 pop; # free memory, save a tree
366
367 return unless delete $state{connect_guard};
368
369 # get handle
370 $state{handle} = new AnyEvent::Handle
371 fh => $state{fh},
372 timeout => $timeout,
373 peername => $rhost,
374 tls_ctx => $arg{tls_ctx};
375
376 # limit the number of persistent connections
377 # keepalive not yet supported
378 if ($KA_COUNT{$_[1]} < $MAX_PERSISTENT_PER_HOST) {
379 ++$KA_COUNT{$_[1]};
380 $state{handle}{ka_count_guard} = AnyEvent::Util::guard {
381 --$KA_COUNT{$_[1]}
382 };
383 $hdr{connection} = "keep-alive";
384 } else {
385 delete $hdr{connection};
386 }
387
388 # (re-)configure handle
389 $state{handle}->on_error (sub {
390 %state = ();
391 $cb->(undef, { Status => 599, Reason => $_[2], URL => $url });
392 });
393 $state{handle}->on_eof (sub {
394 %state = ();
395 $cb->(undef, { Status => 599, Reason => "Unexpected end-of-file", URL => $url });
396 });
397
398 $state{handle}->starttls ("connect") if $rscheme eq "https";
399
400 # handle actual, non-tunneled, request
401 my $handle_actual_request = sub {
402 $state{handle}->starttls ("connect") if $uscheme eq "https" && !exists $state{handle}{tls};
403
404 # send request
405 $state{handle}->push_write (
406 "$method $rpath HTTP/1.0\015\012"
407 . (join "", map "\u$_: $hdr{$_}\015\012", keys %hdr)
408 . "\015\012"
409 . (delete $arg{body})
410 );
411
412 %hdr = (); # reduce memory usage, save a kitten
413
414 # status line
415 $state{handle}->push_read (line => $qr_nl, sub {
416 $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix
417 or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid server response ($_[1])", URL => $url }));
418
419 my %hdr = ( # response headers
420 HTTPVersion => ",$1",
421 Status => ",$2",
422 Reason => ",$3",
423 URL => ",$url"
424 );
425
426 # headers, could be optimized a bit
427 $state{handle}->unshift_read (line => $qr_nlnl, sub {
428 for ("$_[1]\012") {
429 y/\015//d; # weed out any \015, as they show up in the weirdest of places.
430
431 # things seen, not parsed:
432 # p3pP="NON CUR OTPi OUR NOR UNI"
433
434 $hdr{lc $1} .= ",$2"
435 while /\G
436 ([^:\000-\037]+):
437 [\011\040]*
438 ((?: [^\012]+ | \012[\011\040] )*)
439 \012
440 /gxc;
441
442 /\G$/
443 or return (%state = (), $cb->(undef, { Status => 599, Reason => "Garbled response headers", URL => $url }));
444 }
445
446 substr $_, 0, 1, ""
447 for values %hdr;
448
449 my $finish = sub {
450 $state{handle}->destroy;
451 %state = ();
452
453 # set-cookie processing
454 if ($arg{cookie_jar}) {
455 for ($hdr{"set-cookie"}) {
456 # parse NAME=VALUE
457 my @kv;
458
459 while (/\G\s* ([^=;,[:space:]]+) \s*=\s* (?: "((?:[^\\"]+|\\.)*)" | ([^=;,[:space:]]*) )/gcxs) {
460 my $name = $1;
461 my $value = $3;
462
463 unless ($value) {
464 $value = $2;
465 $value =~ s/\\(.)/$1/gs;
466 }
467
468 push @kv, $name => $value;
469
470 last unless /\G\s*;/gc;
471 }
472
473 last unless @kv;
474
475 my $name = shift @kv;
476 my %kv = (value => shift @kv, @kv);
477
478 my $cdom;
479 my $cpath = (delete $kv{path}) || "/";
480
481 if (exists $kv{domain}) {
482 $cdom = delete $kv{domain};
483
484 $cdom =~ s/^\.?/./; # make sure it starts with a "."
485
486 next if $cdom =~ /\.$/;
487
488 # this is not rfc-like and not netscape-like. go figure.
489 my $ndots = $cdom =~ y/.//;
490 next if $ndots < ($cdom =~ /\.[^.][^.]\.[^.][^.]$/ ? 3 : 2);
491 } else {
492 $cdom = $uhost;
493 }
494
495 # store it
496 $arg{cookie_jar}{version} = 1;
497 $arg{cookie_jar}{$cdom}{$cpath}{$name} = \%kv;
498
499 redo if /\G\s*,/gc;
500 }
501 }
502
503 # microsoft and other shitheads don't give a shit for following standards,
504 # try to support some common forms of broken Location headers.
505 if ($_[1]{location} !~ /^(?: $ | [^:\/?\#]+ : )/x) {
506 $_[1]{location} =~ s/^\.\/+//;
507
508 my $url = "$rscheme://$uhost:$uport";
509
510 unless ($_[1]{location} =~ s/^\///) {
511 $url .= $upath;
512 $url =~ s/\/[^\/]*$//;
513 }
514
515 $_[1]{location} = "$url/$_[1]{location}";
516 }
517
518 if ($_[1]{Status} =~ /^30[12]$/ && $recurse && $method ne "POST") {
519 # apparently, mozilla et al. just change POST to GET here
520 # more research is needed before we do the same
521 http_request ($method => $_[1]{location}, %arg, recurse => $recurse - 1, $cb);
522 } elsif ($_[1]{Status} == 303 && $recurse) {
523 # even http/1.1 is unclear on how to mutate the method
524 $method = "GET" unless $method eq "HEAD";
525 http_request ($method => $_[1]{location}, %arg, recurse => $recurse - 1, $cb);
526 } elsif ($_[1]{Status} == 307 && $recurse && $method =~ /^(?:GET|HEAD)$/) {
527 http_request ($method => $_[1]{location}, %arg, recurse => $recurse - 1, $cb);
528 } else {
529 $cb->($_[0], $_[1]);
530 }
531 };
532
533 if ($hdr{Status} =~ /^(?:1..|204|304)$/ or $method eq "HEAD") {
534 $finish->(undef, \%hdr);
535 } else {
536 if (exists $hdr{"content-length"}) {
537 $_[0]->unshift_read (chunk => $hdr{"content-length"}, sub {
538 # could cache persistent connection now
539 if ($hdr{connection} =~ /\bkeep-alive\b/i) {
540 # but we don't, due to misdesigns, this is annoyingly complex
541 };
542
543 $finish->($_[1], \%hdr);
544 });
545 } else {
546 # too bad, need to read until we get an error or EOF,
547 # no way to detect winged data.
548 $_[0]->on_error (sub {
549 # delete ought to be more efficient, as we would have to make
550 # a copy otherwise as $_[0] gets destroyed.
551 $finish->(delete $_[0]{rbuf}, \%hdr);
552 });
553 $_[0]->on_eof (undef);
554 $_[0]->on_read (sub { });
555 }
556 }
557 });
558 });
559 };
560
561 # now handle proxy-CONNECT method
562 if ($proxy && $uscheme eq "https") {
563 # oh dear, we have to wrap it into a connect request
564
565 # maybe re-use $uauthority with patched port?
566 $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012Host: $uhost\015\012\015\012");
567 $state{handle}->push_read (line => $qr_nlnl, sub {
568 $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix
569 or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid proxy connect response ($_[1])", URL => $url }));
570
571 if ($2 == 200) {
572 $rpath = $upath;
573 &$handle_actual_request;
574 } else {
575 %state = ();
576 $cb->(undef, { Status => $2, Reason => $3, URL => $url });
577 }
578 });
579 } else {
580 &$handle_actual_request;
581 }
582
583 }, sub {
584 $timeout
585 };
586 };
587
588 defined wantarray && AnyEvent::Util::guard { %state = () }
589 }
590
591 sub http_get($@) {
592 unshift @_, "GET";
593 &http_request
594 }
595
596 sub http_head($@) {
597 unshift @_, "HEAD";
598 &http_request
599 }
600
601 sub http_post($$@) {
602 my $url = shift;
603 unshift @_, "POST", $url, "body";
604 &http_request
605 }
606
607 =back
608
609 =head2 GLOBAL FUNCTIONS AND VARIABLES
610
611 =over 4
612
613 =item AnyEvent::HTTP::set_proxy "proxy-url"
614
615 Sets the default proxy server to use. The proxy-url must begin with a
616 string of the form C<http://host:port> (optionally C<https:...>).
617
618 =item $AnyEvent::HTTP::MAX_RECURSE
619
620 The default value for the C<recurse> request parameter (default: C<10>).
621
622 =item $AnyEvent::HTTP::USERAGENT
623
624 The default value for the C<User-Agent> header (the default is
625 C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>).
626
627 =item $AnyEvent::HTTP::MAX_PERSISTENT
628
629 The maximum number of persistent connections to keep open (default: 8).
630
631 Not implemented currently.
632
633 =item $AnyEvent::HTTP::PERSISTENT_TIMEOUT
634
635 The maximum time to cache a persistent connection, in seconds (default: 2).
636
637 Not implemented currently.
638
639 =item $AnyEvent::HTTP::ACTIVE
640
641 The number of active connections. This is not the number of currently
642 running requests, but the number of currently open and non-idle TCP
643 connections. This number of can be useful for load-leveling.
644
645 =back
646
647 =cut
648
649 sub set_proxy($) {
650 $PROXY = [$2, $3 || 3128, $1] if $_[0] =~ m%^(https?):// ([^:/]+) (?: : (\d*) )?%ix;
651 }
652
653 # initialise proxy from environment
654 set_proxy $ENV{http_proxy};
655
656 =head1 SEE ALSO
657
658 L<AnyEvent>.
659
660 =head1 AUTHOR
661
662 Marc Lehmann <schmorp@schmorp.de>
663 http://home.schmorp.de/
664
665 With many thanks to Дмитрий Шалашов, who provided countless
666 testcases and bugreports.
667
668 =cut
669
670 1
671