TweetFollow Us on Twitter

Enabling CGI Scripts

Volume Number: 19 (2003)
Issue Number: 9
Column Tag: Programming

Untangling the Web

Enabling CGI Scripts

by Kevin Hemenway

Prepare your server for more powerful dynamic capabilities

Last month, we started down the road of adding dynamic content to our web server with the use of Server Side Includes (SSI). Often regarded as "simple" compared to languages like Perl and PHP, they can provide some quick turnaround to minor features like small single-item databases, changing content based on user whim or URL, and so forth. Regardless of whether you plan on using SSIs or not, we laid some important groundwork with our understanding of how modules work, Apache's "block" configuration format, and a soft introduction to GET and POST.

All relatively Lego. Let's break out the Technix.

A Quick 'How do ya do?' To CGI

SSI's are built into Apache through the use of a module--when they're enabled, the web server handles the request of a resource, processes the SSI statements within, and then sends the final output back to the user. Since Apache is a web server and not a programming language, the capabilities of the built-in SSIs are minimal--they're not intended to be a full-fledged coding environment, and they never will be.

This is where CGI comes in. Meaning "Common Gateway Interface", it defines a way for a web server to interact with external programs: Apache handles the request, sends some relevant information to the requested resource, and trusts the resource to handle the rest (including sending back the final content). If the resource doesn't respond properly (either due to bad programming, incorrect permissions, etc.), Apache generates an error.

What does this really mean? Ultimately, it allows you to use any shell programming language to "do stuff" before showing the results to your visitors. Whether this means displaying content from a database, resetting passwords, saving a comment to a weblog, etc., as long as your program finishes properly, Apache doesn't give a darn.

Most commonly, these "CGI scripts" are written in Perl, but you can use PHP, C, Bash, Ruby, Python, and anything else you may be interested in. Likewise, you can use them all in tandem--you're not locked into any one programming language at any one time. Be forewarned, however: you are locked into security concerns: anything possible in your programming language of choice is doable within your CGI script, including deletion of files, exhaustion of memory, buffer overflows, poor security, and impolite use of resources. Add in the fact that all of these errors in judgment become publicly run-able by anyone who accesses your server, and you've got a whole mess of potential trouble.

Enabling The Gateway to Your Scripts

Learning about CGI follows my oft-repeated method of "search the httpd.conf for the feature you want". So, open up /etc/httpd/httpd.conf in your favorite text editor and search for the word "CGI"--our first two matches look vaguely familiar:

LoadModule cgi_module         libexec/httpd/mod_cgi.so
AddModule mod_cgi.c

If you recall from our previous articles, Apache contains most of its features broken up into modules--the equivalent of plugins. To enable a module, two lines must exist uncommented (not preceded by a # character) in the httpd.conf file, an AddModule and a LoadModule. As previously with SSI, so too with CGI: our two lines already exist, and are already enabled. Let's move on to our next search result, which is also similar to what we saw last month:

<Directory "/Library/WebServer/Documents">
    # This may also be "None", "All", or any combination of 
    # "Indexes", "Includes", "FollowSymLinks", "ExecCGI",   
    # or "MultiViews".
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

Whereas last article the above result was triggered by the word Includes, it's ExecCGI this time around. Unfortunately, explaining ExecCGI without some prior knowledge will cause a little bit of confusion, so let's skip ahead to our next few matches before we go much further. I've truncated them for relevance:

# ScriptAlias: This controls which directories
# contain server scripts. ScriptAliases are essentially
# the same as Aliases, except that documents in the 
# realname directory are treated as applications and
# run by the server when requested rather than as
# documents sent to the client. 
#
ScriptAlias /cgi-bin/ "/Library/WebServer/CGI-Executables/"
# "/Library/WebServer/CGI-Executables" should be changed
# to whatever your ScriptAliased CGI directory exists,
# if you have that configured.
#
<Directory "/Library/WebServer/CGI-Executables">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

The most common CGI configuration is all about segregation: "only files in this directory should be executed as programs--everything else, anywhere else, are just plain old files that should be processed normally." From the standpoint of an overbearing system administrator, this makes sense. With only one directory that can execute code unconditionally, and only one person (you) who can put programs there, it can bring a little sanity to your day-to-day security paranoia.

This is how Apache is configured by default, and the above httpd.conf snippet shows these settings. Our first directive, ScriptAlias, lets us pick and choose which directory we'd like CGI scripts to live in. Anything within that directory, CGI script or not, will be executed by the web server as if it were a program. If something goes wrong, Apache will return an "Internal Server Error" to the requesting user-agent (ie. your visitor's browser).

ScriptAlias consists of two space-separated parts: the fake name and the real name. The fake name, /cgi-bin/, defines what URL will be used to access the real name, /Library/WebServer/CGI-Executables/. In the currently configured settings, whenever we access a URL like http://127.0.0.1/cgi-bin/printenv, we'll really be accessing the matching file stored at /Library/WebServer/CGI-Executables/printenv.

The second part of our configuration is a block directive focusing on that specific location of our hard drive. It merely ensures that said directory has no special privileges besides that ScriptAlias: it can't override anything in the Apache configuration (AllowOverride None), and there are no special capabilities (Options None) associated with it.

At this point, if you only care about the directory segregation of CGI, you can skip over to our next subheading, "Let's See One of These CGI Thingies In Action!" If, on the other hand, you'd like to hear me get high-and-mighty over the "right" way of doing things, read on.

CGI EVERYWHERE: "A Brilliant Psychological Thriller!"

In the very first "Untangling the Web", I professed a fondness and desire to teach you the "right" way to create URLs (MacTech Magazine, June 2003, "Untangling The Web", "Familiarity That Breeds An Uh-Oh!"). A good URL will remain in existence until the dusk of time, never needing to be changed, never needing to be refactored. It's not a snap-decision: if you find yourself changing your URLs around, you designed your site poorly (from an engineering, not visual, standpoint).

One of the maxims, which I'll reiterate here, is that "Your URLs Should Not Reveal Your Technical Capabilities". This has absolutely nothing to do with the oft-maligned "security through obscurity"--the belief that hiding information makes you less susceptible to risk. Instead, removing the technicalities of your URL will allow your site to grow with your needs.

Consider the default configuration of CGI: anytime you want to add some dynamic functionality to your site (with Perl, Python, etc.), you've got to stick your script in a directory and point to it with a URL like http://127.0.0.1/cgi-bin/add_user.pl (where .pl denotes a Perl script) or http://127.0.0.1/cgi-bin/del_user.py (.py denoting Python). What happens, though, when you no longer need CGI scripts, but have moved to an embedded language like PHP? Suddenly, all of your pages that point to that ugly /cgi-bin/ URL are broken, useless, and inaccurate. You find yourself refactoring pages to point to new locations.

The solution? Remove /cgi-bin/ and the file extension from the URL. By clearing this needless technical cruft, you get stronger addresses with less need for change. http://127.0.0.1/admin/add_user and http://127.0.0.1/admin/del_user contain no indication of the technology behind them, merely their purpose in the grande scheme of things.

We're already halfway through removing /cgi-bin/ from our URLs (file extensions I keep putting off, but I'll get to 'em eventually, I promise!). Our very first match for our "CGI" search was for an ExecCGI addition to the Options line of our root web directory (/Library/WebServer/Documents/). ExecCGI works similarly to Includes, which helped get our SSIs running last month. By adding it to the Options line of any Directory we, like SSIs, are telling Apache to allow CGI scripts at that location:

Options Indexes FollowSymLinks MultiViews ExecCGI

To make the comparison even more apt, there's one other thing we need to do before we can use CGIs wherever we need them: we need to add a handler that says "Apache! Listen up! Whenever we request a file with this extension, we want you to treat it as an executable program!" This handler was also needed last month--we told Apache that anytime it ran across a file with an shtml extension, it should process it for SSIs statements.

Thankfully, there's not much brainwork involved here, as our final relevant search match for "CGI" brings us to the below. Simply uncomment the AddHandler (by removing the #), restart Apache (sudo apachectl restart in your Terminal) and you're ready to go:

# If you want to use server side includes, or CGI outside
# ScriptAliased directories, uncomment the following lines.
#
# To use CGI scripts:
#
#AddHandler cgi-script .cgi

Two caveats that may be running through head: "what about the cgi extension?" and "what about that security brouhaha you cautioned us about?" Concerning the file extension, yes, we're swapping /cgi-bin/ for cgi, but this will never be an issue once we remove the need for them in our URLs. As for security, there's not much I can say besides "be careful"--you'll no longer have the niceties of a single and central directory for your code execution, so double and triple check the scripts you'll be programming or using. I'll talk a little more about script security in next month's column.

Let's See One of These CGI Thingies In Action!

Browse to your /Library/WebServer/CGI-Executables/ directory, the default location that Apache has been configured for CGI scripts. You should see two files, printenv and test-cgi, there already. These are some default Apache CGI scripts that will help you quickly test if things are a-ok. Since CGI was already pre-configured in the httpd.conf, we should be able to just load one of these files in the browser and see some fireworks, right? Load http://127.0.0.1/cgi-bin/test-cgi, and we'll receive the response in Figure 1.


Figure 1: An error after loading our test-cgi, but why?

If CGI scripts were already configured, why this rather rude error message? Let's check Apache's error_log, which will always contain some sort of light bulb enlightening response. After running tail /var/log/httpd/error_log on the command line, we'll see something similar to the below as the last line of output:

[Sun Aug 17 10:41:16 2003] [error] [client 127.0.0.1] file 
permissions deny server execution: /Library/WebServer/CGI-
Executables/test-cgi

This is one of the more common errors you'll experience with CGI scripts: the test-cgi file doesn't have the proper credentials to be considered an executable program. I won't get into the vagaries of file ownership or permissions, but follow through the bolded commands below to give both of the default CGI files "execute" access for all users:

> cd /Library/WebServer/CGI-Executables/
> ls -l
total 24
-rw-r--r--  1 root  admin  5398 Jul 27  2002 printenv
-rw-r--r--  1 root  admin   757 Jul 27  2002 test-cgi
> sudo chmod 755 *
Password: **********
> ls -l
total 24
-rwxr-xr-x  1 root  admin  5398 Jul 27  2002 printenv
-rwxr-xr-x  1 root  admin   757 Jul 27  2002 test-cgi

Now, let's try our URL again. Figure 2 shows our new output:


Figure 2: The correct output of our test-cgi script.

Figure 3 shows the output from the other script, http://127.0.0.1/cgi-bin/printenv:


Figure 3: Similar output from the default printenv script.

If you followed the instructions under the "CGI EVERYWHERE!" subheading, you can also move either of the printenv or test-cgi scripts out of their current location and stick them in /Library/WebServer/Documents/ with a cgi file extension. Once you do so, you should then be able to run them under the non-/cgi-bin/ URL and receive the same output (if not, what's your first course of action? Check the error_log!).

Assuming you get similar output as Figures 2 and 3, what does all this gibberish mean? What exactly did we just do? Both scripts show a number of environment variables, which is just a fancy term for data that exists "invisibly" and floats around waiting to be used or read. Some of the variables were set by the browser (like HTTP_USER_AGENT), and some have been set by the server (like SERVER_PROTOCOL). When I first introduced CGI, I mentioned that Apache "sends some relevant information to the requested resource". This "relevant information" is stored in environment variables.

Environment variables can exist outside of your web server too. For instance, if you run printenv in your Terminal, you'll see a listing of variables similar to Figure 4:


Figure 4: Environment variables in your Terminal.

Believe it or not, we've dealt with environment variables already in this series. In our article on Server Side Includes, we checked the $QUERY_STRING variable to see which quote should be displayed at the user's request. If you check back to Figure 3, you'll see an environment variable named QUERY_STRING, which is currently empty. Try adding ?q02 to the end of our URL (http://127.0.0.1/cgi-bin/printenv?q02), and see how that changes the output (Figure 5):


Figure 5: Our QUERY_STRING now has a value.

With the above two scripts working correctly, our CGI capabilities are ready for use.

Homework Malignments

In our next column, we'll chat further about CGI: how to begin creating our own, the most common errors during development and deployment, security issues we should be aware of, and how to find the "good ones" from the immense ocean of crap. If we have time, we'll show you how to install a few that have stood the test of time. For now, students may contact the teacher at morbus@disobey.com.

  • Take a look inside printenv and test-cgi in a text editor.

  • View the printenv script from various browsers and machines. Determine how the output changes, and see if you can figure out what each setting actually means.

  • Forgive me for not including anything amusing in this article.


Kevin Hemenway, coauthor of Mac OS X Hacks, is better known as Morbus Iff, the creator of disobey.com, which bills itself as "content for the discontented." Publisher and developer of more home cooking than you could ever imagine (like the popular open-sourced aggregator AmphetaDesk, the best-kept gaming secret Gamegrene.com, articles for Apple's Internet Developer and the O'Reilly Network, etc.), he's been spending the last two months listening to every song in his iTunes library twice. Contact him at morbus@disobey.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.