1 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
2 # This module is free software, and you may redistribute it and/or modify
3 # under the same terms as Python, so long as this copyright message and
4 # disclaimer are retained in their original form.
5 #
6 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
7 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
8 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
9 # POSSIBILITY OF SUCH DAMAGE.
10 #
11 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
12 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
13 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
14 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
15 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
16 #
17 """ HTTP Server that serves roundup.
19 $Id: roundup_server.py,v 1.8 2002-09-07 22:46:19 richard Exp $
20 """
22 # python version check
23 from roundup import version_check
25 import sys, os, urllib, StringIO, traceback, cgi, binascii, getopt, imp
26 import BaseHTTPServer
28 # Roundup modules of use here
29 from roundup.cgi import cgitb, client
30 import roundup.instance
31 from roundup.i18n import _
33 #
34 ## Configuration
35 #
37 # This indicates where the Roundup instance lives
38 ROUNDUP_INSTANCE_HOMES = {
39 'bar': '/tmp/bar',
40 }
42 ROUNDUP_USER = None
45 # Where to log debugging information to. Use an instance of DevNull if you
46 # don't want to log anywhere.
47 # TODO: actually use this stuff
48 #class DevNull:
49 # def write(self, info):
50 # pass
51 #LOG = open('/var/log/roundup.cgi.log', 'a')
52 #LOG = DevNull()
54 #
55 ## end configuration
56 #
59 class RoundupRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
60 ROUNDUP_INSTANCE_HOMES = ROUNDUP_INSTANCE_HOMES
61 ROUNDUP_USER = ROUNDUP_USER
63 def run_cgi(self):
64 """ Execute the CGI command. Wrap an innner call in an error
65 handler so all errors can be caught.
66 """
67 save_stdin = sys.stdin
68 sys.stdin = self.rfile
69 try:
70 self.inner_run_cgi()
71 except client.NotFound:
72 self.send_error(404, self.path)
73 except client.Unauthorised:
74 self.send_error(403, self.path)
75 except:
76 # it'd be nice to be able to detect if these are going to have
77 # any effect...
78 self.send_response(400)
79 self.send_header('Content-Type', 'text/html')
80 self.end_headers()
81 try:
82 reload(cgitb)
83 self.wfile.write(cgitb.breaker())
84 self.wfile.write(cgitb.html())
85 except:
86 self.wfile.write("<pre>")
87 s = StringIO.StringIO()
88 traceback.print_exc(None, s)
89 self.wfile.write(cgi.escape(s.getvalue()))
90 self.wfile.write("</pre>\n")
91 sys.stdin = save_stdin
93 do_GET = do_POST = do_HEAD = send_head = run_cgi
95 def index(self):
96 ''' Print up an index of the available instances
97 '''
98 self.send_response(200)
99 self.send_header('Content-Type', 'text/html')
100 self.end_headers()
101 w = self.wfile.write
102 w(_('<html><head><title>Roundup instances index</title></head>\n'))
103 w(_('<body><h1>Roundup instances index</h1><ol>\n'))
104 for instance in self.ROUNDUP_INSTANCE_HOMES.keys():
105 w(_('<li><a href="%(instance_url)s/index">%(instance_name)s</a>\n')%{
106 'instance_url': urllib.quote(instance),
107 'instance_name': cgi.escape(instance)})
108 w(_('</ol></body></html>'))
110 def inner_run_cgi(self):
111 ''' This is the inner part of the CGI handling
112 '''
114 rest = self.path
115 i = rest.rfind('?')
116 if i >= 0:
117 rest, query = rest[:i], rest[i+1:]
118 else:
119 query = ''
121 # figure the instance
122 if rest == '/':
123 return self.index()
124 l_path = rest.split('/')
125 instance_name = urllib.unquote(l_path[1])
126 if self.ROUNDUP_INSTANCE_HOMES.has_key(instance_name):
127 instance_home = self.ROUNDUP_INSTANCE_HOMES[instance_name]
128 instance = roundup.instance.open(instance_home)
129 else:
130 raise client.NotFound
132 # figure out what the rest of the path is
133 if len(l_path) > 2:
134 rest = '/'.join(l_path[2:])
135 else:
136 rest = '/'
138 # Set up the CGI environment
139 env = {}
140 env['INSTANCE_NAME'] = instance_name
141 env['REQUEST_METHOD'] = self.command
142 env['PATH_INFO'] = urllib.unquote(rest)
143 if query:
144 env['QUERY_STRING'] = query
145 host = self.address_string()
146 if self.headers.typeheader is None:
147 env['CONTENT_TYPE'] = self.headers.type
148 else:
149 env['CONTENT_TYPE'] = self.headers.typeheader
150 length = self.headers.getheader('content-length')
151 if length:
152 env['CONTENT_LENGTH'] = length
153 co = filter(None, self.headers.getheaders('cookie'))
154 if co:
155 env['HTTP_COOKIE'] = ', '.join(co)
156 env['SCRIPT_NAME'] = ''
157 env['SERVER_NAME'] = self.server.server_name
158 env['SERVER_PORT'] = str(self.server.server_port)
159 env['HTTP_HOST'] = self.headers['host']
161 decoded_query = query.replace('+', ' ')
163 # do the roundup thang
164 c = instance.Client(instance, self, env)
165 c.main()
167 def usage(message=''):
168 if message:
169 message = _('Error: %(error)s\n\n')%{'error': message}
170 print _('''%(message)sUsage:
171 roundup-server [-n hostname] [-p port] [-l file] [-d file] [name=instance home]*
173 -n: sets the host name
174 -p: sets the port to listen on
175 -l: sets a filename to log to (instead of stdout)
176 -d: daemonize, and write the server's PID to the nominated file
178 name=instance home
179 Sets the instance home(s) to use. The name is how the instance is
180 identified in the URL (it's the first part of the URL path). The
181 instance home is the directory that was identified when you did
182 "roundup-admin init". You may specify any number of these name=home
183 pairs on the command-line. For convenience, you may edit the
184 ROUNDUP_INSTANCE_HOMES variable in the roundup-server file instead.
185 ''')%locals()
186 sys.exit(0)
188 def daemonize(pidfile):
189 ''' Turn this process into a daemon.
190 - make sure the sys.std(in|out|err) are completely cut off
191 - make our parent PID 1
193 Write our new PID to the pidfile.
195 From A.M. Kuuchling (possibly originally Greg Ward) with
196 modification from Oren Tirosh, and finally a small mod from me.
197 '''
198 # Fork once
199 if os.fork() != 0:
200 os._exit(0)
202 # Create new session
203 os.setsid()
205 # Second fork to force PPID=1
206 pid = os.fork()
207 if pid:
208 pidfile = open(pidfile, 'w')
209 pidfile.write(str(pid))
210 pidfile.close()
211 os._exit(0)
213 os.chdir("/")
214 os.umask(0)
216 # close off sys.std(in|out|err), redirect to devnull so the file
217 # descriptors can't be used again
218 devnull = os.open('/dev/null', 0)
219 os.dup2(devnull, 0)
220 os.dup2(devnull, 1)
221 os.dup2(devnull, 2)
223 def run():
224 hostname = ''
225 port = 8080
226 pidfile = None
227 logfile = None
228 try:
229 # handle the command-line args
230 try:
231 optlist, args = getopt.getopt(sys.argv[1:], 'n:p:u:d:l:')
232 except getopt.GetoptError, e:
233 usage(str(e))
235 user = ROUNDUP_USER
236 for (opt, arg) in optlist:
237 if opt == '-n': hostname = arg
238 elif opt == '-p': port = int(arg)
239 elif opt == '-u': user = arg
240 elif opt == '-d': pidfile = arg
241 elif opt == '-l': logfile = arg
242 elif opt == '-h': usage()
244 if hasattr(os, 'getuid'):
245 # if root, setuid to the running user
246 if not os.getuid() and user is not None:
247 try:
248 import pwd
249 except ImportError:
250 raise ValueError, _("Can't change users - no pwd module")
251 try:
252 uid = pwd.getpwnam(user)[2]
253 except KeyError:
254 raise ValueError, _("User %(user)s doesn't exist")%locals()
255 os.setuid(uid)
256 elif os.getuid() and user is not None:
257 print _('WARNING: ignoring "-u" argument, not root')
259 # People can remove this check if they're really determined
260 if not os.getuid() and user is None:
261 raise ValueError, _("Can't run as root!")
263 # handle instance specs
264 if args:
265 d = {}
266 for arg in args:
267 try:
268 name, home = arg.split('=')
269 except ValueError:
270 raise ValueError, _("Instances must be name=home")
271 d[name] = home
272 RoundupRequestHandler.ROUNDUP_INSTANCE_HOMES = d
273 except SystemExit:
274 raise
275 except:
276 exc_type, exc_value = sys.exc_info()[:2]
277 usage('%s: %s'%(exc_type, exc_value))
279 # we don't want the cgi module interpreting the command-line args ;)
280 sys.argv = sys.argv[:1]
281 address = (hostname, port)
283 # fork?
284 if pidfile:
285 daemonize(pidfile)
287 # redirect stdout/stderr to our logfile
288 if logfile:
289 sys.stdout = sys.stderr = open(logfile, 'a')
291 httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler)
292 print _('Roundup server started on %(address)s')%locals()
293 httpd.serve_forever()
295 if __name__ == '__main__':
296 run()
298 #
299 # $Log: not supported by cvs2svn $
300 # Revision 1.7 2002/09/04 07:32:55 richard
301 # add daemonification
302 #
303 # Revision 1.6 2002/08/30 08:33:28 richard
304 # new CGI frontend support
305 #
306 # Revision 1.5 2002/03/14 23:59:24 richard
307 # . #517734 ] web header customisation is obscure
308 #
309 # Revision 1.4 2002/02/21 07:02:54 richard
310 # The correct var is "HTTP_HOST"
311 #
312 # Revision 1.3 2002/02/21 06:57:39 richard
313 # . Added popup help for classes using the classhelp html template function.
314 # - add <display call="classhelp('priority', 'id,name,description')">
315 # to an item page, and it generates a link to a popup window which displays
316 # the id, name and description for the priority class. The description
317 # field won't exist in most installations, but it will be added to the
318 # default templates.
319 #
320 # Revision 1.2 2002/01/29 20:07:15 jhermann
321 # Conversion to generated script stubs
322 #
323 # Revision 1.1 2002/01/29 19:53:08 jhermann
324 # Moved scripts from top-level dir to roundup.scripts subpackage
325 #
326 # Revision 1.25 2002/01/05 02:21:21 richard
327 # fixes
328 #
329 # Revision 1.24 2002/01/05 02:19:03 richard
330 # i18n'ification
331 #
332 # Revision 1.23 2001/12/15 23:47:07 richard
333 # sys module went away...
334 #
335 # Revision 1.22 2001/12/13 00:20:01 richard
336 # . Centralised the python version check code, bumped version to 2.1.1 (really
337 # needs to be 2.1.2, but that isn't released yet :)
338 #
339 # Revision 1.21 2001/12/02 05:06:16 richard
340 # . We now use weakrefs in the Classes to keep the database reference, so
341 # the close() method on the database is no longer needed.
342 # I bumped the minimum python requirement up to 2.1 accordingly.
343 # . #487480 ] roundup-server
344 # . #487476 ] INSTALL.txt
345 #
346 # I also cleaned up the change message / post-edit stuff in the cgi client.
347 # There's now a clearly marked "TODO: append the change note" where I believe
348 # the change note should be added there. The "changes" list will obviously
349 # have to be modified to be a dict of the changes, or somesuch.
350 #
351 # More testing needed.
352 #
353 # Revision 1.20 2001/11/26 22:55:56 richard
354 # Feature:
355 # . Added INSTANCE_NAME to configuration - used in web and email to identify
356 # the instance.
357 # . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
358 # signature info in e-mails.
359 # . Some more flexibility in the mail gateway and more error handling.
360 # . Login now takes you to the page you back to the were denied access to.
361 #
362 # Fixed:
363 # . Lots of bugs, thanks Roché and others on the devel mailing list!
364 #
365 # Revision 1.19 2001/11/12 22:51:04 jhermann
366 # Fixed option & associated error handling
367 #
368 # Revision 1.18 2001/11/01 22:04:37 richard
369 # Started work on supporting a pop3-fetching server
370 # Fixed bugs:
371 # . bug #477104 ] HTML tag error in roundup-server
372 # . bug #477107 ] HTTP header problem
373 #
374 # Revision 1.17 2001/10/29 23:55:44 richard
375 # Fix to CGI top-level index (thanks Juergen Hermann)
376 #
377 # Revision 1.16 2001/10/27 00:12:21 richard
378 # Fixed roundup-server for windows, thanks Juergen Hermann.
379 #
380 # Revision 1.15 2001/10/12 02:23:26 richard
381 # Didn't clean up after myself :)
382 #
383 # Revision 1.14 2001/10/12 02:20:32 richard
384 # server now handles setuid'ing much better
385 #
386 # Revision 1.13 2001/10/05 02:23:24 richard
387 # . roundup-admin create now prompts for property info if none is supplied
388 # on the command-line.
389 # . hyperdb Class getprops() method may now return only the mutable
390 # properties.
391 # . Login now uses cookies, which makes it a whole lot more flexible. We can
392 # now support anonymous user access (read-only, unless there's an
393 # "anonymous" user, in which case write access is permitted). Login
394 # handling has been moved into cgi_client.Client.main()
395 # . The "extended" schema is now the default in roundup init.
396 # . The schemas have had their page headings modified to cope with the new
397 # login handling. Existing installations should copy the interfaces.py
398 # file from the roundup lib directory to their instance home.
399 # . Incorrectly had a Bizar Software copyright on the cgitb.py module from
400 # Ping - has been removed.
401 # . Fixed a whole bunch of places in the CGI interface where we should have
402 # been returning Not Found instead of throwing an exception.
403 # . Fixed a deviation from the spec: trying to modify the 'id' property of
404 # an item now throws an exception.
405 #
406 # Revision 1.12 2001/09/29 13:27:00 richard
407 # CGI interfaces now spit up a top-level index of all the instances they can
408 # serve.
409 #
410 # Revision 1.11 2001/08/07 00:24:42 richard
411 # stupid typo
412 #
413 # Revision 1.10 2001/08/07 00:15:51 richard
414 # Added the copyright/license notice to (nearly) all files at request of
415 # Bizar Software.
416 #
417 # Revision 1.9 2001/08/05 07:44:36 richard
418 # Instances are now opened by a special function that generates a unique
419 # module name for the instances on import time.
420 #
421 # Revision 1.8 2001/08/03 01:28:33 richard
422 # Used the much nicer load_package, pointed out by Steve Majewski.
423 #
424 # Revision 1.7 2001/08/03 00:59:34 richard
425 # Instance import now imports the instance using imp.load_module so that
426 # we can have instance homes of "roundup" or other existing python package
427 # names.
428 #
429 # Revision 1.6 2001/07/29 07:01:39 richard
430 # Added vim command to all source so that we don't get no steenkin' tabs :)
431 #
432 # Revision 1.5 2001/07/24 01:07:59 richard
433 # Added command-line arg handling to roundup-server so it's more useful
434 # out-of-the-box.
435 #
436 # Revision 1.4 2001/07/23 10:31:45 richard
437 # disabled the reloading until it can be done properly
438 #
439 # Revision 1.3 2001/07/23 08:53:44 richard
440 # Fixed the ROUNDUPS decl in roundup-server
441 # Move the installation notes to INSTALL
442 #
443 # Revision 1.2 2001/07/23 04:05:05 anthonybaxter
444 # actually quit if python version wrong
445 #
446 # Revision 1.1 2001/07/23 03:46:48 richard
447 # moving the bin files to facilitate out-of-the-boxness
448 #
449 # Revision 1.1 2001/07/22 11:15:45 richard
450 # More Grande Splite stuff
451 #
452 #
453 # vim: set filetype=python ts=4 sw=4 et si