… | |
… | |
41 | use strict; |
41 | use strict; |
42 | no warnings; |
42 | no warnings; |
43 | |
43 | |
44 | use Errno (); |
44 | use Errno (); |
45 | |
45 | |
46 | use AnyEvent 4.452 (); |
46 | use AnyEvent 5.0 (); |
47 | use AnyEvent::Util (); |
47 | use AnyEvent::Util (); |
48 | use AnyEvent::Socket (); |
|
|
49 | use AnyEvent::Handle (); |
48 | use AnyEvent::Handle (); |
50 | |
49 | |
51 | use base Exporter::; |
50 | use base Exporter::; |
52 | |
51 | |
53 | our $VERSION = '1.12'; |
52 | our $VERSION = '1.46'; |
54 | |
53 | |
55 | our @EXPORT = qw(http_get http_post http_head http_request); |
54 | our @EXPORT = qw(http_get http_post http_head http_request); |
56 | |
55 | |
57 | our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)"; |
56 | our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)"; |
58 | our $MAX_RECURSE = 10; |
57 | our $MAX_RECURSE = 10; |
59 | our $MAX_PERSISTENT = 8; |
58 | our $MAX_PERSISTENT = 8; |
60 | our $PERSISTENT_TIMEOUT = 2; |
59 | our $PERSISTENT_TIMEOUT = 2; |
61 | our $TIMEOUT = 300; |
60 | our $TIMEOUT = 300; |
62 | |
61 | |
63 | # changing these is evil |
62 | # changing these is evil |
64 | our $MAX_PERSISTENT_PER_HOST = 2; |
63 | our $MAX_PERSISTENT_PER_HOST = 0; |
65 | our $MAX_PER_HOST = 4; |
64 | our $MAX_PER_HOST = 4; |
66 | |
65 | |
67 | our $PROXY; |
66 | our $PROXY; |
68 | our $ACTIVE = 0; |
67 | our $ACTIVE = 0; |
69 | |
68 | |
… | |
… | |
92 | must be an absolute http or https URL. |
91 | must be an absolute http or https URL. |
93 | |
92 | |
94 | When called in void context, nothing is returned. In other contexts, |
93 | When called in void context, nothing is returned. In other contexts, |
95 | C<http_request> returns a "cancellation guard" - you have to keep the |
94 | 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 |
95 | 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. |
96 | destroyed before the callback is called, the request will be cancelled. |
98 | |
97 | |
99 | The callback will be called with the response data as first argument |
98 | The 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 |
99 | (or C<undef> if an error occured), and a hash-ref with response headers as |
101 | response headers as second argument. |
100 | second argument. |
102 | |
101 | |
103 | All the headers in that hash are lowercased. In addition to the response |
102 | 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> |
103 | headers, the "pseudo-headers" (uppercase to avoid clashing with possible |
|
|
104 | response headers) C<HTTPVersion>, C<Status> and C<Reason> contain the |
105 | contain the three parts of the HTTP Status-Line of the same name. The |
105 | three parts of the HTTP Status-Line of the same name. |
|
|
106 | |
106 | pseudo-header C<URL> contains the original URL (which can differ from the |
107 | The pseudo-header C<URL> contains the actual URL (which can differ from |
107 | requested URL when following redirects). |
108 | the requested URL when following redirects - for example, you might get |
|
|
109 | an error that your URL scheme is not supported even though your URL is a |
|
|
110 | valid http URL because it redirected to an ftp URL, in which case you can |
|
|
111 | look at the URL pseudo header). |
|
|
112 | |
|
|
113 | The pseudo-header C<Redirect> only exists when the request was a result |
|
|
114 | of an internal redirect. In that case it is an array reference with |
|
|
115 | the C<($data, $headers)> from the redirect response. Note that this |
|
|
116 | response could in turn be the result of a redirect itself, and C<< |
|
|
117 | $headers->{Redirect}[1]{Redirect} >> will then contain the original |
|
|
118 | response, and so on. |
108 | |
119 | |
109 | If the server sends a header multiple times, then their contents will be |
120 | 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. |
121 | joined together with a comma (C<,>), as per the HTTP spec. |
111 | |
122 | |
112 | If an internal error occurs, such as not being able to resolve a hostname, |
123 | If an internal error occurs, such as not being able to resolve a hostname, |
… | |
… | |
136 | Whether to recurse requests or not, e.g. on redirects, authentication |
147 | Whether to recurse requests or not, e.g. on redirects, authentication |
137 | retries and so on, and how often to do so. |
148 | retries and so on, and how often to do so. |
138 | |
149 | |
139 | =item headers => hashref |
150 | =item headers => hashref |
140 | |
151 | |
141 | The request headers to use. Currently, C<http_request> may provide its |
152 | The request headers to use, with the header name (I<MUST be in lowercase>) |
142 | own C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers |
153 | as key and header value as hash value. |
143 | and will provide defaults for C<User-Agent:> and C<Referer:>. |
154 | |
|
|
155 | Currently, http_request> may provide its own C<host>, C<content-length>, |
|
|
156 | C<connection> and C<cookie> headers and will provide defaults for |
|
|
157 | C<user-agent> and C<referer> (this can be suppressed by using a value of |
|
|
158 | C<undef> for these headers in which case they won't be sent at all). |
144 | |
159 | |
145 | =item timeout => $seconds |
160 | =item timeout => $seconds |
146 | |
161 | |
147 | The time-out to use for various stages - each connect attempt will reset |
162 | The time-out to use for various stages - each connect attempt will reset |
148 | the timeout, as will read or write activity. Default timeout is 5 minutes. |
163 | the timeout, as will read or write activity, i.e. this is not an overall |
|
|
164 | timeout. |
|
|
165 | |
|
|
166 | Default timeout is 5 minutes. |
149 | |
167 | |
150 | =item proxy => [$host, $port[, $scheme]] or undef |
168 | =item proxy => [$host, $port[, $scheme]] or undef |
151 | |
169 | |
152 | Use the given http proxy for all requests. If not specified, then the |
170 | Use the given http proxy for all requests. If not specified, then the |
153 | default proxy (as specified by C<$ENV{http_proxy}>) is used. |
171 | default proxy (as specified by C<$ENV{http_proxy}>) is used. |
154 | |
172 | |
155 | C<$scheme> must be either missing or C<http> for HTTP, or C<https> for |
173 | C<$scheme> must be either missing, C<http> for HTTP or C<https> for |
156 | HTTPS. |
174 | HTTPS. |
157 | |
175 | |
158 | =item body => $string |
176 | =item body => $string |
159 | |
177 | |
160 | The request body, usually empty. Will be-sent as-is (future versions of |
178 | The request body, usually empty. Will be-sent as-is (future versions of |
… | |
… | |
186 | verification) TLS context. |
204 | verification) TLS context. |
187 | |
205 | |
188 | The default for this option is C<low>, which could be interpreted as "give |
206 | The default for this option is C<low>, which could be interpreted as "give |
189 | me the page, no matter what". |
207 | me the page, no matter what". |
190 | |
208 | |
|
|
209 | =item on_prepare => $callback->($fh) |
|
|
210 | |
|
|
211 | In rare cases you need to "tune" the socket before it is used to |
|
|
212 | connect (for exmaple, to bind it on a given IP address). This parameter |
|
|
213 | overrides the prepare callback passed to C<AnyEvent::Socket::tcp_connect> |
|
|
214 | and behaves exactly the same way (e.g. it has to provide a |
|
|
215 | timeout). See the description for the C<$prepare_cb> argument of |
|
|
216 | C<AnyEvent::Socket::tcp_connect> for details. |
|
|
217 | |
|
|
218 | =item tcp_connect => $callback->($host, $service, $connect_cb, $prepare_cb) |
|
|
219 | |
|
|
220 | In even rarer cases you want total control over how AnyEvent::HTTP |
|
|
221 | establishes connections. Normally it uses L<AnyEvent::Socket::tcp_connect> |
|
|
222 | to do this, but you can provide your own C<tcp_connect> function - |
|
|
223 | obviously, it has to follow the same calling conventions, except that it |
|
|
224 | may always return a connection guard object. |
|
|
225 | |
|
|
226 | There are probably lots of weird uses for this function, starting from |
|
|
227 | tracing the hosts C<http_request> actually tries to connect, to (inexact |
|
|
228 | but fast) host => IP address caching or even socks protocol support. |
|
|
229 | |
191 | =item on_header => $callback->($hdr) |
230 | =item on_header => $callback->($headers) |
192 | |
231 | |
193 | When specified, this callback will be called with the header hash as soon |
232 | When specified, this callback will be called with the header hash as soon |
194 | as headers have been successfully received from the remote server (not on |
233 | as headers have been successfully received from the remote server (not on |
195 | locally-generated errors). |
234 | locally-generated errors). |
196 | |
235 | |
… | |
… | |
200 | |
239 | |
201 | This callback is useful, among other things, to quickly reject unwanted |
240 | This callback is useful, among other things, to quickly reject unwanted |
202 | content, which, if it is supposed to be rare, can be faster than first |
241 | content, which, if it is supposed to be rare, can be faster than first |
203 | doing a C<HEAD> request. |
242 | doing a C<HEAD> request. |
204 | |
243 | |
|
|
244 | Example: cancel the request unless the content-type is "text/html". |
|
|
245 | |
|
|
246 | on_header => sub { |
|
|
247 | $_[0]{"content-type"} =~ /^text\/html\s*(?:;|$)/ |
|
|
248 | }, |
|
|
249 | |
205 | =item on_body => $callback->($data, $hdr) |
250 | =item on_body => $callback->($partial_body, $headers) |
206 | |
251 | |
207 | When specified, all body data will be "filtered" through this callback. |
252 | When specified, all body data will be passed to this callback instead of |
|
|
253 | to the completion callback. The completion callback will get the empty |
|
|
254 | string instead of the body data. |
208 | |
255 | |
209 | The callback will incrementally receive body data, and is supposed to |
256 | It has to return either true (in which case AnyEvent::HTTP will continue), |
210 | return it or a modified version of it (empty strings are valid returns). |
257 | or false, in which case AnyEvent::HTTP will cancel the download (and call |
|
|
258 | the completion callback with an error code of C<598>). |
211 | |
259 | |
212 | If the callback returns C<undef>, then the request will be cancelled. |
260 | This callback is useful when the data is too large to be held in memory |
213 | |
261 | (so the callback writes it to a file) or when only some information should |
214 | This callback is useful when you want to do some processing on the data, |
262 | be extracted, or when the body should be processed incrementally. |
215 | or the data is too large to be held in memory (so the callback writes it |
|
|
216 | to a file and returns the empty string) and so on. |
|
|
217 | |
263 | |
218 | It is usually preferred over doing your own body handling via |
264 | It is usually preferred over doing your own body handling via |
219 | C<want_body_handle>. |
265 | C<want_body_handle>, but in case of streaming APIs, where HTTP is |
|
|
266 | only used to create a connection, C<want_body_handle> is the better |
|
|
267 | alternative, as it allows you to install your own event handler, reducing |
|
|
268 | resource usage. |
220 | |
269 | |
221 | =item want_body_handle => $enable |
270 | =item want_body_handle => $enable |
222 | |
271 | |
223 | When enabled (default is disabled), the behaviour of AnyEvent::HTTP |
272 | When enabled (default is disabled), the behaviour of AnyEvent::HTTP |
224 | changes considerably: after parsing the headers, and instead of |
273 | changes considerably: after parsing the headers, and instead of |
… | |
… | |
236 | This is useful with some push-type services, where, after the initial |
285 | This is useful with some push-type services, where, after the initial |
237 | headers, an interactive protocol is used (typical example would be the |
286 | headers, an interactive protocol is used (typical example would be the |
238 | push-style twitter API which starts a JSON/XML stream). |
287 | push-style twitter API which starts a JSON/XML stream). |
239 | |
288 | |
240 | If you think you need this, first have a look at C<on_body>, to see if |
289 | If you think you need this, first have a look at C<on_body>, to see if |
241 | that doesn'T solve your problem in a better way. |
290 | that doesn't solve your problem in a better way. |
242 | |
291 | |
243 | =back |
292 | =back |
244 | |
293 | |
245 | Example: make a simple HTTP GET request for http://www.nethype.de/ |
294 | Example: make a simple HTTP GET request for http://www.nethype.de/ |
246 | |
295 | |
… | |
… | |
302 | push @{ $CO_SLOT{$_[0]}[1] }, $_[1]; |
351 | push @{ $CO_SLOT{$_[0]}[1] }, $_[1]; |
303 | |
352 | |
304 | _slot_schedule $_[0]; |
353 | _slot_schedule $_[0]; |
305 | } |
354 | } |
306 | |
355 | |
307 | our $qr_nl = qr<\015?\012>; |
356 | our $qr_nlnl = qr{(?<![^\012])\015?\012}; |
308 | our $qr_nlnl = qr<\015?\012\015?\012>; |
|
|
309 | |
357 | |
310 | our $TLS_CTX_LOW = { cache => 1, sslv2 => 1 }; |
358 | our $TLS_CTX_LOW = { cache => 1, sslv2 => 1 }; |
311 | our $TLS_CTX_HIGH = { cache => 1, verify => 1, verify_peername => "https" }; |
359 | our $TLS_CTX_HIGH = { cache => 1, verify => 1, verify_peername => "https" }; |
312 | |
360 | |
313 | sub http_request($$@) { |
361 | sub http_request($$@) { |
… | |
… | |
325 | while (my ($k, $v) = each %$hdr) { |
373 | while (my ($k, $v) = each %$hdr) { |
326 | $hdr{lc $k} = $v; |
374 | $hdr{lc $k} = $v; |
327 | } |
375 | } |
328 | } |
376 | } |
329 | |
377 | |
|
|
378 | # pseudo headers for all subsequent responses |
|
|
379 | my @pseudo = (URL => $url); |
|
|
380 | push @pseudo, Redirect => delete $arg{Redirect} if exists $arg{Redirect}; |
|
|
381 | |
330 | my $recurse = exists $arg{recurse} ? delete $arg{recurse} : $MAX_RECURSE; |
382 | my $recurse = exists $arg{recurse} ? delete $arg{recurse} : $MAX_RECURSE; |
331 | |
383 | |
332 | return $cb->(undef, { Status => 599, Reason => "Too many redirections", URL => $url }) |
384 | return $cb->(undef, { Status => 599, Reason => "Too many redirections", @pseudo }) |
333 | if $recurse < 0; |
385 | if $recurse < 0; |
334 | |
386 | |
335 | my $proxy = $arg{proxy} || $PROXY; |
387 | my $proxy = $arg{proxy} || $PROXY; |
336 | my $timeout = $arg{timeout} || $TIMEOUT; |
388 | my $timeout = $arg{timeout} || $TIMEOUT; |
337 | |
389 | |
338 | my ($uscheme, $uauthority, $upath, $query, $fragment) = |
390 | my ($uscheme, $uauthority, $upath, $query, $fragment) = |
339 | $url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?|; |
391 | $url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:(\?[^#]*))?(?:#(.*))?|; |
340 | |
392 | |
341 | $uscheme = lc $uscheme; |
393 | $uscheme = lc $uscheme; |
342 | |
394 | |
343 | my $uport = $uscheme eq "http" ? 80 |
395 | my $uport = $uscheme eq "http" ? 80 |
344 | : $uscheme eq "https" ? 443 |
396 | : $uscheme eq "https" ? 443 |
345 | : return $cb->(undef, { Status => 599, Reason => "Only http and https URL schemes supported", URL => $url }); |
397 | : return $cb->(undef, { Status => 599, Reason => "Only http and https URL schemes supported", @pseudo }); |
346 | |
398 | |
347 | $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x |
399 | $uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x |
348 | or return $cb->(undef, { Status => 599, Reason => "Unparsable URL", URL => $url }); |
400 | or return $cb->(undef, { Status => 599, Reason => "Unparsable URL", @pseudo }); |
349 | |
401 | |
350 | my $uhost = $1; |
402 | my $uhost = $1; |
351 | $uport = $2 if defined $2; |
403 | $uport = $2 if defined $2; |
352 | |
404 | |
|
|
405 | $hdr{host} = defined $2 ? "$uhost:$2" : "$uhost" |
|
|
406 | unless exists $hdr{host}; |
|
|
407 | |
353 | $uhost =~ s/^\[(.*)\]$/$1/; |
408 | $uhost =~ s/^\[(.*)\]$/$1/; |
354 | $upath .= "?$query" if length $query; |
409 | $upath .= $query if length $query; |
355 | |
410 | |
356 | $upath =~ s%^/?%/%; |
411 | $upath =~ s%^/?%/%; |
357 | |
412 | |
358 | # cookie processing |
413 | # cookie processing |
359 | if (my $jar = $arg{cookie_jar}) { |
414 | if (my $jar = $arg{cookie_jar}) { |
… | |
… | |
389 | my ($rhost, $rport, $rscheme, $rpath); # request host, port, path |
444 | my ($rhost, $rport, $rscheme, $rpath); # request host, port, path |
390 | |
445 | |
391 | if ($proxy) { |
446 | if ($proxy) { |
392 | ($rpath, $rhost, $rport, $rscheme) = ($url, @$proxy); |
447 | ($rpath, $rhost, $rport, $rscheme) = ($url, @$proxy); |
393 | |
448 | |
|
|
449 | $rscheme = "http" unless defined $rscheme; |
|
|
450 | |
394 | # don't support https requests over https-proxy transport, |
451 | # don't support https requests over https-proxy transport, |
395 | # can't be done with tls as spec'ed, unless you double-encrypt. |
452 | # can't be done with tls as spec'ed, unless you double-encrypt. |
396 | $rscheme = "http" if $uscheme eq "https" && $rscheme eq "https"; |
453 | $rscheme = "http" if $uscheme eq "https" && $rscheme eq "https"; |
397 | } else { |
454 | } else { |
398 | ($rhost, $rport, $rscheme, $rpath) = ($uhost, $uport, $uscheme, $upath); |
455 | ($rhost, $rport, $rscheme, $rpath) = ($uhost, $uport, $uscheme, $upath); |
399 | } |
456 | } |
400 | |
457 | |
401 | $hdr{"user-agent"} ||= $USERAGENT; |
458 | # leave out fragment and query string, just a heuristic |
402 | $hdr{referer} ||= "$uscheme://$uauthority$upath"; # leave out fragment and query string, just a heuristic |
459 | $hdr{referer} ||= "$uscheme://$uauthority$upath" unless exists $hdr{referer}; |
|
|
460 | $hdr{"user-agent"} ||= $USERAGENT unless exists $hdr{"user-agent"}; |
403 | |
461 | |
404 | $hdr{host} = "$uhost:$uport"; |
|
|
405 | $hdr{"content-length"} = length $arg{body}; |
462 | $hdr{"content-length"} = length $arg{body} |
|
|
463 | if length $arg{body} || $method ne "GET"; |
406 | |
464 | |
407 | my %state = (connect_guard => 1); |
465 | my %state = (connect_guard => 1); |
408 | |
466 | |
409 | _get_slot $uhost, sub { |
467 | _get_slot $uhost, sub { |
410 | $state{slot_guard} = shift; |
468 | $state{slot_guard} = shift; |
411 | |
469 | |
412 | return unless $state{connect_guard}; |
470 | return unless $state{connect_guard}; |
413 | |
471 | |
414 | $state{connect_guard} = AnyEvent::Socket::tcp_connect $rhost, $rport, sub { |
472 | my $tcp_connect = $arg{tcp_connect} |
|
|
473 | || do { require AnyEvent::Socket; \&AnyEvent::Socket::tcp_connect }; |
|
|
474 | |
|
|
475 | $state{connect_guard} = $tcp_connect->( |
|
|
476 | $rhost, |
|
|
477 | $rport, |
|
|
478 | sub { |
415 | $state{fh} = shift |
479 | $state{fh} = shift |
|
|
480 | or do { |
|
|
481 | my $err = "$!"; |
|
|
482 | %state = (); |
416 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "$!", URL => $url })); |
483 | return $cb->(undef, { Status => 599, Reason => $err, @pseudo }); |
|
|
484 | }; |
|
|
485 | |
417 | pop; # free memory, save a tree |
486 | pop; # free memory, save a tree |
418 | |
487 | |
419 | return unless delete $state{connect_guard}; |
488 | return unless delete $state{connect_guard}; |
420 | |
489 | |
421 | # get handle |
490 | # get handle |
422 | $state{handle} = new AnyEvent::Handle |
491 | $state{handle} = new AnyEvent::Handle |
423 | fh => $state{fh}, |
492 | fh => $state{fh}, |
|
|
493 | peername => $rhost, |
|
|
494 | tls_ctx => $arg{tls_ctx}, |
|
|
495 | # these need to be reconfigured on keepalive handles |
424 | timeout => $timeout, |
496 | timeout => $timeout, |
425 | peername => $rhost, |
497 | on_error => sub { |
426 | tls_ctx => $arg{tls_ctx}; |
498 | %state = (); |
|
|
499 | $cb->(undef, { Status => 599, Reason => $_[2], @pseudo }); |
|
|
500 | }, |
|
|
501 | on_eof => sub { |
|
|
502 | %state = (); |
|
|
503 | $cb->(undef, { Status => 599, Reason => "Unexpected end-of-file", @pseudo }); |
|
|
504 | }, |
|
|
505 | ; |
427 | |
506 | |
428 | # limit the number of persistent connections |
507 | # limit the number of persistent connections |
429 | # keepalive not yet supported |
508 | # keepalive not yet supported |
430 | if ($KA_COUNT{$_[1]} < $MAX_PERSISTENT_PER_HOST) { |
509 | # if ($KA_COUNT{$_[1]} < $MAX_PERSISTENT_PER_HOST) { |
431 | ++$KA_COUNT{$_[1]}; |
510 | # ++$KA_COUNT{$_[1]}; |
432 | $state{handle}{ka_count_guard} = AnyEvent::Util::guard { |
511 | # $state{handle}{ka_count_guard} = AnyEvent::Util::guard { |
433 | --$KA_COUNT{$_[1]} |
512 | # --$KA_COUNT{$_[1]} |
434 | }; |
513 | # }; |
435 | $hdr{connection} = "keep-alive"; |
514 | # $hdr{connection} = "keep-alive"; |
436 | } else { |
515 | # } else { |
437 | delete $hdr{connection}; |
516 | delete $hdr{connection}; |
438 | } |
517 | # } |
439 | |
518 | |
440 | # (re-)configure handle |
|
|
441 | $state{handle}->on_error (sub { |
|
|
442 | %state = (); |
|
|
443 | $cb->(undef, { Status => 599, Reason => $_[2], URL => $url }); |
|
|
444 | }); |
|
|
445 | $state{handle}->on_eof (sub { |
|
|
446 | %state = (); |
|
|
447 | $cb->(undef, { Status => 599, Reason => "Unexpected end-of-file", URL => $url }); |
|
|
448 | }); |
|
|
449 | |
|
|
450 | $state{handle}->starttls ("connect") if $rscheme eq "https"; |
519 | $state{handle}->starttls ("connect") if $rscheme eq "https"; |
451 | |
520 | |
452 | # handle actual, non-tunneled, request |
521 | # handle actual, non-tunneled, request |
453 | my $handle_actual_request = sub { |
522 | my $handle_actual_request = sub { |
454 | $state{handle}->starttls ("connect") if $uscheme eq "https" && !exists $state{handle}{tls}; |
523 | $state{handle}->starttls ("connect") if $uscheme eq "https" && !exists $state{handle}{tls}; |
455 | |
524 | |
456 | # send request |
525 | # send request |
457 | $state{handle}->push_write ( |
526 | $state{handle}->push_write ( |
458 | "$method $rpath HTTP/1.0\015\012" |
527 | "$method $rpath HTTP/1.0\015\012" |
459 | . (join "", map "\u$_: $hdr{$_}\015\012", keys %hdr) |
528 | . (join "", map "\u$_: $hdr{$_}\015\012", grep defined $hdr{$_}, keys %hdr) |
460 | . "\015\012" |
529 | . "\015\012" |
461 | . (delete $arg{body}) |
530 | . (delete $arg{body}) |
462 | ); |
|
|
463 | |
|
|
464 | %hdr = (); # reduce memory usage, save a kitten |
|
|
465 | |
|
|
466 | # status line |
|
|
467 | $state{handle}->push_read (line => $qr_nl, sub { |
|
|
468 | $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix |
|
|
469 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid server response ($_[1])", URL => $url })); |
|
|
470 | |
|
|
471 | my %hdr = ( # response headers |
|
|
472 | HTTPVersion => ",$1", |
|
|
473 | Status => ",$2", |
|
|
474 | Reason => ",$3", |
|
|
475 | URL => ",$url" |
|
|
476 | ); |
531 | ); |
477 | |
532 | |
478 | # headers, could be optimized a bit |
533 | # return if error occured during push_write() |
|
|
534 | return unless %state; |
|
|
535 | |
|
|
536 | %hdr = (); # reduce memory usage, save a kitten, also make it possible to re-use |
|
|
537 | |
|
|
538 | # status line and headers |
479 | $state{handle}->unshift_read (line => $qr_nlnl, sub { |
539 | $state{handle}->push_read (line => $qr_nlnl, sub { |
480 | for ("$_[1]\012") { |
540 | for ("$_[1]") { |
481 | y/\015//d; # weed out any \015, as they show up in the weirdest of places. |
541 | y/\015//d; # weed out any \015, as they show up in the weirdest of places. |
|
|
542 | |
|
|
543 | /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )? \015?\012/igxc |
|
|
544 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid server response", @pseudo })); |
|
|
545 | |
|
|
546 | push @pseudo, |
|
|
547 | HTTPVersion => $1, |
|
|
548 | Status => $2, |
|
|
549 | Reason => $3, |
|
|
550 | ; |
482 | |
551 | |
483 | # things seen, not parsed: |
552 | # things seen, not parsed: |
484 | # p3pP="NON CUR OTPi OUR NOR UNI" |
553 | # p3pP="NON CUR OTPi OUR NOR UNI" |
485 | |
554 | |
486 | $hdr{lc $1} .= ",$2" |
555 | $hdr{lc $1} .= ",$2" |
487 | while /\G |
556 | while /\G |
488 | ([^:\000-\037]+): |
557 | ([^:\000-\037]*): |
489 | [\011\040]* |
558 | [\011\040]* |
490 | ((?: [^\012]+ | \012[\011\040] )*) |
559 | ((?: [^\012]+ | \012[\011\040] )*) |
491 | \012 |
560 | \012 |
492 | /gxc; |
561 | /gxc; |
493 | |
562 | |
494 | /\G$/ |
563 | /\G$/ |
495 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Garbled response headers", URL => $url })); |
564 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Garbled response headers", @pseudo })); |
496 | } |
565 | } |
497 | |
566 | |
|
|
567 | # remove the "," prefix we added to all headers above |
498 | substr $_, 0, 1, "" |
568 | substr $_, 0, 1, "" |
499 | for values %hdr; |
569 | for values %hdr; |
|
|
570 | |
|
|
571 | # patch in all pseudo headers |
|
|
572 | %hdr = (%hdr, @pseudo); |
500 | |
573 | |
501 | # redirect handling |
574 | # redirect handling |
502 | # microsoft and other shitheads don't give a shit for following standards, |
575 | # microsoft and other shitheads don't give a shit for following standards, |
503 | # try to support some common forms of broken Location headers. |
576 | # try to support some common forms of broken Location headers. |
504 | if ($hdr{location} !~ /^(?: $ | [^:\/?\#]+ : )/x) { |
577 | if ($hdr{location} !~ /^(?: $ | [^:\/?\#]+ : )/x) { |
… | |
… | |
515 | } |
588 | } |
516 | |
589 | |
517 | my $redirect; |
590 | my $redirect; |
518 | |
591 | |
519 | if ($recurse) { |
592 | if ($recurse) { |
520 | if ($hdr{Status} =~ /^30[12]$/ && $method ne "POST") { |
593 | my $status = $hdr{Status}; |
521 | # apparently, mozilla et al. just change POST to GET here |
594 | |
522 | # more research is needed before we do the same |
595 | # industry standard is to redirect POST as GET for |
523 | $redirect = 1; |
596 | # 301, 302 and 303, in contrast to http/1.0 and 1.1. |
524 | } elsif ($hdr{Status} == 303) { |
597 | # also, the UA should ask the user for 301 and 307 and POST, |
|
|
598 | # industry standard seems to be to simply follow. |
|
|
599 | # we go with the industry standard. |
|
|
600 | if ($status == 301 or $status == 302 or $status == 303) { |
525 | # even http/1.1 is unclear on how to mutate the method |
601 | # HTTP/1.1 is unclear on how to mutate the method |
526 | $method = "GET" unless $method eq "HEAD"; |
602 | $method = "GET" unless $method eq "HEAD"; |
527 | $redirect = 1; |
603 | $redirect = 1; |
528 | } elsif ($hdr{Status} == 307 && $method =~ /^(?:GET|HEAD)$/) { |
604 | } elsif ($status == 307) { |
529 | $redirect = 1; |
605 | $redirect = 1; |
530 | } |
606 | } |
531 | } |
607 | } |
532 | |
608 | |
533 | my $finish = sub { |
609 | my $finish = sub { |
… | |
… | |
582 | |
658 | |
583 | redo if /\G\s*,/gc; |
659 | redo if /\G\s*,/gc; |
584 | } |
660 | } |
585 | } |
661 | } |
586 | |
662 | |
587 | if ($redirect) { |
663 | if ($redirect && exists $hdr{location}) { |
588 | # we ignore any errors, as it is very common to receive |
664 | # we ignore any errors, as it is very common to receive |
589 | # Content-Length != 0 but no actual body |
665 | # Content-Length != 0 but no actual body |
590 | # we also access %hdr, as $_[1] might be an erro |
666 | # we also access %hdr, as $_[1] might be an erro |
591 | http_request ($method => $hdr{location}, %arg, recurse => $recurse - 1, $cb); |
667 | http_request ( |
|
|
668 | $method => $hdr{location}, |
|
|
669 | %arg, |
|
|
670 | recurse => $recurse - 1, |
|
|
671 | Redirect => \@_, |
|
|
672 | $cb); |
592 | } else { |
673 | } else { |
593 | $cb->($_[0], $_[1]); |
674 | $cb->($_[0], $_[1]); |
594 | } |
675 | } |
595 | }; |
676 | }; |
596 | |
677 | |
597 | my $len = $hdr{"content-length"}; |
678 | my $len = $hdr{"content-length"}; |
598 | |
679 | |
599 | if (!$redirect && $arg{on_header} && !$arg{on_header}(\%hdr)) { |
680 | if (!$redirect && $arg{on_header} && !$arg{on_header}(\%hdr)) { |
600 | $finish->(undef, { Status => 598, Reason => "Request cancelled by on_header", URL => $url }); |
681 | $finish->(undef, { Status => 598, Reason => "Request cancelled by on_header", @pseudo }); |
601 | } elsif ( |
682 | } elsif ( |
602 | $hdr{Status} =~ /^(?:1..|204|304)$/ |
683 | $hdr{Status} =~ /^(?:1..|[23]04)$/ |
603 | or $method eq "HEAD" |
684 | or $method eq "HEAD" |
604 | or (defined $len && !$len) |
685 | or (defined $len && !$len) |
605 | ) { |
686 | ) { |
606 | # no body |
687 | # no body |
607 | $finish->("", \%hdr); |
688 | $finish->("", \%hdr); |
608 | } else { |
689 | } else { |
609 | # body handling, four different code paths |
690 | # body handling, four different code paths |
610 | # for want_body_handle, on_body (2x), normal (2x) |
691 | # for want_body_handle, on_body (2x), normal (2x) |
611 | # we might read too much here, but it does not matter yet (no pers. connections) |
692 | # we might read too much here, but it does not matter yet (no pers. connections) |
612 | if (!$redirect && $arg{want_body_handle}) { |
693 | if (!$redirect && $arg{want_body_handle}) { |
613 | $_[0]->on_eof (undef); |
694 | $_[0]->on_eof (undef); |
614 | $_[0]->on_error (undef); |
695 | $_[0]->on_error (undef); |
615 | $_[0]->on_read (undef); |
696 | $_[0]->on_read (undef); |
616 | |
697 | |
617 | $finish->(delete $state{handle}, \%hdr); |
698 | $finish->(delete $state{handle}, \%hdr); |
618 | |
699 | |
619 | } elsif ($arg{on_body}) { |
700 | } elsif ($arg{on_body}) { |
620 | $_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], URL => $url }) }); |
701 | $_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], @pseudo }) }); |
621 | if ($len) { |
702 | if ($len) { |
622 | $_[0]->on_eof (undef); |
703 | $_[0]->on_eof (undef); |
623 | $_[0]->on_read (sub { |
704 | $_[0]->on_read (sub { |
624 | $len -= length $_[0]{rbuf}; |
705 | $len -= length $_[0]{rbuf}; |
625 | |
706 | |
626 | $arg{on_body}(delete $_[0]{rbuf}, \%hdr) |
707 | $arg{on_body}(delete $_[0]{rbuf}, \%hdr) |
627 | or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", URL => $url }); |
708 | or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", @pseudo }); |
628 | |
709 | |
629 | $len > 0 |
710 | $len > 0 |
630 | or $finish->("", \%hdr); |
711 | or $finish->("", \%hdr); |
631 | }); |
712 | }); |
632 | } else { |
713 | } else { |
633 | $_[0]->on_eof (sub { |
714 | $_[0]->on_eof (sub { |
634 | $finish->("", \%hdr); |
715 | $finish->("", \%hdr); |
635 | }); |
716 | }); |
636 | $_[0]->on_read (sub { |
717 | $_[0]->on_read (sub { |
637 | $arg{on_body}(delete $_[0]{rbuf}, \%hdr) |
718 | $arg{on_body}(delete $_[0]{rbuf}, \%hdr) |
638 | or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", URL => $url }); |
719 | or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", @pseudo }); |
639 | }); |
720 | }); |
640 | } |
721 | } |
641 | } else { |
722 | } else { |
642 | $_[0]->on_eof (undef); |
723 | $_[0]->on_eof (undef); |
643 | |
724 | |
644 | if ($len) { |
725 | if ($len) { |
645 | $_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], URL => $url }) }); |
726 | $_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], @pseudo }) }); |
646 | $_[0]->on_read (sub { |
727 | $_[0]->on_read (sub { |
647 | $finish->((substr delete $_[0]{rbuf}, 0, $len, ""), \%hdr) |
728 | $finish->((substr delete $_[0]{rbuf}, 0, $len, ""), \%hdr) |
648 | if $len <= length $_[0]{rbuf}; |
729 | if $len <= length $_[0]{rbuf}; |
649 | }); |
730 | }); |
650 | } else { |
731 | } else { |
651 | $_[0]->on_error (sub { |
732 | $_[0]->on_error (sub { |
652 | $! == Errno::EPIPE |
733 | ($! == Errno::EPIPE || !$!) |
653 | ? $finish->(delete $_[0]{rbuf}, \%hdr) |
734 | ? $finish->(delete $_[0]{rbuf}, \%hdr) |
654 | : $finish->(undef, { Status => 599, Reason => $_[2], URL => $url }); |
735 | : $finish->(undef, { Status => 599, Reason => $_[2], @pseudo }); |
655 | }); |
736 | }); |
656 | $_[0]->on_read (sub { }); |
737 | $_[0]->on_read (sub { }); |
657 | } |
738 | } |
658 | } |
739 | } |
659 | } |
740 | } |
660 | }); |
741 | }); |
661 | }); |
742 | }; |
662 | }; |
|
|
663 | |
743 | |
664 | # now handle proxy-CONNECT method |
744 | # now handle proxy-CONNECT method |
665 | if ($proxy && $uscheme eq "https") { |
745 | if ($proxy && $uscheme eq "https") { |
666 | # oh dear, we have to wrap it into a connect request |
746 | # oh dear, we have to wrap it into a connect request |
667 | |
747 | |
668 | # maybe re-use $uauthority with patched port? |
748 | # maybe re-use $uauthority with patched port? |
669 | $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012Host: $uhost\015\012\015\012"); |
749 | $state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012Host: $uhost\015\012\015\012"); |
670 | $state{handle}->push_read (line => $qr_nlnl, sub { |
750 | $state{handle}->push_read (line => $qr_nlnl, sub { |
671 | $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix |
751 | $_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix |
672 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid proxy connect response ($_[1])", URL => $url })); |
752 | or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid proxy connect response ($_[1])", @pseudo })); |
673 | |
753 | |
674 | if ($2 == 200) { |
754 | if ($2 == 200) { |
675 | $rpath = $upath; |
755 | $rpath = $upath; |
676 | &$handle_actual_request; |
756 | &$handle_actual_request; |
677 | } else { |
757 | } else { |
678 | %state = (); |
758 | %state = (); |
679 | $cb->(undef, { Status => $2, Reason => $3, URL => $url }); |
759 | $cb->(undef, { Status => $2, Reason => $3, @pseudo }); |
|
|
760 | } |
680 | } |
761 | }); |
681 | }); |
|
|
682 | } else { |
762 | } else { |
683 | &$handle_actual_request; |
763 | &$handle_actual_request; |
|
|
764 | } |
|
|
765 | |
684 | } |
766 | }, |
685 | |
767 | $arg{on_prepare} || sub { $timeout } |
686 | }, sub { |
|
|
687 | $timeout |
|
|
688 | }; |
768 | ); |
689 | }; |
769 | }; |
690 | |
770 | |
691 | defined wantarray && AnyEvent::Util::guard { %state = () } |
771 | defined wantarray && AnyEvent::Util::guard { %state = () } |
692 | } |
772 | } |
693 | |
773 | |
… | |
… | |
707 | &http_request |
787 | &http_request |
708 | } |
788 | } |
709 | |
789 | |
710 | =back |
790 | =back |
711 | |
791 | |
|
|
792 | =head2 DNS CACHING |
|
|
793 | |
|
|
794 | AnyEvent::HTTP uses the AnyEvent::Socket::tcp_connect function for |
|
|
795 | the actual connection, which in turn uses AnyEvent::DNS to resolve |
|
|
796 | hostnames. The latter is a simple stub resolver and does no caching |
|
|
797 | on its own. If you want DNS caching, you currently have to provide |
|
|
798 | your own default resolver (by storing a suitable resolver object in |
|
|
799 | C<$AnyEvent::DNS::RESOLVER>). |
|
|
800 | |
712 | =head2 GLOBAL FUNCTIONS AND VARIABLES |
801 | =head2 GLOBAL FUNCTIONS AND VARIABLES |
713 | |
802 | |
714 | =over 4 |
803 | =over 4 |
715 | |
804 | |
716 | =item AnyEvent::HTTP::set_proxy "proxy-url" |
805 | =item AnyEvent::HTTP::set_proxy "proxy-url" |
717 | |
806 | |
718 | Sets the default proxy server to use. The proxy-url must begin with a |
807 | Sets the default proxy server to use. The proxy-url must begin with a |
719 | string of the form C<http://host:port> (optionally C<https:...>). |
808 | string of the form C<http://host:port> (optionally C<https:...>), croaks |
|
|
809 | otherwise. |
|
|
810 | |
|
|
811 | To clear an already-set proxy, use C<undef>. |
|
|
812 | |
|
|
813 | =item $date = AnyEvent::HTTP::format_date $timestamp |
|
|
814 | |
|
|
815 | Takes a POSIX timestamp (seconds since the epoch) and formats it as a HTTP |
|
|
816 | Date (RFC 2616). |
|
|
817 | |
|
|
818 | =item $timestamp = AnyEvent::HTTP::parse_date $date |
|
|
819 | |
|
|
820 | Takes a HTTP Date (RFC 2616) and returns the corresponding POSIX |
|
|
821 | timestamp, or C<undef> if the date cannot be parsed. |
720 | |
822 | |
721 | =item $AnyEvent::HTTP::MAX_RECURSE |
823 | =item $AnyEvent::HTTP::MAX_RECURSE |
722 | |
824 | |
723 | The default value for the C<recurse> request parameter (default: C<10>). |
825 | The default value for the C<recurse> request parameter (default: C<10>). |
724 | |
826 | |
725 | =item $AnyEvent::HTTP::USERAGENT |
827 | =item $AnyEvent::HTTP::USERAGENT |
726 | |
828 | |
727 | The default value for the C<User-Agent> header (the default is |
829 | The default value for the C<User-Agent> header (the default is |
728 | C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>). |
830 | C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>). |
729 | |
831 | |
730 | =item $AnyEvent::HTTP::MAX_PERSISTENT |
832 | =item $AnyEvent::HTTP::MAX_PER_HOST |
731 | |
833 | |
732 | The maximum number of persistent connections to keep open (default: 8). |
834 | The maximum number of concurrent connections to the same host (identified |
|
|
835 | by the hostname). If the limit is exceeded, then the additional requests |
|
|
836 | are queued until previous connections are closed. |
733 | |
837 | |
734 | Not implemented currently. |
838 | The default value for this is C<4>, and it is highly advisable to not |
735 | |
839 | increase it. |
736 | =item $AnyEvent::HTTP::PERSISTENT_TIMEOUT |
|
|
737 | |
|
|
738 | The maximum time to cache a persistent connection, in seconds (default: 2). |
|
|
739 | |
|
|
740 | Not implemented currently. |
|
|
741 | |
840 | |
742 | =item $AnyEvent::HTTP::ACTIVE |
841 | =item $AnyEvent::HTTP::ACTIVE |
743 | |
842 | |
744 | The number of active connections. This is not the number of currently |
843 | The number of active connections. This is not the number of currently |
745 | running requests, but the number of currently open and non-idle TCP |
844 | running requests, but the number of currently open and non-idle TCP |
… | |
… | |
747 | |
846 | |
748 | =back |
847 | =back |
749 | |
848 | |
750 | =cut |
849 | =cut |
751 | |
850 | |
|
|
851 | our @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); |
|
|
852 | our @weekday = qw(Sun Mon Tue Wed Thu Fri Sat); |
|
|
853 | |
|
|
854 | sub format_date($) { |
|
|
855 | my ($time) = @_; |
|
|
856 | |
|
|
857 | # RFC 822/1123 format |
|
|
858 | my ($S, $M, $H, $mday, $mon, $year, $wday, $yday, undef) = gmtime $time; |
|
|
859 | |
|
|
860 | sprintf "%s, %02d %s %04d %02d:%02d:%02d GMT", |
|
|
861 | $weekday[$wday], $mday, $month[$mon], $year + 1900, |
|
|
862 | $H, $M, $S; |
|
|
863 | } |
|
|
864 | |
|
|
865 | sub parse_date($) { |
|
|
866 | my ($date) = @_; |
|
|
867 | |
|
|
868 | my ($d, $m, $y, $H, $M, $S); |
|
|
869 | |
|
|
870 | if ($date =~ /^[A-Z][a-z][a-z], ([0-9][0-9]) ([A-Z][a-z][a-z]) ([0-9][0-9][0-9][0-9]) ([0-9][0-9]):([0-9][0-9]):([0-9][0-9]) GMT$/) { |
|
|
871 | # RFC 822/1123, required by RFC 2616 |
|
|
872 | ($d, $m, $y, $H, $M, $S) = ($1, $2, $3, $4, $5, $6); |
|
|
873 | |
|
|
874 | } elsif ($date =~ /^[A-Z][a-z]+, ([0-9][0-9])-([A-Z][a-z][a-z])-([0-9][0-9]) ([0-9][0-9]):([0-9][0-9]):([0-9][0-9]) GMT$/) { |
|
|
875 | # RFC 850 |
|
|
876 | ($d, $m, $y, $H, $M, $S) = ($1, $2, $3 < 69 ? $3 + 2000 : $3 + 1900, $4, $5, $6); |
|
|
877 | |
|
|
878 | } elsif ($date =~ /^[A-Z][a-z][a-z] ([A-Z][a-z][a-z]) ([0-9 ][0-9]) ([0-9][0-9]):([0-9][0-9]):([0-9][0-9]) ([0-9][0-9][0-9][0-9])$/) { |
|
|
879 | # ISO C's asctime |
|
|
880 | ($d, $m, $y, $H, $M, $S) = ($2, $1, $6, $3, $4, $5); |
|
|
881 | } |
|
|
882 | # other formats fail in the loop below |
|
|
883 | |
|
|
884 | for (0..11) { |
|
|
885 | if ($m eq $month[$_]) { |
|
|
886 | require Time::Local; |
|
|
887 | return Time::Local::timegm ($S, $M, $H, $d, $_, $y); |
|
|
888 | } |
|
|
889 | } |
|
|
890 | |
|
|
891 | undef |
|
|
892 | } |
|
|
893 | |
752 | sub set_proxy($) { |
894 | sub set_proxy($) { |
|
|
895 | if (length $_[0]) { |
753 | $PROXY = [$2, $3 || 3128, $1] if $_[0] =~ m%^(https?):// ([^:/]+) (?: : (\d*) )?%ix; |
896 | $_[0] =~ m%^(https?):// ([^:/]+) (?: : (\d*) )?%ix |
|
|
897 | or Carp::croak "$_[0]: invalid proxy URL"; |
|
|
898 | $PROXY = [$2, $3 || 3128, $1] |
|
|
899 | } else { |
|
|
900 | undef $PROXY; |
|
|
901 | } |
754 | } |
902 | } |
755 | |
903 | |
756 | # initialise proxy from environment |
904 | # initialise proxy from environment |
|
|
905 | eval { |
757 | set_proxy $ENV{http_proxy}; |
906 | set_proxy $ENV{http_proxy}; |
|
|
907 | }; |
|
|
908 | |
|
|
909 | =head2 SOCKS PROXIES |
|
|
910 | |
|
|
911 | Socks proxies are not directly supported by AnyEvent::HTTP. You can |
|
|
912 | compile your perl to support socks, or use an external program such as |
|
|
913 | F<socksify> (dante) or F<tsocks> to make your program use a socks proxy |
|
|
914 | transparently. |
|
|
915 | |
|
|
916 | Alternatively, for AnyEvent::HTTP only, you can use your own |
|
|
917 | C<tcp_connect> function that does the proxy handshake - here is an example |
|
|
918 | that works with socks4a proxies: |
|
|
919 | |
|
|
920 | use Errno; |
|
|
921 | use AnyEvent::Util; |
|
|
922 | use AnyEvent::Socket; |
|
|
923 | use AnyEvent::Handle; |
|
|
924 | |
|
|
925 | # host, port and username of/for your socks4a proxy |
|
|
926 | my $socks_host = "10.0.0.23"; |
|
|
927 | my $socks_port = 9050; |
|
|
928 | my $socks_user = ""; |
|
|
929 | |
|
|
930 | sub socks4a_connect { |
|
|
931 | my ($host, $port, $connect_cb, $prepare_cb) = @_; |
|
|
932 | |
|
|
933 | my $hdl = new AnyEvent::Handle |
|
|
934 | connect => [$socks_host, $socks_port], |
|
|
935 | on_prepare => sub { $prepare_cb->($_[0]{fh}) }, |
|
|
936 | on_error => sub { $connect_cb->() }, |
|
|
937 | ; |
|
|
938 | |
|
|
939 | $hdl->push_write (pack "CCnNZ*Z*", 4, 1, $port, 1, $socks_user, $host); |
|
|
940 | |
|
|
941 | $hdl->push_read (chunk => 8, sub { |
|
|
942 | my ($hdl, $chunk) = @_; |
|
|
943 | my ($status, $port, $ipn) = unpack "xCna4", $chunk; |
|
|
944 | |
|
|
945 | if ($status == 0x5a) { |
|
|
946 | $connect_cb->($hdl->{fh}, (format_address $ipn) . ":$port"); |
|
|
947 | } else { |
|
|
948 | $! = Errno::ENXIO; $connect_cb->(); |
|
|
949 | } |
|
|
950 | }); |
|
|
951 | |
|
|
952 | $hdl |
|
|
953 | } |
|
|
954 | |
|
|
955 | Use C<socks4a_connect> instead of C<tcp_connect> when doing C<http_request>s, |
|
|
956 | possibly after switching off other proxy types: |
|
|
957 | |
|
|
958 | AnyEvent::HTTP::set_proxy undef; # usually you do not want other proxies |
|
|
959 | |
|
|
960 | http_get 'http://www.google.com', tcp_connect => \&socks4a_connect, sub { |
|
|
961 | my ($data, $headers) = @_; |
|
|
962 | ... |
|
|
963 | }; |
758 | |
964 | |
759 | =head1 SEE ALSO |
965 | =head1 SEE ALSO |
760 | |
966 | |
761 | L<AnyEvent>. |
967 | L<AnyEvent>. |
762 | |
968 | |