home *** CD-ROM | disk | FTP | other *** search
/ ftp.sunet.sepub/pictures / 2014.11.ftp.sunet.se-pictures.tar / ftp.sunet.se / pub / pictures / ACiD-artpacks / www / mirrors / acheron / cgi-bin / links / cgi-lib.pl < prev    next >
Text File  |  1999-02-04  |  15KB  |  457 lines

  1. # Perl Routines to Manipulate CGI input
  2. # Steven E. Brenner / cgi-lib@pobox.com
  3. # $Id: cgi-lib.pl,v 2.12 1996/06/19 13:46:01 brenner Exp $
  4. #
  5. # Copyright (c) 1996 Steven E. Brenner  
  6. # Unpublished work.
  7. # Permission granted to use and modify this library so long as the
  8. # copyright above is maintained, modifications are documented, and
  9. # credit is given for any use of the library.
  10. #
  11. # Thanks are due to many people for reporting bugs and suggestions
  12. # especially Meng Weng Wong, Maki Watanabe, Bo Frese Rasmussen,
  13. # Andrew Dalke, Mark-Jason Dominus, Dave Dittrich, Jason Mathews
  14.  
  15. # For more information, see:
  16. #     http://www.bio.cam.ac.uk/cgi-lib/
  17.  
  18. $cgi_lib'version = sprintf("%d.%02d", q$Revision: 2.12 $ =~ /(\d+)\.(\d+)/);
  19.  
  20.  
  21. # Parameters affecting cgi-lib behavior
  22. # User-configurable parameters affecting file upload.
  23. $cgi_lib'maxdata    = 131072;    # maximum bytes to accept via POST - 2^17
  24. $cgi_lib'writefiles =      0;    # directory to which to write files, or
  25.                                  # 0 if files should not be written
  26. $cgi_lib'filepre    = "cgi-lib"; # Prefix of file names, in directory above
  27.  
  28. # Do not change the following parameters unless you have special reasons
  29. $cgi_lib'bufsize  =  8192;    # default buffer size when reading multipart
  30. $cgi_lib'maxbound =   100;    # maximum boundary length to be encounterd
  31. $cgi_lib'headerout =    0;    # indicates whether the header has been printed
  32.  
  33.  
  34. # ReadParse
  35. # Reads in GET or POST data, converts it to unescaped text, and puts
  36. # key/value pairs in %in, using "\0" to separate multiple selections
  37.  
  38. # Returns >0 if there was input, 0 if there was no input 
  39. # undef indicates some failure.
  40.  
  41. # Now that cgi scripts can be put in the normal file space, it is useful
  42. # to combine both the form and the script in one place.  If no parameters
  43. # are given (i.e., ReadParse returns FALSE), then a form could be output.
  44.  
  45. # If a reference to a hash is given, then the data will be stored in that
  46. # hash, but the data from $in and @in will become inaccessable.
  47. # If a variable-glob (e.g., *cgi_input) is the first parameter to ReadParse,
  48. # information is stored there, rather than in $in, @in, and %in.
  49. # Second, third, and fourth parameters fill associative arrays analagous to
  50. # %in with data relevant to file uploads. 
  51.  
  52. # If no method is given, the script will process both command-line arguments
  53. # of the form: name=value and any text that is in $ENV{'QUERY_STRING'}
  54. # This is intended to aid debugging and may be changed in future releases
  55.  
  56. sub ReadParse {
  57.   local (*in) = shift if @_;    # CGI input
  58.   local (*incfn,                # Client's filename (may not be provided)
  59.      *inct,                 # Client's content-type (may not be provided)
  60.      *insfn) = @_;          # Server's filename (for spooled files)
  61.   local ($len, $type, $meth, $errflag, $cmdflag, $perlwarn, $got);
  62.     
  63.   # Disable warnings as this code deliberately uses local and environment
  64.   # variables which are preset to undef (i.e., not explicitly initialized)
  65.   $perlwarn = $^W;
  66.   $^W = 0;
  67.  
  68.   binmode(STDIN);   # we need these for DOS-based systems
  69.   binmode(STDOUT);  # and they shouldn't hurt anything else 
  70.   binmode(STDERR);
  71.     
  72.   # Get several useful env variables
  73.   $type = $ENV{'CONTENT_TYPE'};
  74.   $len  = $ENV{'CONTENT_LENGTH'};
  75.   $meth = $ENV{'REQUEST_METHOD'};
  76.   
  77.   if ($len > $cgi_lib'maxdata) { #'
  78.       &CgiDie("cgi-lib.pl: Request to receive too much data: $len bytes\n");
  79.   }
  80.   
  81.   if (!defined $meth || $meth eq '' || $meth eq 'GET' || 
  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 _ && -r _ && -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.  
  171.       $amt = ($left > $bufsize+$maxbound-length($buf) 
  172.           ?  $bufsize+$maxbound-length($buf): $left);
  173.       $errflag = (($got = read(STDIN, $buf, $amt, length($buf))) != $amt);
  174.       die "Short Read: wanted $amt, got $got\n" if $errflag;
  175.       $left -= $amt;
  176.  
  177.       $in{$name} .= "\0" if defined $in{$name}; 
  178.       $in{$name} .= $fn if $fn;
  179.  
  180.       $name=~/([-\w]+)/;  # This allows $insfn{$name} to be untainted
  181.       if (defined $1) {
  182.         $insfn{$1} .= "\0" if defined $insfn{$1}; 
  183.         $insfn{$1} .= $fn if $fn;
  184.       }
  185.  
  186.      BODY: 
  187.       while (($bpos = index($buf, $boundary)) == -1) {
  188.         die $@ if $errflag;
  189.         if ($name) {  # if no $name, then it's the prologue -- discard
  190.           if ($fn) { print FILE substr($buf, 0, $bufsize); }
  191.           else     { $in{$name} .= substr($buf, 0, $bufsize); }
  192.         }
  193.         $buf = substr($buf, $bufsize);
  194.         $amt = ($left > $bufsize ? $bufsize : $left); #$maxbound==length($buf);
  195.         $errflag = (($got = read(STDIN, $buf, $amt, $maxbound)) != $amt);  
  196.     die "Short Read: wanted $amt, got $got\n" if $errflag;
  197.         $left -= $amt;
  198.       }
  199.       if (defined $name) {  # if no $name, then it's the prologue -- discard
  200.         if ($fn) { print FILE substr($buf, 0, $bpos-2); }
  201.         else     { $in {$name} .= substr($buf, 0, $bpos-2); } # kill last \r\n
  202.       }
  203.       close (FILE);
  204.       last PART if substr($buf, $bpos + $blen, 4) eq "--\r\n";
  205.       substr($buf, 0, $bpos+$blen+2) = '';
  206.       $amt = ($left > $bufsize+$maxbound-length($buf) 
  207.           ? $bufsize+$maxbound-length($buf) : $left);
  208.       $errflag = (($got = read(STDIN, $buf, $amt, length($buf))) != $amt);
  209.       die "Short Read: wanted $amt, got $got\n" if $errflag;
  210.       $left -= $amt;
  211.  
  212.  
  213.       undef $head;  undef $fn;
  214.      HEAD:
  215.       while (($lpos = index($buf, "\r\n\r\n")) == -1) { 
  216.         die $@ if $errflag;
  217.         $head .= substr($buf, 0, $bufsize);
  218.         $buf = substr($buf, $bufsize);
  219.         $amt = ($left > $bufsize ? $bufsize : $left); #$maxbound==length($buf);
  220.         $errflag = (($got = read(STDIN, $buf, $amt, $maxbound)) != $amt);  
  221.         die "Short Read: wanted $amt, got $got\n" if $errflag;
  222.         $left -= $amt;
  223.       }
  224.       $head .= substr($buf, 0, $lpos+2);
  225.       push (@in, $head);
  226.       @heads = split("\r\n", $head);
  227.       ($cd) = grep (/^\s*Content-Disposition:/i, @heads);
  228.       ($ct) = grep (/^\s*Content-Type:/i, @heads);
  229.  
  230.       ($name) = $cd =~ /\bname="([^"]+)"/i; #"; 
  231.       ($name) = $cd =~ /\bname=([^\s:;]+)/i unless defined $name;  
  232.  
  233.       ($fname) = $cd =~ /\bfilename="([^"]*)"/i; #"; # filename can be null-str
  234.       ($fname) = $cd =~ /\bfilename=([^\s:;]+)/i unless defined $fname;
  235.       $incfn{$name} .= (defined $in{$name} ? "\0" : "") . $fname;
  236.  
  237.       ($ctype) = $ct =~ /^\s*Content-type:\s*"([^"]+)"/i;  #";
  238.       ($ctype) = $ct =~ /^\s*Content-Type:\s*([^\s:;]+)/i unless defined $ctype;
  239.       $inct{$name} .= (defined $in{$name} ? "\0" : "") . $ctype;
  240.  
  241.       if ($writefiles && defined $fname) {
  242.         $ser++;
  243.     $fn = $writefiles . ".$$.$ser";
  244.     open (FILE, ">$fn") || &CgiDie("Couldn't open $fn\n");
  245.         binmode (FILE);  # write files accurately
  246.       }
  247.       substr($buf, 0, $lpos+4) = '';
  248.       undef $fname;
  249.       undef $ctype;
  250.     }
  251.  
  252. 1;
  253. END_MULTIPART
  254.     if ($errflag) {
  255.       local ($errmsg, $value);
  256.       $errmsg = $@ || $errflag;
  257.       foreach $value (values %insfn) {
  258.         unlink(split("\0",$value));
  259.       }
  260.       &CgiDie($errmsg);
  261.     } else {
  262.       # everything's ok.
  263.     }
  264.   } else {
  265.     &CgiDie("cgi-lib.pl: Unknown Content-type: $ENV{'CONTENT_TYPE'}\n");
  266.   }
  267.  
  268.   # no-ops to avoid warnings
  269.   $insfn = $insfn;
  270.   $incfn = $incfn;
  271.   $inct  = $inct;
  272.  
  273.   $^W = $perlwarn;
  274.  
  275.   return ($errflag ? undef :  scalar(@in)); 
  276. }
  277.  
  278.  
  279. # PrintHeader
  280. # Returns the magic line which tells WWW that we're an HTML document
  281.  
  282. sub PrintHeader {
  283.   return "Content-type: text/html\n\n";
  284. }
  285.  
  286.  
  287. # HtmlTop
  288. # Returns the <head> of a document and the beginning of the body
  289. # with the title and a body <h1> header as specified by the parameter
  290.  
  291. sub HtmlTop
  292. {
  293.   local ($title) = @_;
  294.  
  295.   return <<END_OF_TEXT;
  296. <html>
  297. <head>
  298. <title>$title</title>
  299. </head>
  300. <body>
  301. <h1>$title</h1>
  302. END_OF_TEXT
  303. }
  304.  
  305.  
  306. # HtmlBot
  307. # Returns the </body>, </html> codes for the bottom of every HTML page
  308.  
  309. sub HtmlBot
  310. {
  311.   return "</body>\n</html>\n";
  312. }
  313.  
  314.  
  315. # SplitParam
  316. # Splits a multi-valued parameter into a list of the constituent parameters
  317.  
  318. sub SplitParam
  319. {
  320.   local ($param) = @_;
  321.   local (@params) = split ("\0", $param);
  322.   return (wantarray ? @params : $params[0]);
  323. }
  324.  
  325.  
  326. # MethGet
  327. # Return true if this cgi call was using the GET request, false otherwise
  328.  
  329. sub MethGet {
  330.   return (defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq "GET");
  331. }
  332.  
  333.  
  334. # MethPost
  335. # Return true if this cgi call was using the POST request, false otherwise
  336.  
  337. sub MethPost {
  338.   return (defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq "POST");
  339. }
  340.  
  341.  
  342. # MyBaseUrl
  343. # Returns the base URL to the script (i.e., no extra path or query string)
  344. sub MyBaseUrl {
  345.   local ($ret, $perlwarn);
  346.   $perlwarn = $^W; $^W = 0;
  347.   $ret = 'http://' . $ENV{'SERVER_NAME'} .  
  348.          ($ENV{'SERVER_PORT'} != 80 ? ":$ENV{'SERVER_PORT'}" : '') .
  349.          $ENV{'SCRIPT_NAME'};
  350.   $^W = $perlwarn;
  351.   return $ret;
  352. }
  353.  
  354.  
  355. # MyFullUrl
  356. # Returns the full URL to the script (i.e., with extra path or query string)
  357. sub MyFullUrl {
  358.   local ($ret, $perlwarn);
  359.   $perlwarn = $^W; $^W = 0;
  360.   $ret = 'http://' . $ENV{'SERVER_NAME'} .  
  361.          ($ENV{'SERVER_PORT'} != 80 ? ":$ENV{'SERVER_PORT'}" : '') .
  362.          $ENV{'SCRIPT_NAME'} . $ENV{'PATH_INFO'} .
  363.          (length ($ENV{'QUERY_STRING'}) ? "?$ENV{'QUERY_STRING'}" : '');
  364.   $^W = $perlwarn;
  365.   return $ret;
  366. }
  367.  
  368.  
  369. # MyURL
  370. # Returns the base URL to the script (i.e., no extra path or query string)
  371. # This is obsolete and will be removed in later versions
  372. sub MyURL  {
  373.   return &MyBaseUrl;
  374. }
  375.  
  376.  
  377. # CgiError
  378. # Prints out an error message which which containes appropriate headers,
  379. # markup, etcetera.
  380. # Parameters:
  381. #  If no parameters, gives a generic error message
  382. #  Otherwise, the first parameter will be the title and the rest will 
  383. #  be given as different paragraphs of the body
  384.  
  385. sub CgiError {
  386.   local (@msg) = @_;
  387.   local ($i,$name);
  388.  
  389.   if (!@msg) {
  390.     $name = &MyFullUrl;
  391.     @msg = ("Error: script $name encountered fatal error\n");
  392.   };
  393.  
  394.   if (!$cgi_lib'headerout) { #')
  395.     print &PrintHeader;    
  396.     print "<html>\n<head>\n<title>$msg[0]</title>\n</head>\n<body>\n";
  397.   }
  398.   print "<h1>$msg[0]</h1>\n";
  399.   foreach $i (1 .. $#msg) {
  400.     print "<p>$msg[$i]</p>\n";
  401.   }
  402.  
  403.   $cgi_lib'headerout++;
  404. }
  405.  
  406.  
  407. # CgiDie
  408. # Identical to CgiError, but also quits with the passed error message.
  409.  
  410. sub CgiDie {
  411.   local (@msg) = @_;
  412.   &CgiError (@msg);
  413.   die @msg;
  414. }
  415.  
  416.  
  417. # PrintVariables
  418. # Nicely formats variables.  Three calling options:
  419. # A non-null associative array - prints the items in that array
  420. # A type-glob - prints the items in the associated assoc array
  421. # nothing - defaults to use %in
  422. # Typical use: &PrintVariables()
  423.  
  424. sub PrintVariables {
  425.   local (*in) = @_ if @_ == 1;
  426.   local (%in) = @_ if @_ > 1;
  427.   local ($out, $key, $output);
  428.  
  429.   $output =  "\n<dl compact>\n";
  430.   foreach $key (sort keys(%in)) {
  431.     foreach (split("\0", $in{$key})) {
  432.       ($out = $_) =~ s/\n/<br>\n/g;
  433.       $output .=  "<dt><b>$key</b>\n <dd>:<i>$out</i>:<br>\n";
  434.     }
  435.   }
  436.   $output .=  "</dl>\n";
  437.  
  438.   return $output;
  439. }
  440.  
  441. # PrintEnv
  442. # Nicely formats all environment variables and returns HTML string
  443. sub PrintEnv {
  444.   &PrintVariables(*ENV);
  445. }
  446.  
  447.  
  448. # The following lines exist only to avoid warning messages
  449. $cgi_lib'writefiles =  $cgi_lib'writefiles;
  450. $cgi_lib'bufsize    =  $cgi_lib'bufsize ;
  451. $cgi_lib'maxbound   =  $cgi_lib'maxbound;
  452. $cgi_lib'version    =  $cgi_lib'version;
  453. $cgi_lib'filepre    =  $cgi_lib'filepre;
  454.  
  455. 1; #return true 
  456.  
  457.