home *** CD-ROM | disk | FTP | other *** search
/ CD Actual Thematic 7: Programming / CDAT7.iso / Share / Editores / Perl5 / perl / bin / POST < prev    next >
Encoding:
Text File  |  1997-08-10  |  13.5 KB  |  502 lines

  1. #!perl -w
  2.     eval 'exec perl -S $0 "$@"'
  3.     if 0;
  4.  
  5. # $Id: lwp-request.PL,v 1.26 1996/05/19 11:23:05 aas Exp $
  6. #
  7. # Simple user agent using LWP library.
  8.  
  9. =head1 NAME
  10.  
  11. lwp-request, GET, HEAD, POST - Simple WWW user agent
  12.  
  13. =head1 SYNOPSIS
  14.  
  15.  lwp-request [-eEdvhx] [-m method] [-b <base URL>] [-t <timeout>]
  16.              [-i <if-modified-since>] [-c <content-type>] [-C <credentials>]
  17.              [-p <proxy-url>] [-o <format>] <url>...
  18.  
  19. =head1 DESCRIPTION
  20.  
  21. This program can be used to send requests to WWW servers and your
  22. local file system. The request content for POST, PUT and CHECKIN
  23. methods is read from stdin.  The content of the response is printed on
  24. stdout.  Error messages are printed on stderr.  The program returns a
  25. status value indicating the number of URLs that failed.
  26.  
  27. The options are:
  28.  
  29. =over 4
  30.  
  31. =item -m <method>
  32.  
  33. Set which method to use for the request.  If this option is not used,
  34. then the method is derived from the name of the program.
  35.  
  36. =item -f
  37.  
  38. Force request through, even if the program believes that the method is
  39. illegal.  The server will probably reject the request.
  40.  
  41. =item -b <url>
  42.  
  43. This URL will be used as the base URL for the URLs that the method is
  44. applied to.  The base URL only takes effect for relative URLs.  If you
  45. do not provide this option and the URLs are relative, then they will
  46. be treated as files in the local file system.
  47.  
  48. =item -t <timeout>
  49.  
  50. Set the timeout value for the requests.  The timeout is the amount of
  51. time that the program will wait for a response from the remote server
  52. before it fails.  The default unit for the timeout value is seconds.
  53. You might append "m" or "h" to the timeout value to make it minutes or
  54. hours, respectively.  The default timeout is '3m', i.e. 3 minutes.
  55.  
  56. =item -i <time>
  57.  
  58. Set the If-Modified-Since header in the request. If I<time> it the
  59. name of a file, use the modification timestamp for this file. If
  60. I<time> is not a file, it is parsed as a literal date. Take a look at
  61. L<HTTP::Date> for recogniced formats.
  62.  
  63. =item -c <content-type>
  64.  
  65. Set the Content-Type for the request.  This option is only allowed for
  66. requests that take a content, i.e. POST, PUT and CHECKIN.  You can
  67. force methods to take content by using the C<-f> option together with
  68. C<-c>.  The default Content-Type for POST is
  69. C<application/x-www-form-urlencoded>.  The default Content-type for
  70. the others is C<text/plain>.
  71.  
  72. =item -p <proxy-url>
  73.  
  74. Set the proxy to be used for the requests.  The program also loads
  75. proxy settings from the environment.  You can disable this with the
  76. C<-P> option.
  77.  
  78. =item -C <username>:<password>
  79.  
  80. Provide credentials for documents that are protected by Basic
  81. Authentication.  If the document is protected and you did not specify
  82. the username and password with this option, then you will be prompted
  83. to provide these values.
  84.  
  85. =back
  86.  
  87. The following options controls what is displayed by the program:
  88.  
  89. =over 4
  90.  
  91. =item -u
  92.  
  93. Print request method and absolute URL as requests are made.
  94.  
  95. =item -U
  96.  
  97. Print requeset headers in addition to request method and absolute URL.
  98.  
  99. =item -s
  100.  
  101. Print response status code.  This option is always on for HEAD requests.
  102.  
  103. =item -S
  104.  
  105. Print response status chain. This shows redirect and autorization
  106. requests that are handled by the library.
  107.  
  108. =item -e
  109.  
  110. Print response headers.  This option is always on for HEAD requests.
  111.  
  112. =item -d
  113.  
  114. Do B<not> print the content of the response.
  115.  
  116. =item -o <format>
  117.  
  118. Process HTML content in various ways before printing it.  If the
  119. content type of the response is not HTML, then this option has no
  120. effect.  The legal format values are; I<text>, I<ps>, I<links>,
  121. I<html> and I<dump>.
  122.  
  123. If you specify the I<text> format then the HTML will be formatted as
  124. plain latin1 text.  If you specify the I<ps> format then it will be
  125. formatted as Postscript.
  126.  
  127. The I<links> format will output all links found in the HTML document.
  128. Relative links will be expanded to absolute ones.
  129.  
  130. The I<html> format will reformat the HTML code and the I<dump> format
  131. will just dump the HTML syntax tree.
  132.  
  133. =item -v
  134.  
  135. Print the version number of the program and quit.
  136.  
  137. =item -h
  138.  
  139. Print usage message and quit.
  140.  
  141. =item -x
  142.  
  143. Extra debugging output.
  144.  
  145. =back
  146.  
  147. Because this program is implemented using the LWP library, it will
  148. only support the protocols that LWP supports.
  149.  
  150. =head1 SEE ALSO
  151.  
  152. L<lwp-mirror>, L<LWP>
  153.  
  154. =head1 COPYRIGHT
  155.  
  156. Copyright (c) 1995, 1996 Gisle Aas. All rights reserved.
  157.  
  158. This library is free software; you can redistribute it and/or
  159. modify it under the same terms as Perl itself.
  160.  
  161. =head1 AUTHOR
  162.  
  163. Gisle Aas <aas@a.sn.no>
  164.  
  165. =cut
  166.  
  167.  
  168. $0 =~ s,.*/,,;  # use basename only
  169. $VERSION = sprintf("%d.%02d", q$Revision: 1.26 $ =~ /(\d+)\.(\d+)/);
  170.  
  171.  
  172. require LWP;
  173. require LWP::Debug;
  174. require URI::URL;
  175.  
  176. use HTTP::Status qw(status_message);
  177. use HTTP::Date qw(time2str str2time);
  178.  
  179.  
  180. # This table lists the methods that are allowed.  It should really be
  181. # a superset for all methods supported for every scheme that may be
  182. # supported by the library.  Currently it might be a bit too HTTP
  183. # specific.  You might use the -f option to force a method through.
  184. #
  185. # "" = No content in request, "C" = Needs content in request
  186. #
  187. %allowed_methods = (
  188.     GET        => "",   
  189.     HEAD       => "",
  190.     POST       => "C",   
  191.     PUT        => "C",
  192.     DELETE     => "",   
  193.     LINK       => "",
  194.     UNLINK     => "",
  195.     CHECKIN    => "C",
  196.     CHECKOUT   => "",
  197.     SHOWMETHOD => "",
  198. );
  199.  
  200.  
  201. # We make our own specialization of LWP::UserAgent that asks for
  202. # user/password if document is protected.
  203. {
  204.     package RequestAgent;
  205.     @ISA = qw(LWP::UserAgent);
  206.  
  207.     sub new
  208.     { 
  209.     my $self = LWP::UserAgent::new(@_);
  210.     $self->agent("lwp-request/$main::VERSION");
  211.     $self;
  212.     }
  213.  
  214.     sub get_basic_credentials
  215.     {
  216.     my($self, $realm, $uri) = @_;
  217.     if ($main::opt_C) {
  218.         return split(':', $main::opt_C, 2);
  219.     } elsif (-t) {
  220.         my $netloc = $uri->netloc;
  221.         print "Enter username for $realm at $netloc: ";
  222.         my $user = <STDIN>;
  223.         chomp($user);
  224.         return (undef, undef) unless length $user;
  225.         print "Password: ";
  226.         system("stty -echo");
  227.         my $password = <STDIN>;
  228.         system("stty echo");
  229.         print "\n";  # because we disabled echo
  230.         chomp($password);
  231.         return ($user, $password);
  232.     } else {
  233.         return (undef, undef)
  234.     }
  235.     }
  236. }
  237.  
  238. $method = uc($0 eq "lwp-request" ? "GET" : $0);
  239.  
  240. # Parse command line
  241. use Getopt::Std;
  242.  
  243. $opt_m = undef;  # set method
  244. $opt_f = undef;  # make request even if method is now in %allowed_methods
  245. $opt_b = undef;  # base url
  246. $opt_t = undef;  # timeout
  247. $opt_i = undef;  # if-modified-since
  248. $opt_c = undef;  # content type for POST
  249. $opt_C = undef;  # credidentials for basic authorization
  250.  
  251. $opt_u = undef;  # display method, URL and headers of request
  252. $opt_U = undef;  # display request headers also
  253. $opt_s = undef;  # display status code
  254. $opt_S = undef;  # display whole chain of status codes
  255. $opt_e = undef;  # display response headers (default for HEAD)
  256. $opt_d = undef;  # don't display content
  257.  
  258. $opt_h = undef;  # print usage
  259. $opt_v = undef;  # print version
  260.  
  261. $opt_x = undef;  # extra debugging info
  262. $opt_p = undef;  # proxy URL
  263. $opt_P = undef;  # don't load proxy setting from environment
  264.  
  265. $opt_o = undef;  # output format
  266.  
  267. unless (getopts("xhvuUsSedPp:b:t:i:c:C:m:fo:")) {
  268.     usage();
  269. }
  270.  
  271. if ($opt_v) {
  272.     require LWP;
  273.     my $DISTNAME = 'libwww-perl-' . LWP::Version();
  274.     die <<"EOT";
  275. This is lwp-request version $VERSION ($DISTNAME)
  276.  
  277. Copyright 1995-1996, Gisle Aas.
  278.  
  279. This program is free software; you can redistribute it and/or
  280. modify it under the same terms as Perl itself.
  281. EOT
  282. }
  283.  
  284. usage() if $opt_h || !@ARGV;
  285.  
  286. LWP::Debug::level('+') if $opt_x;
  287.  
  288. # Create the user agent object
  289. $ua = new RequestAgent;
  290.  
  291. # Load proxy settings from *_proxy environment variables.
  292. $ua->env_proxy unless $opt_P;
  293.  
  294. $method = uc($opt_m) if defined $opt_m;
  295.  
  296. if ($opt_f) {
  297.     if ($opt_c) {
  298.         $allowed_methods{$method} = "C";  # force content
  299.     } else {
  300.         $allowed_methods{$method} = "";
  301.     }
  302. } elsif (!defined $allowed_methods{$method}) {
  303.     die "$0: $method is not an allowed method\n";
  304. }
  305.  
  306. if ($method eq "HEAD") {
  307.     $opt_s = 1;
  308.     $opt_e = 1 unless $opt_d;
  309.     $opt_d = 1;
  310. }
  311.  
  312. if (defined $opt_t) {
  313.     $opt_t =~ /^(\d+)([smh])?/;
  314.     die "$0: Illegal timeout value!\n" unless defined $1;
  315.     $timeout = $1;
  316.     $timeout *= 60   if ($2 eq "m");
  317.     $timeout *= 3600 if ($2 eq "h");
  318.     $ua->timeout($timeout);
  319. }
  320.  
  321. if (defined $opt_i) {
  322.     if (-e $opt_i) {
  323.         $time = (stat _)[9];
  324.     } else {
  325.         $time = str2time($opt_i);
  326.         die "$0: Illegal time syntax for -i option\n"
  327.             unless defined $time;
  328.     }
  329.     $opt_i = time2str($time);
  330. }
  331.  
  332. $content = undef;
  333. if ($allowed_methods{$method} eq "C") {
  334.     # This request needs some content
  335.     unless (defined $opt_c) {
  336.         # set default content type
  337.         $opt_c = ($method eq "POST") ?
  338.               "application/x-www-form-urlencoded"
  339.             : "text/plain";
  340.     } else {
  341.         die "$0: Illegal Content-type format\n"
  342.             unless $opt_c =~ m,^[\w\-]+/[\w\-]+$,
  343.     }
  344.     print "Please enter content ($opt_c) to be ${method}ed:\n"
  345.         if -t;
  346.     $content = join("", <STDIN>);
  347. } else {
  348.     die "$0: Can't set Content-type for $method requests\n"
  349.         if defined $opt_c;
  350. }
  351.  
  352. # Set up a request.  We will use the same request object for all URLs.
  353. $request = new HTTP::Request $method;
  354. $request->header('If-Modified-Since', $opt_i) if defined $opt_i;
  355. #$request->header('Accept', '*/*');
  356. if ($opt_c) { # will always be set for request that wants content
  357.     $request->header('Content-Type', $opt_c);
  358.     $request->header('Content-Length', length $content);  # Not really needed
  359.     $request->content($content);
  360. }
  361.  
  362.  
  363. $errors = 0;
  364.  
  365. # Ok, now we perform the requests, one URL at a time
  366. while ($url = shift) {
  367.     # Create the URL object, but protect us against bad URLs
  368.     eval {
  369.     if ($url =~ /^\w+:/ || $opt_b) {  # is there any scheme specification
  370.         $url = new URI::URL $url, $opt_b;
  371.     } else {
  372.         # No scheme specified for the URL (treat it as a file)
  373.         $url = newlocal URI::URL $url;
  374.     }
  375.     };
  376.     if ($@) {
  377.     $@ =~ s/at\s+\S+\s+line\s\d+//;
  378.     print STDERR $@;
  379.     $errors++;
  380.     next;
  381.     }
  382.  
  383.     $ua->proxy($url->scheme, $opt_p) if $opt_p;
  384.  
  385.     # Send the request and get a response back from the server
  386.     $request->url($url);
  387.     $response = $ua->request($request);
  388.  
  389.     if ($opt_u || $opt_U) {
  390.         my $url = $response->request->url->as_string;
  391.         print "$method $url\n";
  392.         print $response->request->headers_as_string, "\n" if $opt_U;
  393.     }
  394.  
  395.     if ($opt_S) {
  396.     printResponseChain($response);
  397.     } elsif ($opt_s) {
  398.         # Display status code
  399.         my $code = $response->code;
  400.         print $code, " ", status_message($code), "\n";
  401.         
  402.     }
  403.  
  404.     if ($opt_e) {
  405.         # Display headers
  406.         print $response->headers_as_string;
  407.         print "\n";  # separate headers and content
  408.     }
  409.  
  410.     if ($response->is_success) {
  411.     unless ($opt_d) {
  412.         if ($opt_o &&
  413.         $response->content_type eq 'text/html') {
  414.         require HTML::Parse;
  415.         my $html = HTML::Parse::parse_html($response->content);
  416.         {
  417.             $opt_o eq 'ps' && do {
  418.             require HTML::FormatPS;
  419.             my $f = new HTML::FormatPS;
  420.             print $f->format($html);
  421.             last;
  422.             };
  423.             $opt_o eq 'text' && do {
  424.             require HTML::FormatText;
  425.             my $f = new HTML::FormatText;
  426.             print $f->format($html);
  427.             last;
  428.             };
  429.             $opt_o eq 'html' && do {
  430.             print $html->as_HTML;
  431.             last;
  432.             };
  433.             $opt_o eq 'links' && do {
  434.             my $base = $response->base;
  435.             for ( @{ $html->extract_links } ) {
  436.                 my($link, $elem) = @$_;
  437.                 my $tag = uc $elem->tag;
  438.                 $link = new URI::URL $link, $base;
  439.                 print "$tag\t", $link->abs->as_string, "\n";
  440.             }
  441.             last;
  442.             };
  443.             $opt_o eq 'dump' && do {
  444.             $html->dump;
  445.             last;
  446.             };
  447.             # It is bad to not notice this before now :-(
  448.             die "Illegal -o option value ($opt_o)\n";
  449.         }
  450.         } else {
  451.         print $response->content;
  452.         }
  453.     }
  454.     } else {
  455.         print STDERR $response->error_as_HTML unless $opt_d;
  456.         $errors++;
  457.     }
  458. }
  459.  
  460. exit $errors;
  461.  
  462.  
  463. sub printResponseChain
  464. {
  465.     my($response) = @_;
  466.     return unless defined $response;
  467.     printResponseChain($response->previous);
  468.     my $method = $response->request->method;
  469.     my $url = $response->request->url->as_string;
  470.     my $code = $response->code;
  471.     print "$method $url --> $code ", status_message($code), "\n";
  472. }
  473.  
  474.  
  475. sub usage
  476. {
  477.     die <<"EOT";
  478. Usage: $0 [-options] <url>...
  479.     -m <method>   use method for the request (default is '$method')
  480.     -f            make request even if $0 believes method is illegal
  481.     -b <base>     Use the specified URL as base
  482.     -t <timeout>  Set timeout value
  483.     -i <time>     Set the If-Modified-Since header on the request
  484.     -c <conttype> use this content-type for POST, PUT, CHECKIN
  485.     -p <proxyurl> use this as a proxy
  486.     -P            don't load proxy settings from environment
  487.  
  488.     -u            Display method and URL before any response
  489.     -U            Display request headers (implies -u)
  490.     -s            Display response status code
  491.     -S            Display response status chain
  492.     -e            Display response headers
  493.     -d            Do not display content
  494.     -o <format>   Process HTML content in various ways
  495.  
  496.     -v            Show program version
  497.     -h            Print this message
  498.  
  499.     -x            Extra debugging output
  500. EOT
  501. }
  502.