home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _1fa13a5e4fac97e3730f828a08dbea2d < prev    next >
Encoding:
Text File  |  2004-06-01  |  12.5 KB  |  458 lines

  1. # $Id: Common.pm,v 1.22 2003/10/23 19:11:32 uid39246 Exp $
  2. #
  3. package HTTP::Request::Common;
  4.  
  5. use strict;
  6. use vars qw(@EXPORT @EXPORT_OK $VERSION $DYNAMIC_FILE_UPLOAD);
  7.  
  8. $DYNAMIC_FILE_UPLOAD ||= 0;  # make it defined (don't know why)
  9.  
  10. require Exporter;
  11. *import = \&Exporter::import;
  12. @EXPORT =qw(GET HEAD PUT POST);
  13. @EXPORT_OK = qw($DYNAMIC_FILE_UPLOAD);
  14.  
  15. require HTTP::Request;
  16. use Carp();
  17.  
  18. $VERSION = sprintf("%d.%02d", q$Revision: 1.22 $ =~ /(\d+)\.(\d+)/);
  19.  
  20. my $CRLF = "\015\012";   # "\r\n" is not portable
  21.  
  22. sub GET  { _simple_req('GET',  @_); }
  23. sub HEAD { _simple_req('HEAD', @_); }
  24. sub PUT  { _simple_req('PUT' , @_); }
  25.  
  26. sub POST
  27. {
  28.     my $url = shift;
  29.     my $req = HTTP::Request->new(POST => $url);
  30.     my $content;
  31.     $content = shift if @_ and ref $_[0];
  32.     my($k, $v);
  33.     while (($k,$v) = splice(@_, 0, 2)) {
  34.     if (lc($k) eq 'content') {
  35.         $content = $v;
  36.     }
  37.     else {
  38.         $req->push_header($k, $v);
  39.     }
  40.     }
  41.     my $ct = $req->header('Content-Type');
  42.     unless ($ct) {
  43.     $ct = 'application/x-www-form-urlencoded';
  44.     }
  45.     elsif ($ct eq 'form-data') {
  46.     $ct = 'multipart/form-data';
  47.     }
  48.  
  49.     if (ref $content) {
  50.     if ($ct =~ m,^multipart/form-data\s*(;|$),i) {
  51.         require HTTP::Headers::Util;
  52.         my @v = HTTP::Headers::Util::split_header_words($ct);
  53.         Carp::carp("Multiple Content-Type headers") if @v > 1;
  54.         @v = @{$v[0]};
  55.  
  56.         my $boundary;
  57.         my $boundary_index;
  58.         for (my @tmp = @v; @tmp;) {
  59.         my($k, $v) = splice(@tmp, 0, 2);
  60.         if (lc($k) eq "boundary") {
  61.             $boundary = $v;
  62.             $boundary_index = @v - @tmp - 1;
  63.             last;
  64.         }
  65.         }
  66.  
  67.         ($content, $boundary) = form_data($content, $boundary, $req);
  68.  
  69.         if ($boundary_index) {
  70.         $v[$boundary_index] = $boundary;
  71.         }
  72.         else {
  73.         push(@v, boundary => $boundary);
  74.         }
  75.  
  76.         $ct = HTTP::Headers::Util::join_header_words(@v);
  77.     }
  78.     else {
  79.         # We use a temporary URI object to format
  80.         # the application/x-www-form-urlencoded content.
  81.         require URI;
  82.         my $url = URI->new('http:');
  83.         $url->query_form(ref($content) eq "HASH" ? %$content : @$content);
  84.         $content = $url->query;
  85.     }
  86.     }
  87.  
  88.     $req->header('Content-Type' => $ct);  # might be redundant
  89.     if (defined($content)) {
  90.     $req->header('Content-Length' =>
  91.              length($content)) unless ref($content);
  92.     $req->content($content);
  93.     }
  94.     else {
  95.         $req->header('Content-Length' => 0);
  96.     }
  97.     $req;
  98. }
  99.  
  100.  
  101. sub _simple_req
  102. {
  103.     my($method, $url) = splice(@_, 0, 2);
  104.     my $req = HTTP::Request->new($method => $url);
  105.     my($k, $v);
  106.     while (($k,$v) = splice(@_, 0, 2)) {
  107.     if (lc($k) eq 'content') {
  108.         $req->add_content($v);
  109.     }
  110.     else {
  111.         $req->push_header($k, $v);
  112.     }
  113.     }
  114.     $req;
  115. }
  116.  
  117.  
  118. sub form_data   # RFC1867
  119. {
  120.     my($data, $boundary, $req) = @_;
  121.     my @data = ref($data) eq "HASH" ? %$data : @$data;  # copy
  122.     my $fhparts;
  123.     my @parts;
  124.     my($k,$v);
  125.     while (($k,$v) = splice(@data, 0, 2)) {
  126.     if (!ref($v)) {
  127.         $k =~ s/([\\\"])/\\$1/g;  # escape quotes and backslashes
  128.         push(@parts,
  129.          qq(Content-Disposition: form-data; name="$k"$CRLF$CRLF$v));
  130.     }
  131.     else {
  132.         my($file, $usename, @headers) = @$v;
  133.         unless (defined $usename) {
  134.         $usename = $file;
  135.         $usename =~ s,.*/,, if defined($usename);
  136.         }
  137.         my $disp = qq(form-data; name="$k");
  138.         $disp .= qq(; filename="$usename") if $usename;
  139.         my $content = "";
  140.         my $h = HTTP::Headers->new(@headers);
  141.         my $ct = $h->header("Content-Type");
  142.         if ($file) {
  143.         require Symbol;
  144.         my $fh = Symbol::gensym();
  145.         open($fh, $file) or Carp::croak("Can't open file $file: $!");
  146.         binmode($fh);
  147.         if ($DYNAMIC_FILE_UPLOAD) {
  148.             # will read file later
  149.             $content = $fh;
  150.         }
  151.         else {
  152.             local($/) = undef; # slurp files
  153.             $content = <$fh>;
  154.             close($fh);
  155.             $h->header("Content-Length" => length($content));
  156.         }
  157.         unless ($ct) {
  158.             require LWP::MediaTypes;
  159.             $ct = LWP::MediaTypes::guess_media_type($file, $h);
  160.         }
  161.         }
  162.         if ($h->header("Content-Disposition")) {
  163.         # just to get it sorted first
  164.         $disp = $h->header("Content-Disposition");
  165.         $h->remove_header("Content-Disposition");
  166.         }
  167.         if ($h->header("Content")) {
  168.         $content = $h->header("Content");
  169.         $h->remove_header("Content");
  170.         }
  171.         my $head = join($CRLF, "Content-Disposition: $disp",
  172.                        $h->as_string($CRLF),
  173.                        "");
  174.         if (ref $content) {
  175.         push(@parts, [$head, $content]);
  176.         $fhparts++;
  177.         }
  178.         else {
  179.         push(@parts, $head . $content);
  180.         }
  181.     }
  182.     }
  183.     return "" unless @parts;
  184.  
  185.     my $content;
  186.     if ($fhparts) {
  187.     $boundary = boundary(10) # hopefully enough randomness
  188.         unless $boundary;
  189.  
  190.     # add the boundaries to the @parts array
  191.     for (1..@parts-1) {
  192.         splice(@parts, $_*2-1, 0, "$CRLF--$boundary$CRLF");
  193.     }
  194.     unshift(@parts, "--$boundary$CRLF");
  195.     push(@parts, "$CRLF--$boundary--$CRLF");
  196.  
  197.     # See if we can generate Content-Length header
  198.     my $length = 0;
  199.     for (@parts) {
  200.         if (ref $_) {
  201.          my ($head, $f) = @$_;
  202.         my $file_size;
  203.         unless ( -f $f && ($file_size = -s _) ) {
  204.             # The file is either a dynamic file like /dev/audio
  205.             # or perhaps a file in the /proc file system where
  206.             # stat may return a 0 size even though reading it
  207.             # will produce data.  So we cannot make
  208.             # a Content-Length header.  
  209.             undef $length;
  210.             last;
  211.         }
  212.             $length += $file_size + length $head;
  213.         }
  214.         else {
  215.         $length += length;
  216.         }
  217.         }
  218.         $length && $req->header('Content-Length' => $length);
  219.  
  220.     # set up a closure that will return content piecemeal
  221.     $content = sub {
  222.         for (;;) {
  223.         unless (@parts) {
  224.             defined $length && $length != 0 &&
  225.                 Carp::croak "length of data sent did not match calculated Content-Length header.  Probably because uploaded file changed in size during transfer.";
  226.             return;
  227.         }
  228.         my $p = shift @parts;
  229.         unless (ref $p) {
  230.             $p .= shift @parts while @parts && !ref($parts[0]);
  231.             defined $length && ($length -= length $p);
  232.             return $p;
  233.         }
  234.         my($buf, $fh) = @$p;
  235.         my $buflength = length $buf;
  236.         my $n = read($fh, $buf, 2048, $buflength);
  237.         if ($n) {
  238.             $buflength += $n;
  239.             unshift(@parts, ["", $fh]);
  240.         }
  241.         else {
  242.             close($fh);
  243.         }
  244.         if ($buflength) {
  245.             defined $length && ($length -= $buflength);
  246.             return $buf 
  247.             }
  248.         }
  249.     };
  250.  
  251.     }
  252.     else {
  253.     $boundary = boundary() unless $boundary;
  254.  
  255.     my $bno = 0;
  256.       CHECK_BOUNDARY:
  257.     {
  258.         for (@parts) {
  259.         if (index($_, $boundary) >= 0) {
  260.             # must have a better boundary
  261.             $boundary = boundary(++$bno);
  262.             redo CHECK_BOUNDARY;
  263.         }
  264.         }
  265.         last;
  266.     }
  267.     $content = "--$boundary$CRLF" .
  268.                join("$CRLF--$boundary$CRLF", @parts) .
  269.            "$CRLF--$boundary--$CRLF";
  270.     }
  271.  
  272.     wantarray ? ($content, $boundary) : $content;
  273. }
  274.  
  275.  
  276. sub boundary
  277. {
  278.     my $size = shift || return "xYzZY";
  279.     require MIME::Base64;
  280.     my $b = MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), "");
  281.     $b =~ s/[\W]/X/g;  # ensure alnum only
  282.     $b;
  283. }
  284.  
  285. 1;
  286.  
  287. __END__
  288.  
  289. =head1 NAME
  290.  
  291. HTTP::Request::Common - Construct common HTTP::Request objects
  292.  
  293. =head1 SYNOPSIS
  294.  
  295.   use HTTP::Request::Common;
  296.   $ua = LWP::UserAgent->new;
  297.   $ua->request(GET 'http://www.sn.no/');
  298.   $ua->request(POST 'http://somewhere/foo', [foo => bar, bar => foo]);
  299.  
  300. =head1 DESCRIPTION
  301.  
  302. This module provide functions that return newly created HTTP::Request
  303. objects.  These functions are usually more convenient to use than the
  304. standard HTTP::Request constructor for these common requests.  The
  305. following functions are provided.
  306.  
  307. =over 4
  308.  
  309. =item GET $url, Header => Value,...
  310.  
  311. The GET() function returns a HTTP::Request object initialized with the
  312. GET method and the specified URL.  Without additional arguments it
  313. is exactly equivalent to the following call
  314.  
  315.   HTTP::Request->new(GET => $url)
  316.  
  317. but is less cluttered.  It also reads better when used together with the
  318. LWP::UserAgent->request() method:
  319.  
  320.   my $ua = new LWP::UserAgent;
  321.   my $res = $ua->request(GET 'http://www.sn.no')
  322.   if ($res->is_success) { ...
  323.  
  324. You can also initialize header values in the request by specifying
  325. some key/value pairs as optional arguments.  For instance:
  326.  
  327.   $ua->request(GET 'http://www.sn.no',
  328.                If_Match => 'foo',
  329.                    From     => 'gisle@aas.no',
  330.               );
  331.  
  332. A header key called 'Content' is special and when seen the value will
  333. initialize the content part of the request instead of setting a header.
  334.  
  335. =item HEAD $url, [Header => Value,...]
  336.  
  337. Like GET() but the method in the request is HEAD.
  338.  
  339. =item PUT $url, [Header => Value,...]
  340.  
  341. Like GET() but the method in the request is PUT.
  342.  
  343. =item POST $url, [$form_ref], [Header => Value,...]
  344.  
  345. This works mostly like GET() with POST as the method, but this function
  346. also takes a second optional array or hash reference parameter
  347. ($form_ref).  This argument can be used to pass key/value pairs for
  348. the form content.  By default we will initialize a request using the
  349. C<application/x-www-form-urlencoded> content type.  This means that
  350. you can emulate a HTML E<lt>form> POSTing like this:
  351.  
  352.   POST 'http://www.perl.org/survey.cgi',
  353.        [ name   => 'Gisle Aas',
  354.          email  => 'gisle@aas.no',
  355.          gender => 'M',
  356.          born   => '1964',
  357.          perc   => '3%',
  358.        ];
  359.  
  360. This will create a HTTP::Request object that looks like this:
  361.  
  362.   POST http://www.perl.org/survey.cgi
  363.   Content-Length: 66
  364.   Content-Type: application/x-www-form-urlencoded
  365.  
  366.   name=Gisle%20Aas&email=gisle%40aas.no&gender=M&born=1964&perc=3%25
  367.  
  368. The POST method also supports the C<multipart/form-data> content used
  369. for I<Form-based File Upload> as specified in RFC 1867.  You trigger
  370. this content format by specifying a content type of C<'form-data'> as
  371. one of the request headers.  If one of the values in the $form_ref is
  372. an array reference, then it is treated as a file part specification
  373. with the following interpretation:
  374.  
  375.   [ $file, $filename, Header => Value... ]
  376.  
  377. The first value in the array ($file) is the name of a file to open.
  378. This file will be read and its content placed in the request.  The
  379. routine will croak if the file can't be opened.  Use an C<undef> as $file
  380. value if you want to specify the content directly.  The $filename is
  381. the filename to report in the request.  If this value is undefined,
  382. then the basename of the $file will be used.  You can specify an empty
  383. string as $filename if you don't want any filename in the request.
  384.  
  385. Sending my F<~/.profile> to the survey used as example above can be
  386. achieved by this:
  387.  
  388.   POST 'http://www.perl.org/survey.cgi',
  389.        Content_Type => 'form-data',
  390.        Content      => [ name  => 'Gisle Aas',
  391.                          email => 'gisle@aas.no',
  392.                          gender => 'M',
  393.                          born   => '1964',
  394.                          init   => ["$ENV{HOME}/.profile"],
  395.                        ]
  396.  
  397. This will create a HTTP::Request object that almost looks this (the
  398. boundary and the content of your F<~/.profile> is likely to be
  399. different):
  400.  
  401.   POST http://www.perl.org/survey.cgi
  402.   Content-Length: 388
  403.   Content-Type: multipart/form-data; boundary="6G+f"
  404.  
  405.   --6G+f
  406.   Content-Disposition: form-data; name="name"
  407.  
  408.   Gisle Aas
  409.   --6G+f
  410.   Content-Disposition: form-data; name="email"
  411.  
  412.   gisle@aas.no
  413.   --6G+f
  414.   Content-Disposition: form-data; name="gender"
  415.  
  416.   M
  417.   --6G+f
  418.   Content-Disposition: form-data; name="born"
  419.  
  420.   1964
  421.   --6G+f
  422.   Content-Disposition: form-data; name="init"; filename=".profile"
  423.   Content-Type: text/plain
  424.  
  425.   PATH=/local/perl/bin:$PATH
  426.   export PATH
  427.  
  428.   --6G+f--
  429.  
  430. If you set the $DYNAMIC_FILE_UPLOAD variable (exportable) to some TRUE
  431. value, then you get back a request object with a subroutine closure as
  432. the content attribute.  This subroutine will read the content of any
  433. files on demand and return it in suitable chunks.  This allow you to
  434. upload arbitrary big files without using lots of memory.  You can even
  435. upload infinite files like F</dev/audio> if you wish; however, if
  436. the file is not a plain file, there will be no Content-Length header
  437. defined for the request.  Not all servers (or server
  438. applications) like this.  Also, if the file(s) change in size between
  439. the time the Content-Length is calculated and the time that the last
  440. chunk is delivered, the subroutine will C<Croak>.
  441.  
  442. =back
  443.  
  444. =head1 SEE ALSO
  445.  
  446. L<HTTP::Request>, L<LWP::UserAgent>
  447.  
  448.  
  449. =head1 COPYRIGHT
  450.  
  451. Copyright 1997-2000, Gisle Aas
  452.  
  453. This library is free software; you can redistribute it and/or
  454. modify it under the same terms as Perl itself.
  455.  
  456. =cut
  457.  
  458.