Guest User

lwp-request

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