home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / wvhtm064.zip / gateway / cgi-lib.pl next >
Text File  |  2001-02-04  |  15KB  |  458 lines

  1. # Perl Routines to Manipulate CGI input
  2. # S.E.Brenner@bioc.cam.ac.uk
  3. # $Id: cgi-lib.pl,v 1.1.1.1 2000/09/02 20:04:30 cinamod 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: 1.1.1.1 $ =~ /(\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" : "") . 
  236.         (defined $fname ? $fname : "");
  237.  
  238.       ($ctype) = $ct =~ /^\s*Content-type:\s*"([^"]+)"/i;  #";
  239.       ($ctype) = $ct =~ /^\s*Content-Type:\s*([^\s:;]+)/i unless defined $ctype;
  240.       $inct{$name} .= (defined $in{$name} ? "\0" : "") . $ctype;
  241.  
  242.       if ($writefiles && defined $fname) {
  243.         $ser++;
  244.         $fn = $writefiles . ".$$.$ser";
  245.         open (FILE, ">$fn") || &CgiDie("Couldn't open $fn\n");
  246.         binmode (FILE);  # write files accurately
  247.       }
  248.       substr($buf, 0, $lpos+4) = '';
  249.       undef $fname;
  250.       undef $ctype;
  251.     }
  252.  
  253. 1;
  254. END_MULTIPART
  255.     if ($errflag) {
  256.       local ($errmsg, $value);
  257.       $errmsg = $@ || $errflag;
  258.       foreach $value (values %insfn) {
  259.         unlink(split("\0",$value));
  260.       }
  261.       &CgiDie($errmsg);
  262.     } else {
  263.       # everything's ok.
  264.     }
  265.   } else {
  266.     &CgiDie("cgi-lib.pl: Unknown Content-type: $ENV{'CONTENT_TYPE'}\n");
  267.   }
  268.  
  269.   # no-ops to avoid warnings
  270.   $insfn = $insfn;
  271.   $incfn = $incfn;
  272.   $inct  = $inct;
  273.  
  274.   $^W = $perlwarn;
  275.  
  276.   return ($errflag ? undef :  scalar(@in)); 
  277. }
  278.  
  279.  
  280. # PrintHeader
  281. # Returns the magic line which tells WWW that we're an HTML document
  282.  
  283. sub PrintHeader {
  284.   return "Content-type: text/html\n\n";
  285. }
  286.  
  287.  
  288. # HtmlTop
  289. # Returns the <head> of a document and the beginning of the body
  290. # with the title and a body <h1> header as specified by the parameter
  291.  
  292. sub HtmlTop
  293. {
  294.   local ($title) = @_;
  295.  
  296.   return <<END_OF_TEXT;
  297. <html>
  298. <head>
  299. <title>$title</title>
  300. </head>
  301. <body>
  302. <h1>$title</h1>
  303. END_OF_TEXT
  304. }
  305.  
  306.  
  307. # HtmlBot
  308. # Returns the </body>, </html> codes for the bottom of every HTML page
  309.  
  310. sub HtmlBot
  311. {
  312.   return "</body>\n</html>\n";
  313. }
  314.  
  315.  
  316. # SplitParam
  317. # Splits a multi-valued parameter into a list of the constituent parameters
  318.  
  319. sub SplitParam
  320. {
  321.   local ($param) = @_;
  322.   local (@params) = split ("\0", $param);
  323.   return (wantarray ? @params : $params[0]);
  324. }
  325.  
  326.  
  327. # MethGet
  328. # Return true if this cgi call was using the GET request, false otherwise
  329.  
  330. sub MethGet {
  331.   return (defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq "GET");
  332. }
  333.  
  334.  
  335. # MethPost
  336. # Return true if this cgi call was using the POST request, false otherwise
  337.  
  338. sub MethPost {
  339.   return (defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq "POST");
  340. }
  341.  
  342.  
  343. # MyBaseUrl
  344. # Returns the base URL to the script (i.e., no extra path or query string)
  345. sub MyBaseUrl {
  346.   local ($ret, $perlwarn);
  347.   $perlwarn = $^W; $^W = 0;
  348.   $ret = 'http://' . $ENV{'SERVER_NAME'} .  
  349.          ($ENV{'SERVER_PORT'} != 80 ? ":$ENV{'SERVER_PORT'}" : '') .
  350.          $ENV{'SCRIPT_NAME'};
  351.   $^W = $perlwarn;
  352.   return $ret;
  353. }
  354.  
  355.  
  356. # MyFullUrl
  357. # Returns the full URL to the script (i.e., with extra path or query string)
  358. sub MyFullUrl {
  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'} . $ENV{'PATH_INFO'} .
  364.          (length ($ENV{'QUERY_STRING'}) ? "?$ENV{'QUERY_STRING'}" : '');
  365.   $^W = $perlwarn;
  366.   return $ret;
  367. }
  368.  
  369.  
  370. # MyURL
  371. # Returns the base URL to the script (i.e., no extra path or query string)
  372. # This is obsolete and will be removed in later versions
  373. sub MyURL  {
  374.   return &MyBaseUrl;
  375. }
  376.  
  377.  
  378. # CgiError
  379. # Prints out an error message which which containes appropriate headers,
  380. # markup, etcetera.
  381. # Parameters:
  382. #  If no parameters, gives a generic error message
  383. #  Otherwise, the first parameter will be the title and the rest will 
  384. #  be given as different paragraphs of the body
  385.  
  386. sub CgiError {
  387.   local (@msg) = @_;
  388.   local ($i,$name);
  389.  
  390.   if (!@msg) {
  391.     $name = &MyFullUrl;
  392.     @msg = ("Error: script $name encountered fatal error\n");
  393.   };
  394.  
  395.   if (!$cgi_lib'headerout) { #')
  396.     print &PrintHeader; 
  397.     print "<html>\n<head>\n<title>$msg[0]</title>\n</head>\n<body>\n";
  398.   }
  399.   print "<h1>$msg[0]</h1>\n";
  400.   foreach $i (1 .. $#msg) {
  401.     print "<p>$msg[$i]</p>\n";
  402.   }
  403.  
  404.   $cgi_lib'headerout++;
  405. }
  406.  
  407.  
  408. # CgiDie
  409. # Identical to CgiError, but also quits with the passed error message.
  410.  
  411. sub CgiDie {
  412.   local (@msg) = @_;
  413.   &CgiError (@msg);
  414.   die @msg;
  415. }
  416.  
  417.  
  418. # PrintVariables
  419. # Nicely formats variables.  Three calling options:
  420. # A non-null associative array - prints the items in that array
  421. # A type-glob - prints the items in the associated assoc array
  422. # nothing - defaults to use %in
  423. # Typical use: &PrintVariables()
  424.  
  425. sub PrintVariables {
  426.   local (*in) = @_ if @_ == 1;
  427.   local (%in) = @_ if @_ > 1;
  428.   local ($out, $key, $output);
  429.  
  430.   $output =  "\n<dl compact>\n";
  431.   foreach $key (sort keys(%in)) {
  432.     foreach (split("\0", $in{$key})) {
  433.       ($out = $_) =~ s/\n/<br>\n/g;
  434.       $output .=  "<dt><b>$key</b>\n <dd>:<i>$out</i>:<br>\n";
  435.     }
  436.   }
  437.   $output .=  "</dl>\n";
  438.  
  439.   return $output;
  440. }
  441.  
  442. # PrintEnv
  443. # Nicely formats all environment variables and returns HTML string
  444. sub PrintEnv {
  445.   &PrintVariables(*ENV);
  446. }
  447.  
  448.  
  449. # The following lines exist only to avoid warning messages
  450. $cgi_lib'writefiles =  $cgi_lib'writefiles;
  451. $cgi_lib'bufsize    =  $cgi_lib'bufsize ;
  452. $cgi_lib'maxbound   =  $cgi_lib'maxbound;
  453. $cgi_lib'version    =  $cgi_lib'version;
  454. $cgi_lib'filepre    =  $cgi_lib'filepre;
  455.  
  456. 1; #return true 
  457.  
  458.