home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 27 / CDROM27.iso / share / progra / cgi-lib.pl.txt next >
Encoding:
Text File  |  1998-09-21  |  15.2 KB  |  472 lines

  1.  
  2. # Perl Routines to Manipulate CGI input
  3. # cgi-lib@pobox.com
  4. # $Id: cgi-lib.pl,v 2.17 1998/05/14 22:39:23 brenner Exp $
  5. #
  6. # Copyright (c) 1993-1998 Steven E. Brenner  
  7. # Unpublished work.
  8. # Permission granted to use and modify this library so long as the
  9. # copyright above is maintained, modifications are documented, and
  10. # credit is given for any use of the library.
  11. #
  12. # Thanks are due to many people for reporting bugs and suggestions
  13.  
  14. # For more information, see:
  15. #     http://cgi-lib.stanford.edu/cgi-lib/
  16.  
  17. $cgi_lib'version = sprintf("%d.%02d", q$Revision: 2.17 $ =~ /(\d+)\.(\d+)/);
  18.  
  19.  
  20. # Parameters affecting cgi-lib behavior
  21. # User-configurable parameters affecting file upload.
  22. $cgi_lib'maxdata    = 131072;    # maximum bytes to accept via POST - 2^17
  23. $cgi_lib'writefiles =      0;    # directory to which to write files, or
  24.                                  # 0 if files should not be written
  25. $cgi_lib'filepre    = "cgi-lib"; # Prefix of file names, in directory above
  26.  
  27. # Do not change the following parameters unless you have special reasons
  28. $cgi_lib'bufsize  =  8192;    # default buffer size when reading multipart
  29. $cgi_lib'maxbound =   100;    # maximum boundary length to be encounterd
  30. $cgi_lib'headerout =    0;    # indicates whether the header has been printed
  31.  
  32.  
  33. # ReadParse
  34. # Reads in GET or POST data, converts it to unescaped text, and puts
  35. # key/value pairs in %in, using "\0" to separate multiple selections
  36.  
  37. # Returns >0 if there was input, 0 if there was no input 
  38. # undef indicates some failure.
  39.  
  40. # Now that cgi scripts can be put in the normal file space, it is useful
  41. # to combine both the form and the script in one place.  If no parameters
  42. # are given (i.e., ReadParse returns FALSE), then a form could be output.
  43.  
  44. # If a reference to a hash is given, then the data will be stored in that
  45. # hash, but the data from $in and @in will become inaccessable.
  46. # If a variable-glob (e.g., *cgi_input) is the first parameter to ReadParse,
  47. # information is stored there, rather than in $in, @in, and %in.
  48. # Second, third, and fourth parameters fill associative arrays analagous to
  49. # %in with data relevant to file uploads. 
  50.  
  51. # If no method is given, the script will process both command-line arguments
  52. # of the form: name=value and any text that is in $ENV{'QUERY_STRING'}
  53. # This is intended to aid debugging and may be changed in future releases
  54.  
  55. sub ReadParse {
  56.   local (*in) = shift if @_;    # CGI input
  57.   local (*incfn,                # Client's filename (may not be provided)
  58.      *inct,                 # Client's content-type (may not be provided)
  59.      *insfn) = @_;          # Server's filename (for spooled files)
  60.   local ($len, $type, $meth, $errflag, $cmdflag, $perlwarn, $got, $name);
  61.     
  62.   # Disable warnings as this code deliberately uses local and environment
  63.   # variables which are preset to undef (i.e., not explicitly initialized)
  64.   $perlwarn = $^W;
  65.   $^W = 0;
  66.  
  67.   binmode(STDIN);   # we need these for DOS-based systems
  68.   binmode(STDOUT);  # and they shouldn't hurt anything else 
  69.   binmode(STDERR);
  70.     
  71.   # Get several useful env variables
  72.   $type = $ENV{'CONTENT_TYPE'};
  73.   $len  = $ENV{'CONTENT_LENGTH'};
  74.   $meth = $ENV{'REQUEST_METHOD'};
  75.   
  76.   if ($len > $cgi_lib'maxdata) { #'
  77.       &CgiDie("cgi-lib.pl: Request to receive too much data: $len bytes\n");
  78.   }
  79.   
  80.   if (!defined $meth || $meth eq '' || $meth eq 'GET' || 
  81.       $meth eq 'HEAD' ||
  82.       $type eq 'application/x-www-form-urlencoded') {
  83.     local ($key, $val, $i);
  84.     
  85.     # Read in text
  86.     if (!defined $meth || $meth eq '') {
  87.       $in = $ENV{'QUERY_STRING'};
  88.       $cmdflag = 1;  # also use command-line options
  89.     } elsif($meth eq 'GET' || $meth eq 'HEAD') {
  90.       $in = $ENV{'QUERY_STRING'};
  91.     } elsif ($meth eq 'POST') {
  92.         if (($got = read(STDIN, $in, $len) != $len))
  93.       {$errflag="Short Read: wanted $len, got $got\n";};
  94.     } else {
  95.       &CgiDie("cgi-lib.pl: Unknown request method: $meth\n");
  96.     }
  97.  
  98.     @in = split(/[&;]/,$in); 
  99.     push(@in, @ARGV) if $cmdflag; # add command-line parameters
  100.  
  101.     foreach $i (0 .. $#in) {
  102.       # Convert plus to space
  103.       $in[$i] =~ s/\+/ /g;
  104.  
  105.       # Split into key and value.  
  106.       ($key, $val) = split(/=/,$in[$i],2); # splits on the first =.
  107.  
  108.       # Convert %XX from hex numbers to alphanumeric
  109.       $key =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
  110.       $val =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
  111.  
  112.       # Associate key and value
  113.       $in{$key} .= "\0" if (defined($in{$key})); # \0 is the multiple separator
  114.       $in{$key} .= $val;
  115.     }
  116.  
  117.   } elsif ($ENV{'CONTENT_TYPE'} =~ m#^multipart/form-data#) {
  118.     # for efficiency, compile multipart code only if needed
  119. $errflag = !(eval <<'END_MULTIPART');
  120.  
  121.     local ($buf, $boundary, $head, @heads, $cd, $ct, $fname, $ctype, $blen);
  122.     local ($bpos, $lpos, $left, $amt, $fn, $ser);
  123.     local ($bufsize, $maxbound, $writefiles) = 
  124.       ($cgi_lib'bufsize, $cgi_lib'maxbound, $cgi_lib'writefiles);
  125.  
  126.  
  127.     # The following lines exist solely to eliminate spurious warning messages
  128.     $buf = ''; 
  129.  
  130.     ($boundary) = $type =~ /boundary="([^"]+)"/; #";   # find boundary
  131.     ($boundary) = $type =~ /boundary=(\S+)/ unless $boundary;
  132.     &CgiDie ("Boundary not provided: probably a bug in your server") 
  133.       unless $boundary;
  134.     $boundary =  "--" . $boundary;
  135.     $blen = length ($boundary);
  136.  
  137.     if ($ENV{'REQUEST_METHOD'} ne 'POST') {
  138.       &CgiDie("Invalid request method for  multipart/form-data: $meth\n");
  139.     }
  140.  
  141.     if ($writefiles) {
  142.       local($me);
  143.       stat ($writefiles);
  144.       $writefiles = "/tmp" unless  -d _ && -w _;
  145.       # ($me) = $0 =~ m#([^/]*)$#;
  146.       $writefiles .= "/$cgi_lib'filepre"; 
  147.     }
  148.  
  149.     # read in the data and split into parts:
  150.     # put headers in @in and data in %in
  151.     # General algorithm:
  152.     #   There are two dividers: the border and the '\r\n\r\n' between
  153.     # header and body.  Iterate between searching for these
  154.     #   Retain a buffer of size(bufsize+maxbound); the latter part is
  155.     # to ensure that dividers don't get lost by wrapping between two bufs
  156.     #   Look for a divider in the current batch.  If not found, then
  157.     # save all of bufsize, move the maxbound extra buffer to the front of
  158.     # the buffer, and read in a new bufsize bytes.  If a divider is found,
  159.     # save everything up to the divider.  Then empty the buffer of everything
  160.     # up to the end of the divider.  Refill buffer to bufsize+maxbound
  161.     #   Note slightly odd organization.  Code before BODY: really goes with
  162.     # code following HEAD:, but is put first to 'pre-fill' buffers.  BODY:
  163.     # is placed before HEAD: because we first need to discard any 'preface,'
  164.     # which would be analagous to a body without a preceeding head.
  165.  
  166.     $left = $len;
  167.    PART: # find each part of the multi-part while reading data
  168.     while (1) {
  169.       die $@ if $errflag;
  170.       $amt = ($left > $bufsize+$maxbound-length($buf) 
  171.           ?  $bufsize+$maxbound-length($buf): $left);
  172.       $errflag = (($got = read(STDIN, $buf, $amt, length($buf))) != $amt);
  173.       die "Short Read: wanted $amt, got $got\n" if $errflag;
  174.       $left -= $amt;
  175.  
  176.       $in{$name} .= "\0" if defined $in{$name}; 
  177.       $in{$name} .= $fn if $fn;
  178.  
  179.       $name=~/([-\w]+)/;  # This allows $insfn{$name} to be untainted
  180.       if (defined $1) {
  181.         $insfn{$1} .= "\0" if defined $insfn{$1}; 
  182.         $insfn{$1} .= $fn if $fn;
  183.       }
  184.  
  185.      BODY: 
  186.       while (($bpos = index($buf, $boundary)) == -1) {
  187.         if ($left == 0 && $buf eq '') {
  188.       foreach $value (values %insfn) {
  189.             unlink(split("\0",$value));
  190.       }
  191.       &CgiDie("cgi-lib.pl: reached end of input while seeking boundary " .
  192.           "of multipart. Format of CGI input is wrong.\n");
  193.         }
  194.         die $@ if $errflag;
  195.         if ($name) {  # if no $name, then it's the prologue -- discard
  196.           if ($fn) { print FILE substr($buf, 0, $bufsize); }
  197.           else     { $in{$name} .= substr($buf, 0, $bufsize); }
  198.         }
  199.         $buf = substr($buf, $bufsize);
  200.         $amt = ($left > $bufsize ? $bufsize : $left); #$maxbound==length($buf);
  201.         $errflag = (($got = read(STDIN, $buf, $amt, length($buf))) != $amt);
  202.     die "Short Read: wanted $amt, got $got\n" if $errflag;
  203.         $left -= $amt;
  204.       }
  205.       if (defined $name) {  # if no $name, then it's the prologue -- discard
  206.         if ($fn) { print FILE substr($buf, 0, $bpos-2); }
  207.         else     { $in {$name} .= substr($buf, 0, $bpos-2); } # kill last \r\n
  208.       }
  209.       close (FILE);
  210.       last PART if substr($buf, $bpos + $blen, 2) eq "--";
  211.       substr($buf, 0, $bpos+$blen+2) = '';
  212.       $amt = ($left > $bufsize+$maxbound-length($buf) 
  213.           ? $bufsize+$maxbound-length($buf) : $left);
  214.       $errflag = (($got = read(STDIN, $buf, $amt, length($buf))) != $amt);
  215.       die "Short Read: wanted $amt, got $got\n" if $errflag;
  216.       $left -= $amt;
  217.  
  218.  
  219.       undef $head;  undef $fn;
  220.      HEAD:
  221.       while (($lpos = index($buf, "\r\n\r\n")) == -1) { 
  222.         if ($left == 0  && $buf eq '') {
  223.       foreach $value (values %insfn) {
  224.             unlink(split("\0",$value));
  225.       }
  226.       &CgiDie("cgi-lib: reached end of input while seeking end of " .
  227.           "headers. Format of CGI input is wrong.\n$buf");
  228.         }
  229.         die $@ if $errflag;
  230.         $head .= substr($buf, 0, $bufsize);
  231.         $buf = substr($buf, $bufsize);
  232.         $amt = ($left > $bufsize ? $bufsize : $left); #$maxbound==length($buf);
  233.         $errflag = (($got = read(STDIN, $buf, $amt, length($buf))) != $amt);
  234.         die "Short Read: wanted $amt, got $got\n" if $errflag;
  235.         $left -= $amt;
  236.       }
  237.       $head .= substr($buf, 0, $lpos+2);
  238.       push (@in, $head);
  239.       @heads = split("\r\n", $head);
  240.       ($cd) = grep (/^\s*Content-Disposition:/i, @heads);
  241.       ($ct) = grep (/^\s*Content-Type:/i, @heads);
  242.  
  243.       ($name) = $cd =~ /\bname="([^"]+)"/i; #"; 
  244.       ($name) = $cd =~ /\bname=([^\s:;]+)/i unless defined $name;  
  245.  
  246.       ($fname) = $cd =~ /\bfilename="([^"]*)"/i; #"; # filename can be null-str
  247.       ($fname) = $cd =~ /\bfilename=([^\s:;]+)/i unless defined $fname;
  248.       $incfn{$name} .= (defined $in{$name} ? "\0" : "") . 
  249.         (defined $fname ? $fname : "");
  250.  
  251.       ($ctype) = $ct =~ /^\s*Content-type:\s*"([^"]+)"/i;  #";
  252.       ($ctype) = $ct =~ /^\s*Content-Type:\s*([^\s:;]+)/i unless defined $ctype;
  253.       $inct{$name} .= (defined $in{$name} ? "\0" : "") . $ctype;
  254.  
  255.       if ($writefiles && defined $fname) {
  256.         $ser++;
  257.     $fn = $writefiles . ".$$.$ser";
  258.     open (FILE, ">$fn") || &CgiDie("Couldn't open $fn\n");
  259.         binmode (FILE);  # write files accurately
  260.       }
  261.       substr($buf, 0, $lpos+4) = '';
  262.       undef $fname;
  263.       undef $ctype;
  264.     }
  265.  
  266. 1;
  267. END_MULTIPART
  268.     if ($errflag) {
  269.       local ($errmsg, $value);
  270.       $errmsg = $@ || $errflag;
  271.       foreach $value (values %insfn) {
  272.         unlink(split("\0",$value));
  273.       }
  274.       &CgiDie($errmsg);
  275.     } else {
  276.       # everything's ok.
  277.     }
  278.   } else {
  279.     &CgiDie("cgi-lib.pl: Unknown Content-type: $ENV{'CONTENT_TYPE'}\n");
  280.   }
  281.  
  282.   # no-ops to avoid warnings
  283.   $insfn = $insfn;
  284.   $incfn = $incfn;
  285.   $inct  = $inct;
  286.  
  287.   $^W = $perlwarn;
  288.  
  289.   return ($errflag ? undef :  scalar(@in)); 
  290. }
  291.  
  292.  
  293. # PrintHeader
  294. # Returns the magic line which tells WWW that we're an HTML document
  295.  
  296. sub PrintHeader {
  297.   return "Content-type: text/html\n\n";
  298. }
  299.  
  300.  
  301. # HtmlTop
  302. # Returns the <head> of a document and the beginning of the body
  303. # with the title and a body <h1> header as specified by the parameter
  304.  
  305. sub HtmlTop
  306. {
  307.   local ($title) = @_;
  308.  
  309.   return <<END_OF_TEXT;
  310. <html>
  311. <head>
  312. <title>$title</title>
  313. </head>
  314. <body>
  315. <h1>$title</h1>
  316. END_OF_TEXT
  317. }
  318.  
  319.  
  320. # HtmlBot
  321. # Returns the </body>, </html> codes for the bottom of every HTML page
  322.  
  323. sub HtmlBot
  324. {
  325.   return "</body>\n</html>\n";
  326. }
  327.  
  328.  
  329. # SplitParam
  330. # Splits a multi-valued parameter into a list of the constituent parameters
  331.  
  332. sub SplitParam
  333. {
  334.   local ($param) = @_;
  335.   local (@params) = split ("\0", $param);
  336.   return (wantarray ? @params : $params[0]);
  337. }
  338.  
  339.  
  340. # MethGet
  341. # Return true if this cgi call was using the GET request, false otherwise
  342.  
  343. sub MethGet {
  344.   return (defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq "GET");
  345. }
  346.  
  347.  
  348. # MethPost
  349. # Return true if this cgi call was using the POST request, false otherwise
  350.  
  351. sub MethPost {
  352.   return (defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq "POST");
  353. }
  354.  
  355.  
  356. # MyBaseUrl
  357. # Returns the base URL to the script (i.e., no extra path or query string)
  358. sub MyBaseUrl {
  359.   local ($ret, $perlwarn);
  360.   $perlwarn = $^W; $^W = 0;
  361.   $ret = 'http://' . $ENV{'SERVER_NAME'} .  
  362.          ($ENV{'SERVER_PORT'} != 80 ? ":$ENV{'SERVER_PORT'}" : '') .
  363.          $ENV{'SCRIPT_NAME'};
  364.   $^W = $perlwarn;
  365.   return $ret;
  366. }
  367.  
  368.  
  369. # MyFullUrl
  370. # Returns the full URL to the script (i.e., with extra path or query string)
  371. sub MyFullUrl {
  372.   local ($ret, $perlwarn);
  373.   $perlwarn = $^W; $^W = 0;
  374.   $ret = 'http://' . $ENV{'SERVER_NAME'} .  
  375.          ($ENV{'SERVER_PORT'} != 80 ? ":$ENV{'SERVER_PORT'}" : '') .
  376.          $ENV{'SCRIPT_NAME'} . $ENV{'PATH_INFO'} .
  377.          (length ($ENV{'QUERY_STRING'}) ? "?$ENV{'QUERY_STRING'}" : '');
  378.   $^W = $perlwarn;
  379.   return $ret;
  380. }
  381.  
  382.  
  383. # MyURL
  384. # Returns the base URL to the script (i.e., no extra path or query string)
  385. # This is obsolete and will be removed in later versions
  386. sub MyURL  {
  387.   return &MyBaseUrl;
  388. }
  389.  
  390.  
  391. # CgiError
  392. # Prints out an error message which which containes appropriate headers,
  393. # markup, etcetera.
  394. # Parameters:
  395. #  If no parameters, gives a generic error message
  396. #  Otherwise, the first parameter will be the title and the rest will 
  397. #  be given as different paragraphs of the body
  398.  
  399. sub CgiError {
  400.   local (@msg) = @_;
  401.   local ($i,$name);
  402.  
  403.   if (!@msg) {
  404.     $name = &MyFullUrl;
  405.     @msg = ("Error: script $name encountered fatal error\n");
  406.   };
  407.  
  408.   if (!$cgi_lib'headerout) { #')
  409.     print &PrintHeader;    
  410.     print "<html>\n<head>\n<title>$msg[0]</title>\n</head>\n<body>\n";
  411.   }
  412.   print "<h1>$msg[0]</h1>\n";
  413.   foreach $i (1 .. $#msg) {
  414.     print "<p>$msg[$i]</p>\n";
  415.   }
  416.  
  417.   $cgi_lib'headerout++;
  418. }
  419.  
  420.  
  421. # CgiDie
  422. # Identical to CgiError, but also quits with the passed error message.
  423.  
  424. sub CgiDie {
  425.   local (@msg) = @_;
  426.   &CgiError (@msg);
  427.   die @msg;
  428. }
  429.  
  430.  
  431. # PrintVariables
  432. # Nicely formats variables.  Three calling options:
  433. # A non-null associative array - prints the items in that array
  434. # A type-glob - prints the items in the associated assoc array
  435. # nothing - defaults to use %in
  436. # Typical use: &PrintVariables()
  437.  
  438. sub PrintVariables {
  439.   local (*in) = @_ if @_ == 1;
  440.   local (%in) = @_ if @_ > 1;
  441.   local ($out, $key, $output);
  442.  
  443.   $output =  "\n<dl compact>\n";
  444.   foreach $key (sort keys(%in)) {
  445.     foreach (split("\0", $in{$key})) {
  446.       ($out = $_) =~ s/\n/<br>\n/g;
  447.       $output .=  "<dt><b>$key</b>\n <dd>:<i>$out</i>:<br>\n";
  448.     }
  449.   }
  450.   $output .=  "</dl>\n";
  451.  
  452.   return $output;
  453. }
  454.  
  455. # PrintEnv
  456. # Nicely formats all environment variables and returns HTML string
  457. sub PrintEnv {
  458.   &PrintVariables(*ENV);
  459. }
  460.  
  461.  
  462. # The following lines exist only to avoid warning messages
  463. $cgi_lib'writefiles =  $cgi_lib'writefiles;
  464. $cgi_lib'bufsize    =  $cgi_lib'bufsize ;
  465. $cgi_lib'maxbound   =  $cgi_lib'maxbound;
  466. $cgi_lib'version    =  $cgi_lib'version;
  467. $cgi_lib'filepre    =  $cgi_lib'filepre;
  468.  
  469. 1; #return true 
  470.  
  471.  
  472.