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.5 2002-03-14 23:59:24 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 import cgitb, cgi_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 cgi_client.NotFound:
72 self.send_error(404, self.path)
73 except cgi_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 cgi_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 client = instance.Client(instance, self, env)
165 client.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] [name=instance home]*
173 -n: sets the host name
174 -p: sets the port to listen on
176 name=instance home
177 Sets the instance home(s) to use. The name is how the instance is
178 identified in the URL (it's the first part of the URL path). The
179 instance home is the directory that was identified when you did
180 "roundup-admin init". You may specify any number of these name=home
181 pairs on the command-line. For convenience, you may edit the
182 ROUNDUP_INSTANCE_HOMES variable in the roundup-server file instead.
183 ''')%locals()
184 sys.exit(0)
186 def run():
187 hostname = ''
188 port = 8080
189 try:
190 # handle the command-line args
191 try:
192 optlist, args = getopt.getopt(sys.argv[1:], 'n:p:u:')
193 except getopt.GetoptError, e:
194 usage(str(e))
196 user = ROUNDUP_USER
197 for (opt, arg) in optlist:
198 if opt == '-n': hostname = arg
199 elif opt == '-p': port = int(arg)
200 elif opt == '-u': user = arg
201 elif opt == '-h': usage()
203 if hasattr(os, 'getuid'):
204 # if root, setuid to the running user
205 if not os.getuid() and user is not None:
206 try:
207 import pwd
208 except ImportError:
209 raise ValueError, _("Can't change users - no pwd module")
210 try:
211 uid = pwd.getpwnam(user)[2]
212 except KeyError:
213 raise ValueError, _("User %(user)s doesn't exist")%locals()
214 os.setuid(uid)
215 elif os.getuid() and user is not None:
216 print _('WARNING: ignoring "-u" argument, not root')
218 # People can remove this check if they're really determined
219 if not os.getuid() and user is None:
220 raise ValueError, _("Can't run as root!")
222 # handle instance specs
223 if args:
224 d = {}
225 for arg in args:
226 try:
227 name, home = arg.split('=')
228 except ValueError:
229 raise ValueError, _("Instances must be name=home")
230 d[name] = home
231 RoundupRequestHandler.ROUNDUP_INSTANCE_HOMES = d
232 except SystemExit:
233 raise
234 except:
235 exc_type, exc_value = sys.exc_info()[:2]
236 usage('%s: %s'%(exc_type, exc_value))
238 # we don't want the cgi module interpreting the command-line args ;)
239 sys.argv = sys.argv[:1]
240 address = (hostname, port)
241 httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler)
242 print _('Roundup server started on %(address)s')%locals()
243 httpd.serve_forever()
245 if __name__ == '__main__':
246 run()
248 #
249 # $Log: not supported by cvs2svn $
250 # Revision 1.4 2002/02/21 07:02:54 richard
251 # The correct var is "HTTP_HOST"
252 #
253 # Revision 1.3 2002/02/21 06:57:39 richard
254 # . Added popup help for classes using the classhelp html template function.
255 # - add <display call="classhelp('priority', 'id,name,description')">
256 # to an item page, and it generates a link to a popup window which displays
257 # the id, name and description for the priority class. The description
258 # field won't exist in most installations, but it will be added to the
259 # default templates.
260 #
261 # Revision 1.2 2002/01/29 20:07:15 jhermann
262 # Conversion to generated script stubs
263 #
264 # Revision 1.1 2002/01/29 19:53:08 jhermann
265 # Moved scripts from top-level dir to roundup.scripts subpackage
266 #
267 # Revision 1.25 2002/01/05 02:21:21 richard
268 # fixes
269 #
270 # Revision 1.24 2002/01/05 02:19:03 richard
271 # i18n'ification
272 #
273 # Revision 1.23 2001/12/15 23:47:07 richard
274 # sys module went away...
275 #
276 # Revision 1.22 2001/12/13 00:20:01 richard
277 # . Centralised the python version check code, bumped version to 2.1.1 (really
278 # needs to be 2.1.2, but that isn't released yet :)
279 #
280 # Revision 1.21 2001/12/02 05:06:16 richard
281 # . We now use weakrefs in the Classes to keep the database reference, so
282 # the close() method on the database is no longer needed.
283 # I bumped the minimum python requirement up to 2.1 accordingly.
284 # . #487480 ] roundup-server
285 # . #487476 ] INSTALL.txt
286 #
287 # I also cleaned up the change message / post-edit stuff in the cgi client.
288 # There's now a clearly marked "TODO: append the change note" where I believe
289 # the change note should be added there. The "changes" list will obviously
290 # have to be modified to be a dict of the changes, or somesuch.
291 #
292 # More testing needed.
293 #
294 # Revision 1.20 2001/11/26 22:55:56 richard
295 # Feature:
296 # . Added INSTANCE_NAME to configuration - used in web and email to identify
297 # the instance.
298 # . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
299 # signature info in e-mails.
300 # . Some more flexibility in the mail gateway and more error handling.
301 # . Login now takes you to the page you back to the were denied access to.
302 #
303 # Fixed:
304 # . Lots of bugs, thanks Roché and others on the devel mailing list!
305 #
306 # Revision 1.19 2001/11/12 22:51:04 jhermann
307 # Fixed option & associated error handling
308 #
309 # Revision 1.18 2001/11/01 22:04:37 richard
310 # Started work on supporting a pop3-fetching server
311 # Fixed bugs:
312 # . bug #477104 ] HTML tag error in roundup-server
313 # . bug #477107 ] HTTP header problem
314 #
315 # Revision 1.17 2001/10/29 23:55:44 richard
316 # Fix to CGI top-level index (thanks Juergen Hermann)
317 #
318 # Revision 1.16 2001/10/27 00:12:21 richard
319 # Fixed roundup-server for windows, thanks Juergen Hermann.
320 #
321 # Revision 1.15 2001/10/12 02:23:26 richard
322 # Didn't clean up after myself :)
323 #
324 # Revision 1.14 2001/10/12 02:20:32 richard
325 # server now handles setuid'ing much better
326 #
327 # Revision 1.13 2001/10/05 02:23:24 richard
328 # . roundup-admin create now prompts for property info if none is supplied
329 # on the command-line.
330 # . hyperdb Class getprops() method may now return only the mutable
331 # properties.
332 # . Login now uses cookies, which makes it a whole lot more flexible. We can
333 # now support anonymous user access (read-only, unless there's an
334 # "anonymous" user, in which case write access is permitted). Login
335 # handling has been moved into cgi_client.Client.main()
336 # . The "extended" schema is now the default in roundup init.
337 # . The schemas have had their page headings modified to cope with the new
338 # login handling. Existing installations should copy the interfaces.py
339 # file from the roundup lib directory to their instance home.
340 # . Incorrectly had a Bizar Software copyright on the cgitb.py module from
341 # Ping - has been removed.
342 # . Fixed a whole bunch of places in the CGI interface where we should have
343 # been returning Not Found instead of throwing an exception.
344 # . Fixed a deviation from the spec: trying to modify the 'id' property of
345 # an item now throws an exception.
346 #
347 # Revision 1.12 2001/09/29 13:27:00 richard
348 # CGI interfaces now spit up a top-level index of all the instances they can
349 # serve.
350 #
351 # Revision 1.11 2001/08/07 00:24:42 richard
352 # stupid typo
353 #
354 # Revision 1.10 2001/08/07 00:15:51 richard
355 # Added the copyright/license notice to (nearly) all files at request of
356 # Bizar Software.
357 #
358 # Revision 1.9 2001/08/05 07:44:36 richard
359 # Instances are now opened by a special function that generates a unique
360 # module name for the instances on import time.
361 #
362 # Revision 1.8 2001/08/03 01:28:33 richard
363 # Used the much nicer load_package, pointed out by Steve Majewski.
364 #
365 # Revision 1.7 2001/08/03 00:59:34 richard
366 # Instance import now imports the instance using imp.load_module so that
367 # we can have instance homes of "roundup" or other existing python package
368 # names.
369 #
370 # Revision 1.6 2001/07/29 07:01:39 richard
371 # Added vim command to all source so that we don't get no steenkin' tabs :)
372 #
373 # Revision 1.5 2001/07/24 01:07:59 richard
374 # Added command-line arg handling to roundup-server so it's more useful
375 # out-of-the-box.
376 #
377 # Revision 1.4 2001/07/23 10:31:45 richard
378 # disabled the reloading until it can be done properly
379 #
380 # Revision 1.3 2001/07/23 08:53:44 richard
381 # Fixed the ROUNDUPS decl in roundup-server
382 # Move the installation notes to INSTALL
383 #
384 # Revision 1.2 2001/07/23 04:05:05 anthonybaxter
385 # actually quit if python version wrong
386 #
387 # Revision 1.1 2001/07/23 03:46:48 richard
388 # moving the bin files to facilitate out-of-the-boxness
389 #
390 # Revision 1.1 2001/07/22 11:15:45 richard
391 # More Grande Splite stuff
392 #
393 #
394 # vim: set filetype=python ts=4 sw=4 et si