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