Recipe 14.16. Writing a CGI ScriptCredit: Chetan Patil ProblemYou want to expose Ruby code through an existing web server, without having to do any special configuration. SolutionMost web servers are set up to run CGI
DiscussionCGI was the first major technology to add dynamic elements to the previously static Web. A CGI resource is requested like any static HTML document, but behind the scenes the web server executes an external program (in this case, a Ruby CGI has a very simple interface, based on environment variables and standard input and output; one that should be very familiar to writers of command-line programs. This simplicity is CGI's weakness: it leaves too many things undefined. But when a Rails application would be overkill, a CGI script might be the right size. CGI programs typically reside in a special directory of the web server's web space (often the /cgi-bin directory). On Unix systems, CGI files must be made executable by the web server, and the first line of the script must point to the system's Ruby interpreter (usually /usr/bin/ruby or /usr/local/bin/ruby). A There are only a few restrictions on the output of a The headers are separated from the content by a blank line. If the blank line is missing, the server may incorrectly interpret the entire data stream as a HTTP headera leading cause of errors. Other possible problems include:
If you get the dreaded error "premature end of script headers" from your web server, these issues are the first things to check. Newer versions of Ruby include the CGI support library cgi. Except for extremely simple CGIs, it's better to use this library than to simply write HTML to standard output. The CGI class makes it easy to retrieve HTTP request parameters and to manage cookies. It also provides custom methods for generating HTML, using Ruby code that has the same structure as the eventual output. Here's the code from ps.cgi, rewritten to use the CGI class. Instead of writing HTML, we make the CGI class do it. CGI also takes care of the content type, since we're using the default (text/html).
Since CGI allows any user to execute an external CGI program on your web server, security is of paramount importance. Popular CGI hacks include corrupting the program's input by inserting special characters in the QUERY_STRING, stealing confidential user data by modifying the parameters posted to the CGI program, and launching denial-of-service attacks to render the web server inoperable. CGI programs need to be carefully inspected for possible bugs and exploits. A few simple techniques will improve your security: call taint on external data, set your $SAFE variable to 1 or higher, and don't use methods like eval, system, or popen unless you have to. See Also
|
Friday, November 6, 2009
Recipe 14.16. Writing a CGI Script
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment