blob: e2bef264ad36e87663b578910dc566e63dbc58bd [file] [log] [blame]
Guido van Rossume7e578f1995-08-04 04:00:20 +00001"""CGI-savvy HTTP Server.
2
3This module builds on SimpleHTTPServer by implementing GET and POST
4requests to cgi-bin scripts.
5
Guido van Rossume7d6b0a2000-09-19 04:01:01 +00006If the os.fork() function is not present (e.g. on Windows),
7os.popen2() is used as a fallback, with slightly altered semantics; if
8that function is not present either (e.g. on Macintosh), only Python
9scripts are supported, and they are executed by the current process.
10
11In all cases, the implementation is intentionally naive -- all
12requests are executed sychronously.
13
14SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
15-- it may execute arbitrary Python code or external programs.
Fred Drake40e84db1999-10-16 02:07:50 +000016
Guido van Rossume7e578f1995-08-04 04:00:20 +000017"""
18
19
Guido van Rossume7d6b0a2000-09-19 04:01:01 +000020__version__ = "0.4"
Guido van Rossume7e578f1995-08-04 04:00:20 +000021
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000022__all__ = ["CGIHTTPRequestHandler"]
Guido van Rossume7e578f1995-08-04 04:00:20 +000023
24import os
Guido van Rossume7d6b0a2000-09-19 04:01:01 +000025import sys
Guido van Rossume7e578f1995-08-04 04:00:20 +000026import string
27import urllib
28import BaseHTTPServer
29import SimpleHTTPServer
30
31
32class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
33
34 """Complete HTTP server with GET, HEAD and POST commands.
35
36 GET and HEAD also support running CGI scripts.
37
38 The POST command is *only* implemented for CGI scripts.
39
40 """
41
Guido van Rossume7d6b0a2000-09-19 04:01:01 +000042 # Determine platform specifics
43 have_fork = hasattr(os, 'fork')
44 have_popen2 = hasattr(os, 'popen2')
45
Guido van Rossum6aefd912000-09-01 03:27:34 +000046 # Make rfile unbuffered -- we need to read one line and then pass
47 # the rest to a subprocess, so we can't use buffered input.
48 rbufsize = 0
49
Guido van Rossume7e578f1995-08-04 04:00:20 +000050 def do_POST(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000051 """Serve a POST request.
Guido van Rossume7e578f1995-08-04 04:00:20 +000052
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000053 This is only implemented for CGI scripts.
Guido van Rossume7e578f1995-08-04 04:00:20 +000054
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000055 """
Guido van Rossume7e578f1995-08-04 04:00:20 +000056
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000057 if self.is_cgi():
58 self.run_cgi()
59 else:
60 self.send_error(501, "Can only POST to CGI scripts")
Guido van Rossume7e578f1995-08-04 04:00:20 +000061
62 def send_head(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000063 """Version of send_head that support CGI scripts"""
64 if self.is_cgi():
65 return self.run_cgi()
66 else:
67 return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
Guido van Rossume7e578f1995-08-04 04:00:20 +000068
69 def is_cgi(self):
Guido van Rossume7d6b0a2000-09-19 04:01:01 +000070 """Test whether self.path corresponds to a CGI script.
Guido van Rossume7e578f1995-08-04 04:00:20 +000071
Guido van Rossume7d6b0a2000-09-19 04:01:01 +000072 Return a tuple (dir, rest) if self.path requires running a
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000073 CGI script, None if not. Note that rest begins with a
74 slash if it is not empty.
Guido van Rossume7e578f1995-08-04 04:00:20 +000075
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000076 The default implementation tests whether the path
77 begins with one of the strings in the list
78 self.cgi_directories (and the next character is a '/'
79 or the end of the string).
Guido van Rossume7e578f1995-08-04 04:00:20 +000080
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000081 """
Guido van Rossume7e578f1995-08-04 04:00:20 +000082
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000083 path = self.path
Guido van Rossume7e578f1995-08-04 04:00:20 +000084
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000085 for x in self.cgi_directories:
86 i = len(x)
87 if path[:i] == x and (not path[i:] or path[i] == '/'):
88 self.cgi_info = path[:i], path[i+1:]
89 return 1
90 return 0
Guido van Rossume7e578f1995-08-04 04:00:20 +000091
92 cgi_directories = ['/cgi-bin', '/htbin']
93
Guido van Rossume7d6b0a2000-09-19 04:01:01 +000094 def is_executable(self, path):
95 """Test whether argument path is an executable file."""
96 return executable(path)
97
98 def is_python(self, path):
99 """Test whether argument path is a Python script."""
100 head, tail = os.path.splitext(path)
101 return tail.lower() in (".py", ".pyw")
102
Guido van Rossume7e578f1995-08-04 04:00:20 +0000103 def run_cgi(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000104 """Execute a CGI script."""
105 dir, rest = self.cgi_info
106 i = string.rfind(rest, '?')
107 if i >= 0:
108 rest, query = rest[:i], rest[i+1:]
109 else:
110 query = ''
111 i = string.find(rest, '/')
112 if i >= 0:
113 script, rest = rest[:i], rest[i:]
114 else:
115 script, rest = rest, ''
116 scriptname = dir + '/' + script
117 scriptfile = self.translate_path(scriptname)
118 if not os.path.exists(scriptfile):
119 self.send_error(404, "No such CGI script (%s)" % `scriptname`)
120 return
121 if not os.path.isfile(scriptfile):
122 self.send_error(403, "CGI script is not a plain file (%s)" %
123 `scriptname`)
124 return
Guido van Rossume7d6b0a2000-09-19 04:01:01 +0000125 ispy = self.is_python(scriptname)
126 if not ispy:
127 if not (self.have_fork or self.have_popen2):
128 self.send_error(403, "CGI script is not a Python script (%s)" %
129 `scriptname`)
130 return
131 if not self.is_executable(scriptfile):
132 self.send_error(403, "CGI script is not executable (%s)" %
133 `scriptname`)
134 return
135
136 # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
137 # XXX Much of the following could be prepared ahead of time!
138 env = {}
139 env['SERVER_SOFTWARE'] = self.version_string()
140 env['SERVER_NAME'] = self.server.server_name
141 env['GATEWAY_INTERFACE'] = 'CGI/1.1'
142 env['SERVER_PROTOCOL'] = self.protocol_version
143 env['SERVER_PORT'] = str(self.server.server_port)
144 env['REQUEST_METHOD'] = self.command
145 uqrest = urllib.unquote(rest)
146 env['PATH_INFO'] = uqrest
147 env['PATH_TRANSLATED'] = self.translate_path(uqrest)
148 env['SCRIPT_NAME'] = scriptname
149 if query:
150 env['QUERY_STRING'] = query
151 host = self.address_string()
152 if host != self.client_address[0]:
153 env['REMOTE_HOST'] = host
154 env['REMOTE_ADDR'] = self.client_address[0]
155 # XXX AUTH_TYPE
156 # XXX REMOTE_USER
157 # XXX REMOTE_IDENT
158 if self.headers.typeheader is None:
159 env['CONTENT_TYPE'] = self.headers.type
160 else:
161 env['CONTENT_TYPE'] = self.headers.typeheader
162 length = self.headers.getheader('content-length')
163 if length:
164 env['CONTENT_LENGTH'] = length
165 accept = []
166 for line in self.headers.getallmatchingheaders('accept'):
167 if line[:1] in string.whitespace:
168 accept.append(string.strip(line))
Guido van Rossum01fc65d1998-05-13 20:13:24 +0000169 else:
Guido van Rossume7d6b0a2000-09-19 04:01:01 +0000170 accept = accept + string.split(line[7:], ',')
171 env['HTTP_ACCEPT'] = string.joinfields(accept, ',')
172 ua = self.headers.getheader('user-agent')
173 if ua:
174 env['HTTP_USER_AGENT'] = ua
175 co = filter(None, self.headers.getheaders('cookie'))
176 if co:
177 env['HTTP_COOKIE'] = string.join(co, ', ')
178 # XXX Other HTTP_* headers
179 if not self.have_fork:
180 # Since we're setting the env in the parent, provide empty
181 # values to override previously set values
182 for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
183 'HTTP_USER_AGENT', 'HTTP_COOKIE'):
184 env.setdefault(k, "")
185
186 self.send_response(200, "Script output follows")
187
188 decoded_query = string.replace(query, '+', ' ')
189
190 if self.have_fork:
191 # Unix -- fork as we should
192 args = [script]
193 if '=' not in decoded_query:
194 args.append(decoded_query)
195 nobody = nobody_uid()
196 self.wfile.flush() # Always flush before forking
197 pid = os.fork()
198 if pid != 0:
199 # Parent
200 pid, sts = os.waitpid(pid, 0)
201 if sts:
202 self.log_error("CGI script exit status %#x", sts)
203 return
204 # Child
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000205 try:
Guido van Rossume7d6b0a2000-09-19 04:01:01 +0000206 try:
207 os.setuid(nobody)
208 except os.error:
209 pass
210 os.dup2(self.rfile.fileno(), 0)
211 os.dup2(self.wfile.fileno(), 1)
212 os.execve(scriptfile, args, env)
213 except:
214 self.server.handle_error(self.request, self.client_address)
215 os._exit(127)
216
217 elif self.have_popen2:
218 # Windows -- use popen2 to create a subprocess
219 import shutil
220 os.environ.update(env)
221 cmdline = scriptfile
222 if self.is_python(scriptfile):
223 interp = sys.executable
224 if interp.lower().endswith("w.exe"):
225 # On Windows, use python.exe, not python.exe
226 interp = interp[:-5] = interp[-4:]
227 cmdline = "%s %s" % (interp, cmdline)
228 if '=' not in query and '"' not in query:
229 cmdline = '%s "%s"' % (cmdline, query)
230 self.log_error("command: %s", cmdline)
231 try:
232 nbytes = int(length)
233 except:
234 nbytes = 0
235 fi, fo = os.popen2(cmdline)
236 if self.command.lower() == "post" and nbytes > 0:
237 data = self.rfile.read(nbytes)
238 fi.write(data)
239 fi.close()
240 shutil.copyfileobj(fo, self.wfile)
241 sts = fo.close()
242 if sts:
243 self.log_error("CGI script exit status %#x", sts)
244 else:
245 self.log_error("CGI script exited OK")
246
247 else:
248 # Other O.S. -- execute script in this process
249 os.environ.update(env)
250 save_argv = sys.argv
251 save_stdin = sys.stdin
252 save_stdout = sys.stdout
253 save_stderr = sys.stderr
254 try:
255 try:
256 sys.argv = [scriptfile]
257 if '=' not in decoded_query:
258 sys.argv.append(decoded_query)
259 sys.stdout = self.wfile
260 sys.stdin = self.rfile
261 execfile(scriptfile, {"__name__": "__main__"})
262 finally:
263 sys.argv = save_argv
264 sys.stdin = save_stdin
265 sys.stdout = save_stdout
266 sys.stderr = save_stderr
267 except SystemExit, sts:
268 self.log_error("CGI script exit status %s", str(sts))
269 else:
270 self.log_error("CGI script exited OK")
Guido van Rossume7e578f1995-08-04 04:00:20 +0000271
272
273nobody = None
274
275def nobody_uid():
276 """Internal routine to get nobody's uid"""
277 global nobody
278 if nobody:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 return nobody
Guido van Rossume7d6b0a2000-09-19 04:01:01 +0000280 try:
281 import pwd
282 except ImportError:
283 return -1
Guido van Rossume7e578f1995-08-04 04:00:20 +0000284 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000285 nobody = pwd.getpwnam('nobody')[2]
Guido van Rossum630b8111999-04-28 12:21:47 +0000286 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000287 nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
Guido van Rossume7e578f1995-08-04 04:00:20 +0000288 return nobody
289
290
291def executable(path):
292 """Test for executable file."""
293 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000294 st = os.stat(path)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000295 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000296 return 0
Guido van Rossum13ad35a1996-01-25 18:23:50 +0000297 return st[0] & 0111 != 0
Guido van Rossume7e578f1995-08-04 04:00:20 +0000298
299
300def test(HandlerClass = CGIHTTPRequestHandler,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000301 ServerClass = BaseHTTPServer.HTTPServer):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000302 SimpleHTTPServer.test(HandlerClass, ServerClass)
303
304
305if __name__ == '__main__':
306 test()