Debian Codegraph @

src/.svn/text-base/http.pl.svn-base

raw
1 #BSD Copyright (c) 2009, Jeff Forristal (wiretrip.net)
2 #BSD All rights reserved.
3 #BSD
4 #BSD Redistribution and use in source and binary forms, with or without
5 #BSD modification, are permitted provided that the following conditions
6 #BSD are met:
7 #BSD
8 #BSD - Redistributions of source code must retain the above copyright
9 #BSD notice, this list of conditions and the following disclaimer.
10 #BSD
11 #BSD - Redistributions in binary form must reproduce the above copyright
12 #BSD notice, this list of conditions and the following disclaimer in the
13 #BSD documentation and/or other materials provided with the distribution.
14 #BSD
15 #BSD THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 #BSD "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 #BSD LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 #BSD FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 #BSD COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 #BSD INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 #BSD BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 #BSD LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 #BSD CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 #BSD LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
25 #BSD ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 #BSD POSSIBILITY OF SUCH DAMAGE.
27
28 ##################################################################
29
30 # cluster global variables
31 %http_host_cache = ();
32
33 ##################################################################
34
35 =item B<http_new_request>
36
37 Params: %parameters
38
39 Return: \%request_hash
40
41 This function basically 'objectifies' the creation of whisker
42 request hash objects. You would call it like:
43
44 $req = http_new_request( host=>'www.example.com', uri=>'/' )
45
46 where 'host' and 'uri' can be any number of {whisker} hash
47 control values (see http_init_request for default list).
48
49 =cut
50
51 sub http_new_request {
52 my %X = @_;
53 my ( $k, $v, %RET, %RES );
54
55 http_init_request( \%RET );
56 while ( ( $k, $v ) = each(%X) ) {
57 $RET{whisker}->{$k} = $v;
58 }
59 $RES{whisker} = {};
60 $RES{whisker}->{MAGIC} = 31340;
61 $RES{whisker}->{uri} = '';
62 return ( \%RET, \%RES ) if wantarray();
63 return \%RET;
64 }
65
66 ##################################################################
67
68 =item B<http_new_response>
69
70 Params: [none]
71
72 Return: \%response_hash
73
74 This function basically 'objectifies' the creation of whisker
75 response hash objects. You would call it like:
76
77 $resp = http_new_response()
78
79 =cut
80
81 sub http_new_response {
82 my %RET;
83 $RET{whisker} = {};
84 $RET{whisker}->{MAGIC} = 31340;
85 $RET{whisker}->{uri} = '';
86 return \%RET;
87 }
88
89 ##################################################################
90
91 =item B<http_init_request>
92
93 Params: \%request_hash_to_initialize
94
95 Return: Nothing (modifies input hash)
96
97 Sets default values to the input hash for use. Sets the host to
98 'localhost', port 80, request URI '/', using HTTP 1.1 with GET
99 method. The timeout is set to 10 seconds, no proxies are defined, and all
100 URI formatting is set to standard HTTP syntax. It also sets the
101 Connection (Keep-Alive) and User-Agent headers.
102
103 NOTICE!! It's important to use http_init_request before calling
104 http_do_request, or http_do_request might puke. Thus, a special magic
105 value is placed in the hash to let http_do_request know that the hash has
106 been properly initialized. If you really must 'roll your own' and not use
107 http_init_request before you call http_do_request, you will at least need
108 to set the MAGIC value (amongst other things).
109
110 =cut
111
112 sub http_init_request { # doesn't return anything
113 my ($hin) = shift;
114
115 return if ( !( defined $hin && ref($hin) ) );
116 %$hin = (); # clear control hash
117
118 # control values
119 $$hin{whisker} = {
120 http_space1 => ' ',
121 http_space2 => ' ',
122 version => '1.1',
123 method => 'GET',
124 protocol => 'HTTP',
125 port => 80,
126 uri => '/',
127 uri_prefix => '',
128 uri_postfix => '',
129 uri_param_sep => '?',
130 host => 'localhost',
131 timeout => 10,
132 include_host_in_uri => 0,
133 ignore_duplicate_headers => 1,
134 normalize_incoming_headers => 1,
135 lowercase_incoming_headers => 0,
136 require_newline_after_headers => 0,
137 invalid_protocol_return_value => 1,
138 ssl => 0,
139 ssl_save_info => 0,
140 http_eol => "\x0d\x0a",
141 force_close => 0,
142 force_open => 0,
143 retry => 1,
144 trailing_slurp => 0,
145 force_bodysnatch => 0,
146 max_size => 0,
147 MAGIC => 31339
148 };
149
150 # default header values
151 $$hin{'Connection'} = 'Keep-Alive';
152 $$hin{'User-Agent'} = "Mozilla (libwhisker/$LW2::VERSION)";
153 }
154
155 ##################################################################
156
157 =item B<http_do_request>
158
159 Params: \%request, \%response [, \%configs]
160
161 Return: >=1 if error; 0 if no error (also modifies response hash)
162
163 *THE* core function of libwhisker. http_do_request actually performs
164 the HTTP request, using the values submitted in %request, and placing result
165 values in %response. This allows you to resubmit %request in subsequent
166 requests (%response is automatically cleared upon execution). You can
167 submit 'runtime' config directives as %configs, which will be spliced into
168 $hin{whisker}->{} before anything else. That means you can do:
169
170 LW2::http_do_request(\%req,\%resp,{'uri'=>'/cgi-bin/'});
171
172 This will set $req{whisker}->{'uri'}='/cgi-bin/' before execution, and
173 provides a simple shortcut (note: it does modify %req).
174
175 This function will also retry any requests that bomb out during the
176 transaction (but not during the connecting phase). This is controlled
177 by the {whisker}->{retry} value. Also note that the returned error
178 message in hout is the *last* error received. All retry errors are
179 put into {whisker}->{retry_errors}, which is an anonymous array.
180
181 Also note that all NTLM auth logic is implemented in http_do_request().
182 NTLM requires multiple requests in order to work correctly, and so this
183 function attempts to wrap that and make it all transparent, so that the
184 final end result is what's passed to the application.
185
186 This function will return 0 on success, 1 on HTTP protocol error, and 2
187 on non-recoverable network connection error (you can retry error 1, but
188 error 2 means that the server is totally unreachable and there's no
189 point in retrying).
190
191 =cut
192
193 sub http_do_request {
194 my ( $hin, $hout ) = ( shift, shift );
195
196 return 2 if ( !( defined $hin && ref($hin) ) );
197 return 2 if ( !( defined $hout && ref($hout) ) );
198
199 # setup hash
200 %$hout = ();
201 $$hout{whisker} = {};
202 $$hout{whisker}->{'MAGIC'} = 31340;
203 $$hout{whisker}->{uri} = $$hin{whisker}->{uri};
204
205 if ( !defined $$hin{whisker}
206 || !defined $$hin{whisker}->{'MAGIC'}
207 || $$hin{whisker}->{'MAGIC'} != 31339 )
208 {
209 $$hout{whisker}->{error} = 'Input hash not initialized';
210 return 2;
211 }
212
213 if ( defined $_[0] ) { # handle extra params
214 my %hashref;
215 if ( ref( $_[0] ) eq 'HASH' ) { %hashref = %{ $_[0] }; }
216 else { %hashref = @_; }
217 $$hin{whisker}->{$_} = $hashref{$_} foreach ( keys %hashref );
218 }
219 if ( defined $$hin{whisker}->{'anti_ids'} ) { # handle anti_ids
220 my %copy = %$hin;
221 $copy{whisker} = {};
222 %{ $copy{whisker} } = %{ $$hin{whisker} };
223 encode_anti_ids( \%copy, $$hin{whisker}->{'anti_ids'} );
224 $hin = \%copy;
225 }
226
227 # find/setup stream
228 my $cache_key = stream_key($hin);
229 my $stream;
230 if ( !defined $http_host_cache{$cache_key} ) {
231 $stream = stream_new($hin);
232 $http_host_cache{$cache_key} = $stream;
233 }
234 else {
235 $stream = $http_host_cache{$cache_key};
236 }
237 if ( !defined $stream ) {
238 $$hout{whisker}->{error} = 'unable to allocate stream';
239 return 2;
240 }
241
242 my $retry_count = $$hin{whisker}->{retry};
243 my $puke_flag = 0;
244 my $ret = 1;
245 do { # retries wrapper
246 my ( $aret, $pass );
247
248 if ( !$stream->{valid}->() ) {
249 $stream->{clearall}->();
250 if ( !$stream->{open}->($hin) ) {
251 $$hout{whisker}->{error} =
252 'opening stream: ' . $stream->{error};
253 $$hout{whisker}->{error} .=
254 '(reconnect problem after prior request)'
255 if ($puke_flag);
256 return 2;
257 }
258
259 # freshly open stream/connection, handle auth
260 if ( defined $$hin{whisker}->{proxy_host}
261 && defined $$hin{whisker}->{auth_proxy_callback} )
262 {
263 $aret =
264 $$hin{whisker}->{auth_proxy_callback}
265 ->( $stream, $hin, $hout );
266 return $aret if ( $aret != 0 ); # proxy auth error
267 }
268 if ( defined $$hin{whisker}->{auth_callback} ) {
269 $aret =
270 $$hin{whisker}->{auth_callback}->( $stream, $hin, $hout );
271 return 0 if ( $aret == 200 ); # auth not needed?
272 return $aret if ( $aret != 0 ); # auth error
273 }
274 }
275
276 _ssl_save_info( $hout, $stream )
277 if ( $$hin{whisker}->{ssl} > 0
278 && $$hin{whisker}->{ssl_save_info} > 0 );
279
280 $ret = _http_do_request_ex( $stream, $hin, $hout );
281 $puke_flag++
282 if ( $ret == 1 && defined( $$hout{whisker}->{http_data_sent} ) );
283 return $ret
284 if ( $ret == 0 || $ret == 2 ); # success or fatal socket error
285 $retry_count--;
286 } while ( $retry_count >= 0 );
287
288 # if we get here, we still had errors, but no more retries
289 return $ret;
290
291 }
292
293 ##################################################################
294
295 sub _http_do_request_ex {
296 my ( $stream, $hin, $hout, $raw ) = @_;
297
298 return 2 if ( !defined $stream );
299 return 2 if ( !( defined $hin && ref($hin) ) );
300 return 2 if ( !( defined $hout && ref($hout) ) );
301 my $W = $hin->{whisker};
302
303 # setup hash, if needed
304 if ( !defined $$hout{whisker}->{MAGIC}
305 || $$hout{whisker}->{MAGIC} != 31340 )
306 {
307 %$hout = ();
308 $$hout{whisker} = {};
309 $$hout{whisker}->{'MAGIC'} = 31340;
310 $$hout{whisker}->{uri} = $$hin{whisker}->{uri};
311 }
312
313 ##### construct and send request
314 $stream->{clear}->();
315
316 if ( defined $raw && ref($raw) ) {
317 $stream->{queue}->($$raw);
318
319 }
320 else {
321 $stream->{queue}->( http_req2line($hin) );
322
323 if ( $$W{version} ne '0.9' ) {
324 $stream->{queue}->( http_construct_headers($hin) );
325 $stream->{queue}->( $$W{raw_header_data} )
326 if ( defined $$W{raw_header_data} );
327 $stream->{queue}->( $$W{http_eol} );
328 $stream->{queue}->( $$W{data} ) if ( defined $$W{data} );
329 } # http 0.9 support
330 }
331
332 # good time to fingerprint, if requested
333 if ( defined $$W{request_fingerprint} ) {
334 $$hout{whisker}->{request_fingerprint} =
335 'md5:' . md5( $stream->{bufout} )
336 if ( $$W{request_fingerprint} eq 'md5' );
337 $$hout{whisker}->{request_fingerprint} =
338 'md4:' . md4( $stream->{bufout} )
339 if ( $$W{request_fingerprint} eq 'md4' );
340 }
341
342 # all data is wrangled...actually send it now
343 if ( !$stream->{'write'}->() ) {
344 $$hout{whisker}->{'error'} = 'sending request: ' . $stream->{error};
345 $stream->{'close'}->();
346 return 1;
347 }
348
349 # needed for SSL requests
350 # NOTE: this is disabled because it's just a noop anyways
351 # $stream->{writedone}->();
352
353 $$hout{whisker}->{http_data_sent} = 1;
354 $$hout{whisker}->{'lowercase_incoming_headers'} =
355 $$W{'lowercase_incoming_headers'};
356
357 ##### read and parse response
358 my @H;
359 if ( $$W{'version'} ne '0.9' ) {
360 do { # catch '100 Continue' responses
361 my $resp = _http_getline($stream);
362
363 if ( !defined $resp ) {
364 $$hout{whisker}->{error} = 'error reading HTTP response';
365 $$hout{whisker}->{data} = $stream->{bufin};
366 $stream->{'close'}->();
367 return 1;
368 }
369
370 $$hout{whisker}->{'raw_header_data'} .= $resp
371 if ( defined $$W{'save_raw_headers'} );
372
373 if ( $resp !~
374 /^([^\/]+)\/(\d\.\d)([ \t]+)(\d+)([ \t]*)(.*?)([\r\n]+)/ )
375 {
376 $$hout{whisker}->{'error'} = 'invalid HTTP response';
377 $$hout{whisker}->{'data'} = $resp;
378 while ( defined( $_ = _http_getline($stream) ) ) {
379 $$hout{whisker}->{'data'} .= $_;
380 }
381 $stream->{'close'}->();
382 return $$W{'invalid_protocol_return_value'} || 1;
383 }
384
385 $$hout{whisker}->{protocol} = $1;
386 $$hout{whisker}->{version} = $2;
387 $$hout{whisker}->{http_space1} = $3;
388 $$hout{whisker}->{code} = $4;
389 $$hout{whisker}->{http_space2} = $5;
390 $$hout{whisker}->{message} = $6;
391 $$hout{whisker}->{http_eol} = $7;
392 $$hout{whisker}->{'100_continue'}++ if ( $4 == 100 );
393
394 @H = http_read_headers( $stream, $hin, $hout );
395 if ( !$H[0] ) {
396 $$hout{whisker}->{'error'} =
397 'Error in reading headers: ' . $H[1];
398 $stream->{'close'}->();
399 return 1;
400 }
401
402 if ( !defined $H[3] ) { # connection
403 my ($t) = utils_find_lowercase_key( $hin, 'connection' );
404 $H[3] = $t || 'close';
405 }
406
407 } while ( $$hout{whisker}->{'code'} == 100 );
408
409 }
410 else { # http ver 0.9, we need to fake it since headers are not sent
411 $$hout{whisker}->{version} = '0.9';
412 $$hout{whisker}->{code} = 200;
413 $$hout{whisker}->{message} = '';
414 $H[3] = 'close';
415 }
416
417 if ( $$hout{whisker}->{code}==404 && defined $$W{'shortcut_on_404'} ) {
418 $stream->{'close'}->();
419 }
420 elsif ( defined $$W{data_sock} ) {
421 $$hout{whisker}->{data_sock} = $stream->{sock};
422 $$hout{whisker}->{data_stream} = $stream;
423 }
424 else {
425 if (
426 $$W{'force_bodysnatch'}
427 || ( $$W{'method'} ne 'HEAD'
428 && $$hout{whisker}->{'code'} != 206
429 && $$hout{whisker}->{'code'} != 102 )
430 )
431 {
432 return 1
433 if ( !http_read_body( $stream, $hin, $hout, $H[1], $H[2] ) );
434
435 # {hide_chunked_responses} stuff follows
436 if ( lc( $H[1] ) eq 'chunked'
437 && defined $$hin{whisker}->{hide_chunked_responses}
438 && $$hin{whisker}->{hide_chunked_responses} == 1
439 && !defined $$hin{whisker}->{save_raw_chunks} )
440 {
441 $$hout{'Content-Length'} = length( $$hout{whisker}->{data} );
442 utils_delete_lowercase_key( $hout, 'transfer-encoding' );
443 my $new = [];
444 my $cl = 0;
445 foreach ( @{ $$hout{whisker}->{header_order} } ) {
446 my $l = lc($_);
447 if ( $l eq 'content-length' ) {
448 $cl++;
449 next if ( $cl > 1 );
450 }
451 push @$new, $_ if ( $l ne 'transfer-encoding' );
452 }
453 push @$new, 'Content-Length' if ( $cl == 0 );
454 $$hout{whisker}->{header_order} = $new;
455 }
456 }
457
458 my ($ch) = LW2::utils_find_lowercase_key( $hin, 'connection' );
459 my $cl = 0;
460 $cl++
461 if (
462 (
463 lc( $H[3] ) ne 'keep-alive' || ( defined $ch
464 && $ch =~ m/close/i )
465 )
466 && $$W{'force_open'} != 1
467 );
468 $cl++ if ( $$W{'force_close'} > 0 || $stream->{forceclose} > 0 );
469 $cl++ if ( $$W{'ssl'} > 0 && $LW_SSL_KEEPALIVE == 0 );
470 $stream->{'close'}->() if ($cl);
471 }
472
473 if ( defined $$W{'header_delete_on_success'}
474 && ref( $$W{'header_delete_on_success'} ) )
475 {
476 foreach ( @{ $$W{'header_delete_on_success'} } ) {
477 delete $hin->{$_} if ( exists $hin->{$_} );
478 }
479 delete $$W{header_delete_on_success};
480 }
481
482 $stream->{reqs}++;
483 $$hout{whisker}->{'stats_reqs'} = $stream->{reqs};
484 $$hout{whisker}->{'stats_syns'} = $stream->{syns};
485 $$hout{whisker}->{'socket_state'} = $stream->{state};
486 delete $$hout{whisker}->{'error'}; # no error
487 return 0;
488
489 }
490
491 ##################################################################
492
493 =item B<http_req2line>
494
495 Params: \%request, $uri_only_switch
496
497 Return: $request
498
499 req2line is used internally by http_do_request, as well as provides a
500 convienient way to turn a %request configuration into an actual HTTP request
501 line. If $switch is set to 1, then the returned $request will be the URI
502 only ('/requested/page.html'), versus the entire HTTP request ('GET
503 /requested/page.html HTTP/1.0\n\n'). Also, if the 'full_request_override'
504 whisker config variable is set in %hin, then it will be returned instead
505 of the constructed URI.
506
507 =cut
508
509 sub http_req2line {
510 my ( $S, $hin, $UO ) = ( '', @_ );
511 $UO ||= 0;
512
513 # notice: full_request_override can play havoc with proxy settings
514 if ( defined $$hin{whisker}->{'full_request_override'} ) {
515 return $$hin{whisker}->{'full_request_override'};
516
517 }
518 else { # notice the components of a request--this is for flexibility
519 if ( $UO != 1 ) {
520 $S .= $$hin{whisker}->{'method'} . $$hin{whisker}->{'http_space1'};
521 if ( $$hin{whisker}->{'include_host_in_uri'} > 0 ) {
522 if ( $$hin{whisker}->{'ssl'} == 1 ) {
523 $S .= 'https://';
524 }
525 else {
526 $S .= 'http://';
527 }
528
529 if ( defined $$hin{whisker}->{'uri_user'} ) {
530 $S .= $$hin{whisker}->{'uri_user'};
531 if ( defined $$hin{whisker}->{'uri_password'} ) {
532 $S .= ':' . $$hin{whisker}->{'uri_password'};
533 }
534 $S .= '@';
535 }
536
537 $S .= $$hin{whisker}->{'host'} . ':' . $$hin{whisker}->{'port'};
538 }
539 }
540
541 $S .=
542 $$hin{whisker}->{'uri_prefix'}
543 . $$hin{whisker}->{'uri'}
544 . $$hin{whisker}->{'uri_postfix'};
545
546 if ( defined $$hin{whisker}->{'parameters'}
547 && $$hin{whisker}->{'parameters'} ne '' )
548 {
549 $S .=
550 $$hin{whisker}->{'uri_param_sep'}
551 . $$hin{whisker}->{'parameters'};
552 }
553
554 if ( $UO != 1 ) {
555 if ( $$hin{whisker}->{'version'} ne '0.9' ) {
556 $S .=
557 $$hin{whisker}->{'http_space2'}
558 . $$hin{whisker}->{'protocol'} . '/'
559 . $$hin{whisker}->{'version'};
560 }
561 $S .= $$hin{whisker}->{'http_eol'};
562 }
563 }
564 return $S;
565 }
566
567 ##################################################################
568
569 =item B<http_resp2line>
570
571 Params: \%response
572
573 Return: $response
574
575 http_resp2line provides a convienient way to turn a %response hash back
576 into the original HTTP response line.
577
578 =cut
579
580 sub http_resp2line {
581 my $hout = shift;
582 my $out = '';
583 return undef if ( !defined $hout || !ref($hout) );
584 return undef if ( $hout->{whisker}->{MAGIC} != 31340 );
585 $out .= $$hout{whisker}->{protocol};
586 $out .= '/';
587 $out .= $$hout{whisker}->{version};
588 $out .= $$hout{whisker}->{http_space1};
589 $out .= $$hout{whisker}->{code};
590 $out .= $$hout{whisker}->{http_space2};
591 $out .= $$hout{whisker}->{message};
592 $out .= $$hout{whisker}->{http_eol};
593 return $out;
594 }
595
596 ##################################################################
597
598 sub _http_getline {
599 my $stream = shift;
600 my ( $str, $t, $bc ) = ( '', 0, 0 );
601
602 $t = index( $stream->{bufin}, "\n", 0 );
603 while ( $t < 0 ) {
604 return undef if !$stream->{read}->() ||
605 length($stream->{bufin}) == $bc;
606 $t = index( $stream->{bufin}, "\n", 0 );
607 $bc = length( $stream->{bufin} );
608 }
609
610 my $r = substr( $stream->{bufin}, 0, $t + 1 );
611 $stream->{bufin} = substr( $stream->{bufin}, $t + 1 );
612
613 # substr($stream->{bufin},0,$t+1)='';
614 return $r;
615 }
616
617 ##################################################################
618
619 sub _http_get { # read from socket w/ timeouts
620 my ( $stream, $amount ) = @_;
621 my ( $str, $t, $b ) = ( '', '', 0 );
622
623 while ( $amount > length( $stream->{bufin} ) ) {
624 return undef if !$stream->{read}->() ||
625 length( $stream->{bufin} ) == $b;
626 $b = length( $stream->{bufin} );
627 }
628
629 my $r = substr( $stream->{bufin}, 0, $amount );
630 $stream->{bufin} = substr( $stream->{bufin}, $amount );
631
632 # substr($stream->{bufin},0,$amount)='';
633 return $r;
634 }
635
636 ##################################################################
637
638 sub _http_getall {
639 my ( $tmp, $b, $stream, $max_size ) = ('', 0, @_);
640
641 while ( $stream->{read}->() && length( $stream->{bufin} ) != $b) {
642 last if ( $max_size && length( $stream->{bufin} ) >= $max_size );
643 $b = length( $stream->{bufin} );
644 }
645 ( $tmp, $stream->{bufin} ) = ( $stream->{bufin}, '' );
646 $tmp = substr($tmp, 0, $max_size) if($max_size &&
647 length($tmp) > $max_size);
648 return $tmp;
649 }
650
651 ##################################################################
652
653 =item B<http_fixup_request>
654
655 Params: $hash_ref
656
657 Return: Nothing
658
659 This function takes a %hin hash reference and makes sure the proper
660 headers exist (for example, it will add the Host: header, calculate the
661 Content-Length: header for POST requests, etc). For standard requests
662 (i.e. you want the request to be HTTP RFC-compliant), you should call this
663 function right before you call http_do_request.
664
665 =cut
666
667 sub http_fixup_request {
668 my $hin = shift;
669
670 return if ( !( defined $hin && ref($hin) ) );
671
672 $$hin{whisker}->{uri} = '/' if ( $$hin{whisker}->{uri} eq '' );
673 $$hin{whisker}->{http_space1}= ' ';
674 $$hin{whisker}->{http_space2}= ' ';
675 $$hin{whisker}->{protocol}= 'HTTP';
676 $$hin{whisker}->{uri_param_sep}= '?';
677
678 if ( $$hin{whisker}->{'version'} eq '1.1' ) {
679 my ($host) = utils_find_lowercase_key($hin,'host');
680 $$hin{'Host'} = $$hin{whisker}->{'host'}
681 if(!defined $host || $host eq '');
682 $$hin{'Host'} .= ':' . $$hin{whisker}->{'port'}
683 if ( index($$hin{'Host'},':') == -1 &&
684 ( $$hin{whisker}->{port} != 80 || ( $$hin{whisker}->{ssl}==1 &&
685 $$hin{whisker}->{port} != 443 ) ) );
686 my ($conn) = utils_find_lowercase_key($hin,'connection');
687 $$hin{'Connection'} = 'Keep-Alive'
688 if(!defined $conn || $conn eq '');
689
690 } elsif( $$hin{whisker}->{'version'} eq '1.0' ){
691 my ($conn) = utils_find_lowercase_key($hin,'connection');
692 $$hin{'Connection'} = 'close'
693 if(!defined $conn || $conn eq '');
694 }
695
696 utils_delete_lowercase_key( $hin, 'content-length' );
697 if ( $$hin{whisker}->{method} eq 'POST' ||
698 defined $$hin{whisker}->{data} ) {
699 $$hin{whisker}->{data}||='';
700 $$hin{'Content-Length'} = length( $$hin{whisker}->{'data'} );
701 my ($v) = utils_find_lowercase_key( $hin, 'content-type' );
702 if ( !defined $v || $v eq '' ) {
703 $$hin{'Content-Type'} = 'application/x-www-form-urlencoded';
704 }
705 }
706
707 #if(defined $$hin{whisker}->{'proxy_host'} && $$hin{whisker}->{ssl}==0){
708 if ( defined $$hin{whisker}->{'proxy_host'} ) {
709 $$hin{whisker}->{'include_host_in_uri'} = 1;
710 }
711
712 }
713
714 ##################################################################
715
716 =item B<http_reset>
717
718 Params: Nothing
719
720 Return: Nothing
721
722 The http_reset function will walk through the %http_host_cache,
723 closing all open sockets and freeing SSL resources. It also clears
724 out the host cache in case you need to rerun everything fresh.
725
726 Note: if you just want to close a single connection, and you have
727 a copy of the %request hash you used, you should use the http_close()
728 function instead.
729
730 =cut
731
732 sub http_reset {
733 my $stream;
734
735 foreach $stream ( keys %http_host_cache ) {
736 $stream->{'close'}->() if(ref($stream));
737 delete $http_host_cache{$stream};
738 }
739 }
740
741 ##################################################################
742
743 =item B<ssl_is_available>
744
745 Params: Nothing
746
747 Return: $boolean [, $lib_name, $version]
748
749 The ssl_is_available() function will inform you whether SSL requests
750 are allowed, which is dependant on whether the appropriate SSL
751 libraries are installed on the machine. In scalar context, the
752 function will return 1 or 0. In array context, the second element
753 will be the SSL library name that is currently being used by LW2,
754 and the third elment will be the SSL library version number.
755 Elements two and three (name and version) will be undefined if
756 called in array context and no SSL libraries are available.
757
758 =cut
759
760 sub ssl_is_available {
761 return 0 if ( $LW_SSL_LIB == 0 );
762 if ( $LW_SSL_LIB == 1 ) {
763 return 1 if ( !wantarray() );
764 return ( 1, "Net::SSLeay", $Net::SSLeay::VERSION );
765 }
766 elsif ( $LW_SSL_LIB == 2 ) {
767 return 1 if ( !wantarray() );
768 return ( 1, "Net::SSL", $Net::SSL::VERSION );
769 }
770 else {
771 utils_carp('',"ssl_is_available: sanity check failed");
772 return 0;
773 }
774 }
775
776 ##################################################################
777
778 sub _ssl_save_info {
779 my ( $hr, $stream ) = @_;
780 my $cert;
781
782 if ( $stream->{streamtype} == 4 ) {
783 my $SSL = $stream->{sock};
784 $hr->{whisker}->{ssl_cipher} = Net::SSLeay::get_cipher($SSL);
785 if ( $cert = Net::SSLeay::get_peer_certificate($SSL) ) {
786 $hr->{whisker}->{ssl_cert_subject} =
787 Net::SSLeay::X509_NAME_oneline(
788 Net::SSLeay::X509_get_subject_name($cert) );
789 $hr->{whisker}->{ssl_cert_issuer} =
790 Net::SSLeay::X509_NAME_oneline(
791 Net::SSLeay::X509_get_issuer_name($cert) );
792 }
793 return;
794 }
795
796 if ( $stream->{streamtype} == 5 ) {
797 $hr->{whisker}->{ssl_cipher} = $stream->{sock}->get_cipher();
798 if ( $cert = $stream->{sock}->get_peer_certificate() ) {
799 $hr->{whisker}->{ssl_cert_subject} = $cert->subject_name();
800 $hr->{whisker}->{ssl_cert_issuer} = $cert->issuer_name();
801 }
802 return;
803 }
804 }
805
806 ##################################################################
807
808 =item B<http_read_headers>
809
810 Params: $stream, \%in, \%out
811
812 Return: $result_code, $encoding, $length, $connection
813
814 Read HTTP headers from the given stream, storing the results in %out. On
815 success, $result_code will be 1 and $encoding, $length, and $connection
816 will hold the values of the Transfer-Encoding, Content-Length, and
817 Connection headers, respectively. If any of those headers are not present,
818 then it will have an 'undef' value. On an error, the $result_code will
819 be 0 and $encoding will contain an error message.
820
821 This function can be used to parse both request and response headers.
822
823 Note: if there are multiple Transfer-Encoding, Content-Length, or
824 Connection headers, then only the last header value is the one returned
825 by the function.
826
827 =cut
828
829 sub http_read_headers {
830 my ( $stream, $in, $hout ) = @_;
831 my $W = $in->{whisker};
832 my ( $a, $b, $LC, $CL, $TE, $CO );
833
834 # we use direct access into the stream buffers for quickest
835 # parsing of the headers
836 my $last;
837 pos( $stream->{bufin} ) = 0;
838 while (1) {
839 $last = pos( $stream->{bufin} );
840 if ( $stream->{bufin} !~ m/(.*?)[\r]{0,1}\n/g ) {
841 if ( !$stream->{read}->() ) {
842 last
843 if ( $$W{require_newline_after_headers} == 0
844 && length( $stream->{bufin} ) - 1 == $last );
845 return ( 0, 'error reading in all headers' );
846 }
847 pos( $stream->{bufin} ) = $last;
848 next;
849 }
850 last if ( $1 eq '' );
851
852 # should we *not* puke on malformed header?
853 return ( 0, 'malformed header' )
854 if ( $1 !~ m/^([^:]+):([ \t]*)(.*)$/ );
855
856 $$hout{whisker}->{'abnormal_header_spacing'}++ if ( $2 ne ' ' );
857
858 $a = $1;
859 $b = $3;
860 $LC = lc($a);
861 next if ( $LC eq 'whisker' );
862 $TE = lc($b) if ( $LC eq 'transfer-encoding' );
863 $CL = $b if ( $LC eq 'content-length' );
864 $CO = lc($b) if ( $LC eq 'connection' );
865 push( @{ $$hout{whisker}->{cookies} }, $b )
866 if ( $LC eq 'set-cookie' || $LC eq 'set-cookie2' );
867
868 if ( $$W{'lowercase_incoming_headers'} > 0 ) {
869 $a = $LC;
870 }
871 elsif ( $$W{'normalize_incoming_headers'} > 0 ) {
872 $a = ucfirst($LC);
873 $a = 'ETag' if ( $a eq 'Etag' );
874 $a =~ s/(-[a-z])/uc($1)/eg;
875 }
876
877 push( @{ $$hout{whisker}->{header_order} }, $a );
878
879 if ( defined $$hout{$a} && $$W{ignore_duplicate_headers} != 1 ) {
880 $$hout{$a} = [ $$hout{$a} ] if ( !ref( $$hout{$a} ) );
881 push( @{ $$hout{$a} }, $b );
882 }
883 else {
884 $$hout{$a} = $b;
885 }
886 }
887
888 my $found = pos( $stream->{bufin} );
889 $$hout{whisker}->{'raw_header_data'} = substr( $stream->{bufin}, 0, $found )
890 if ( defined $$W{'save_raw_headers'} );
891 $stream->{bufin} = substr( $stream->{bufin}, $found );
892 return ( 1, $TE, $CL, $CO );
893 }
894
895 ##################################################################
896
897 =item B<http_read_body>
898
899 Params: $stream, \%in, \%out, $encoding, $length
900
901 Return: 1 on success, 0 on error (and sets $hout->{whisker}->{error})
902
903 Read the body from the given stream, placing it in $out->{whisker}->{data}.
904 Handles chunked encoding. Can be used to read HTTP (POST) request or HTTP
905 response bodies. $encoding parameter should be lowercase encoding type.
906
907 NOTE: $out->{whisker}->{data} is erased/cleared when this function is called,
908 leaving {data} to just contain this particular HTTP body.
909
910 =cut
911
912 sub http_read_body {
913 my ( $temp, $stream, $hin, $hout, $enc, $len ) = ( '', @_ );
914 my $max_size = $hin->{whisker}->{max_size} || 0;
915 $$hout{whisker}->{data} = '';
916
917 if ( defined $enc && lc($enc) eq 'chunked' ) {
918 my $total = 0;
919 my $x;
920 my $saveraw = $$hin{whisker}->{save_raw_chunks} || 0;
921 if ( !defined( $x = _http_getline($stream) ) ) {
922 $$hout{whisker}->{'error'} = 'Error reading chunked data length';
923 $stream->{'close'}->();
924 return 0;
925 }
926 $a = $x;
927 $a =~ tr/a-fA-F0-9//cd;
928 if ( length($a) > 8 ) {
929 $$hout{whisker}->{'error'} = 'Chunked size is too big: ' . $x;
930 $stream->{'close'}->();
931 return 0;
932 }
933 $len = hex($a);
934 $len = $max_size if ( $max_size && $len > $max_size );
935
936 $$hout{whisker}->{'data'} = $x if ($saveraw);
937
938 while ( $len > 0 ) { # chunked sucks
939 if ( !defined( $temp = _http_get( $stream, $len ) ) ) {
940 $$hout{whisker}->{'error'} = 'Error reading chunked data';
941 $stream->{'close'}->();
942 return 0;
943 }
944 $$hout{whisker}->{'data'} = $$hout{whisker}->{'data'} . $temp;
945 $total += $len;
946 if ( $max_size && $total >= $max_size ) {
947 $stream->{'close'}->();
948 return 1;
949 }
950 $temp = _http_getline($stream);
951 $$hout{whisker}->{'data'} .= $temp if ( $saveraw && defined $temp );
952 if ( defined $temp && $temp =~ /^[\r\n]*$/ ) {
953 $temp = _http_getline($stream);
954 $$hout{whisker}->{'data'} .= $temp
955 if ( $saveraw && defined $temp );
956 }
957 if ( !defined $temp ) {
958 $$hout{whisker}->{'error'} = 'Error reading chunked data';
959 $stream->{'close'}->();
960 return 0;
961 }
962 $temp =~ tr/a-fA-F0-9//cd;
963 if ( length($temp) > 8 ) {
964 $$hout{whisker}->{'error'} =
965 'Chunked size is too big: ' . $temp;
966 $stream->{'close'}->();
967 return 0;
968 }
969 $len = hex($temp);
970 $len = ( $max_size - $total )
971 if ( $max_size && $len > ( $max_size - $total ) );
972 }
973
974 # read in trailer headers; currently doesn't account for max_size
975 while ( defined( $_ = _http_getline($stream) ) ) {
976 $$hout{whisker}->{'data'} .= $_ if ($saveraw);
977 tr/\r\n//d;
978 last if ( $_ eq '' );
979 }
980
981 }
982 else {
983 if ( defined $len ) {
984 return 1 if ( $len <= 0 );
985 $len = $max_size if ( $max_size && $len > $max_size );
986 if (
987 !defined(
988 $$hout{whisker}->{data} = _http_get( $stream, $len )
989 )
990 )
991 {
992 $stream->{'close'}->();
993
994 # New LW2.5 feature: allow_short_reads will still return
995 # success, even if all the data wasn't read. This was
996 # per request due to some 3Com switches sending out
997 # the wrong content-length in HTTP response
998 my $s = $$hin{whisker}->{allow_short_reads} || 0;
999 if ( $s != 0 && length($stream->{'bufin'}) > 0 ) {
1000 # short read is requested, and there is some data, so
1001 # copy it over and return a non-error
1002 $$hout{whisker}->{'data'} = $stream->{'bufin'};
1003 return 1;
1004 }
1005
1006 $$hout{whisker}->{'error'} =
1007 'Error reading data: ' . $stream->{error};
1008 return 0;
1009 }
1010 }
1011 else { # Yuck...read until server stops sending....
1012 $$hout{whisker}->{data} = _http_getall( $stream, $max_size );
1013 $stream->{'close'}->();
1014 }
1015 $$hout{whisker}->{'data'} ||= '';
1016 }
1017 return 1;
1018 }
1019
1020 ##################################################################
1021
1022 =item B<http_construct_headers>
1023
1024 Params: \%in
1025
1026 Return: $data
1027
1028 This function assembles the headers in the given hash into a data
1029 string.
1030
1031 =cut
1032
1033 sub http_construct_headers {
1034 my $hin = shift;
1035 my ( %SENT, $output, $i );
1036
1037 my $EOL = $hin->{whisker}->{http_eol} || "\x0d\x0a";
1038 if ( defined $hin->{whisker}->{header_order}
1039 && ref( $hin->{whisker}->{header_order} ) eq 'ARRAY' )
1040 {
1041 foreach ( @{ $hin->{whisker}->{header_order} } ) {
1042 next if ( $_ eq '' || $_ eq 'whisker' || !defined $hin->{$_} );
1043 if ( ref( $hin->{$_} ) ) {
1044 utils_croak("http_construct_headers: non-array header value reference")
1045 if ( ref( $hin->{$_} ) ne 'ARRAY' );
1046 $SENT{$_} ||= 0;
1047 my $v = $$hin{$_}->[ $SENT{$_} ];
1048 $output .= "$_: $v$EOL";
1049 }
1050 else {
1051 $output .= "$_: $$hin{$_}$EOL";
1052 }
1053 $SENT{$_}++;
1054 }
1055 }
1056
1057 foreach ( keys %$hin ) {
1058 next if ( $_ eq '' || $_ eq 'whisker' );
1059 if ( ref( $hin->{$_} ) ) { # header with multiple values
1060 utils_croak("http_construct_headers: non-array header value ref")
1061 if ( ref( $hin->{$_} ) ne 'ARRAY' );
1062 $SENT{$_} ||= 0;
1063 for($i=$SENT{$_}; $i<~~@{ $hin->{$_} }; $i++) {
1064 $output .= "$_: " . $hin->{$_}->[$i] . $EOL;
1065 }
1066 }
1067 else { # normal header
1068 next if ( defined $SENT{$_} );
1069 $output .= "$_: $$hin{$_}$EOL";
1070 }
1071 }
1072 return $output;
1073 }
1074
1075 ##################################################################
1076
1077 =item B<http_close>
1078
1079 Params: \%request
1080
1081 Return: nothing
1082
1083 This function will close any open streams for the given request.
1084
1085 Note: in order for http_close() to find the right connection, all
1086 original host/proxy/port parameters in %request must be the exact
1087 same as when the original request was made.
1088
1089 =cut
1090
1091 sub http_close {
1092 my $hin = shift;
1093 my $cache_key = stream_key($hin);
1094 return if ( !defined $http_host_cache{$cache_key} );
1095 my $stream = $http_host_cache{$cache_key};
1096 $stream->{'close'}->();
1097 }
1098
1099 ##################################################################
1100
1101 =item B<http_do_request_timeout>
1102
1103 Params: \%request, \%response, $timeout
1104
1105 Return: $result
1106
1107 This function is identical to http_do_request(), except that it
1108 wraps the entire request in a timeout wrapper. $timeout is the
1109 number of seconds to allow for the entire request to be completed.
1110
1111 Note: this function uses alarm() and signals, and thus will only
1112 work on Unix-ish platforms. It should be safe to call on any
1113 platform though.
1114
1115 =cut
1116
1117 sub http_do_request_timeout {
1118 my ( $req, $resp, $timeout ) = @_;
1119 $timeout ||= 30;
1120
1121 my $result;
1122 eval {
1123 local $SIG{ALRM} = sub { die "timeout\n" };
1124 eval { alarm($timeout) };
1125 $result = LW2::http_do_request( $req, $resp );
1126 eval { alarm(0) };
1127 };
1128 if ($@) {
1129 $result = 1;
1130 $resp->{whisker}->{error} = 'Error with timeout wrapper';
1131 $resp->{whisker}->{error} = 'Total transaction timed out'
1132 if ( $@ =~ /timeout/ );
1133 }
1134 return $result;
1135 }
1136