Code

Minor change
[roundup.git] / roundup-server
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 Based on CGIHTTPServer in the Python library.
23 $Id: roundup-server,v 1.23 2001-12-15 23:47:07 richard Exp $
25 """
27 # python version check
28 from roundup import version_check
30 import sys, os, urllib, StringIO, traceback, cgi, binascii, getopt, imp
31 import BaseHTTPServer
33 # Roundup modules of use here
34 from roundup import cgitb, cgi_client
35 import roundup.instance
37 #
38 ##  Configuration
39 #
41 # This indicates where the Roundup instance lives
42 ROUNDUP_INSTANCE_HOMES = {
43     'bar': '/tmp/bar',
44 }
46 ROUNDUP_USER = None
49 # Where to log debugging information to. Use an instance of DevNull if you
50 # don't want to log anywhere.
51 # TODO: actually use this stuff
52 #class DevNull:
53 #    def write(self, info):
54 #        pass
55 #LOG = open('/var/log/roundup.cgi.log', 'a')
56 #LOG = DevNull()
58 #
59 ##  end configuration
60 #
63 class RoundupRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
64     ROUNDUP_INSTANCE_HOMES = ROUNDUP_INSTANCE_HOMES
65     ROUNDUP_USER = ROUNDUP_USER
67     def run_cgi(self):
68         """ Execute the CGI command. Wrap an innner call in an error
69             handler so all errors can be caught.
70         """
71         save_stdin = sys.stdin
72         sys.stdin = self.rfile
73         try:
74             self.inner_run_cgi()
75         except cgi_client.NotFound:
76             self.send_error(404, self.path)
77         except cgi_client.Unauthorised:
78             self.send_error(403, self.path)
79         except:
80             # it'd be nice to be able to detect if these are going to have
81             # any effect...
82             self.send_response(400)
83             self.send_header('Content-Type', 'text/html')
84             self.end_headers()
85             try:
86                 reload(cgitb)
87                 self.wfile.write(cgitb.breaker())
88                 self.wfile.write(cgitb.html())
89             except:
90                 self.wfile.write("<pre>")
91                 s = StringIO.StringIO()
92                 traceback.print_exc(None, s)
93                 self.wfile.write(cgi.escape(s.getvalue()))
94                 self.wfile.write("</pre>\n")
95         sys.stdin = save_stdin
97     do_GET = do_POST = do_HEAD = send_head = run_cgi
99     def index(self):
100         ''' Print up an index of the available instances
101         '''
102         self.send_response(200)
103         self.send_header('Content-Type', 'text/html')
104         self.end_headers()
105         w = self.wfile.write
106         w('<html><head><title>Roundup instances index</title></head>\n')
107         w('<body><h1>Roundup instances index</h1><ol>\n')
108         for instance in self.ROUNDUP_INSTANCE_HOMES.keys():
109             w('<li><a href="%s/index">%s</a>\n'%(urllib.quote(instance),
110                 cgi.escape(instance)))
111         w('</ol></body></html>')
113     def inner_run_cgi(self):
114         ''' This is the inner part of the CGI handling
115         '''
117         rest = self.path
118         i = rest.rfind('?')
119         if i >= 0:
120             rest, query = rest[:i], rest[i+1:]
121         else:
122             query = ''
124         # figure the instance
125         if rest == '/':
126             return self.index()
127         l_path = rest.split('/')
128         instance_name = urllib.unquote(l_path[1])
129         if self.ROUNDUP_INSTANCE_HOMES.has_key(instance_name):
130             instance_home = self.ROUNDUP_INSTANCE_HOMES[instance_name]
131             instance = roundup.instance.open(instance_home)
132         else:
133             raise cgi_client.NotFound
135         # figure out what the rest of the path is
136         if len(l_path) > 2:
137             rest = '/'.join(l_path[2:])
138         else:
139             rest = '/'
141         # Set up the CGI environment
142         env = {}
143         env['INSTANCE_NAME'] = instance_name
144         env['REQUEST_METHOD'] = self.command
145         env['PATH_INFO'] = urllib.unquote(rest)
146         if query:
147             env['QUERY_STRING'] = query
148         host = self.address_string()
149         if self.headers.typeheader is None:
150             env['CONTENT_TYPE'] = self.headers.type
151         else:
152             env['CONTENT_TYPE'] = self.headers.typeheader
153         length = self.headers.getheader('content-length')
154         if length:
155             env['CONTENT_LENGTH'] = length
156         co = filter(None, self.headers.getheaders('cookie'))
157         if co:
158             env['HTTP_COOKIE'] = ', '.join(co)
159         env['SCRIPT_NAME'] = ''
160         env['SERVER_NAME'] = self.server.server_name
161         env['SERVER_PORT'] = str(self.server.server_port)
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: message = 'Error: %s\n\n'%message
171     print '''%sUsage:
172 roundup-server [-n hostname] [-p port] [name=instance home]*
174  -n: sets the host name
175  -p: sets the port to listen on
177  name=instance home
178    Sets the instance home(s) to use. The name is how the instance is
179    identified in the URL (it's the first part of the URL path). The
180    instance home is the directory that was identified when you did
181    "roundup-admin init". You may specify any number of these name=home
182    pairs on the command-line. For convenience, you may edit the
183    ROUNDUP_INSTANCE_HOMES variable in the roundup-server file instead.
184 '''%message
185     sys.exit(0)
187 def main():
188     hostname = ''
189     port = 8080
190     try:
191         # handle the command-line args
192         try:
193             optlist, args = getopt.getopt(sys.argv[1:], 'n:p:u:')
194         except getopt.GetoptError, e:
195             usage(str(e))
197         user = ROUNDUP_USER
198         for (opt, arg) in optlist:
199             if opt == '-n': hostname = arg
200             elif opt == '-p': port = int(arg)
201             elif opt == '-u': user = arg
202             elif opt == '-h': usage()
204         if hasattr(os, 'getuid'):
205             # if root, setuid to the running user
206             if not os.getuid() and user is not None:
207                 try:
208                     import pwd
209                 except ImportError:
210                     raise ValueError, "Can't change users - no pwd module"
211                 try:
212                     uid = pwd.getpwnam(user)[2]
213                 except KeyError:
214                     raise ValueError, "User %s doesn't exist"%user
215                 os.setuid(uid)
216             elif os.getuid() and user is not None:
217                 print 'WARNING: ignoring "-u" argument, not root'
219             # People can remove this check if they're really determined
220             if not os.getuid() and user is None:
221                 raise ValueError, "Can't run as root!"
223         # handle instance specs
224         if args:
225             d = {}
226             for arg in args:
227                 try:
228                     name, home = arg.split('=')
229                 except ValueError:
230                     raise ValueError, "Instances must be name=home"
231                 d[name] = home
232             RoundupRequestHandler.ROUNDUP_INSTANCE_HOMES = d
233     except SystemExit:
234         raise
235     except:
236         exc_type, exc_value = sys.exc_info()[:2]
237         usage('%s: %s'%(exc_type, exc_value))
239     # we don't want the cgi module interpreting the command-line args ;)
240     sys.argv = sys.argv[:1]
241     address = (hostname, port)
242     httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler)
243     print 'Roundup server started on', address
244     httpd.serve_forever()
246 if __name__ == '__main__':
247     main()
250 # $Log: not supported by cvs2svn $
251 # Revision 1.22  2001/12/13 00:20:01  richard
252 #  . Centralised the python version check code, bumped version to 2.1.1 (really
253 #    needs to be 2.1.2, but that isn't released yet :)
255 # Revision 1.21  2001/12/02 05:06:16  richard
256 # . We now use weakrefs in the Classes to keep the database reference, so
257 #   the close() method on the database is no longer needed.
258 #   I bumped the minimum python requirement up to 2.1 accordingly.
259 # . #487480 ] roundup-server
260 # . #487476 ] INSTALL.txt
262 # I also cleaned up the change message / post-edit stuff in the cgi client.
263 # There's now a clearly marked "TODO: append the change note" where I believe
264 # the change note should be added there. The "changes" list will obviously
265 # have to be modified to be a dict of the changes, or somesuch.
267 # More testing needed.
269 # Revision 1.20  2001/11/26 22:55:56  richard
270 # Feature:
271 #  . Added INSTANCE_NAME to configuration - used in web and email to identify
272 #    the instance.
273 #  . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
274 #    signature info in e-mails.
275 #  . Some more flexibility in the mail gateway and more error handling.
276 #  . Login now takes you to the page you back to the were denied access to.
278 # Fixed:
279 #  . Lots of bugs, thanks Roché and others on the devel mailing list!
281 # Revision 1.19  2001/11/12 22:51:04  jhermann
282 # Fixed option & associated error handling
284 # Revision 1.18  2001/11/01 22:04:37  richard
285 # Started work on supporting a pop3-fetching server
286 # Fixed bugs:
287 #  . bug #477104 ] HTML tag error in roundup-server
288 #  . bug #477107 ] HTTP header problem
290 # Revision 1.17  2001/10/29 23:55:44  richard
291 # Fix to CGI top-level index (thanks Juergen Hermann)
293 # Revision 1.16  2001/10/27 00:12:21  richard
294 # Fixed roundup-server for windows, thanks Juergen Hermann.
296 # Revision 1.15  2001/10/12 02:23:26  richard
297 # Didn't clean up after myself :)
299 # Revision 1.14  2001/10/12 02:20:32  richard
300 # server now handles setuid'ing much better
302 # Revision 1.13  2001/10/05 02:23:24  richard
303 #  . roundup-admin create now prompts for property info if none is supplied
304 #    on the command-line.
305 #  . hyperdb Class getprops() method may now return only the mutable
306 #    properties.
307 #  . Login now uses cookies, which makes it a whole lot more flexible. We can
308 #    now support anonymous user access (read-only, unless there's an
309 #    "anonymous" user, in which case write access is permitted). Login
310 #    handling has been moved into cgi_client.Client.main()
311 #  . The "extended" schema is now the default in roundup init.
312 #  . The schemas have had their page headings modified to cope with the new
313 #    login handling. Existing installations should copy the interfaces.py
314 #    file from the roundup lib directory to their instance home.
315 #  . Incorrectly had a Bizar Software copyright on the cgitb.py module from
316 #    Ping - has been removed.
317 #  . Fixed a whole bunch of places in the CGI interface where we should have
318 #    been returning Not Found instead of throwing an exception.
319 #  . Fixed a deviation from the spec: trying to modify the 'id' property of
320 #    an item now throws an exception.
322 # Revision 1.12  2001/09/29 13:27:00  richard
323 # CGI interfaces now spit up a top-level index of all the instances they can
324 # serve.
326 # Revision 1.11  2001/08/07 00:24:42  richard
327 # stupid typo
329 # Revision 1.10  2001/08/07 00:15:51  richard
330 # Added the copyright/license notice to (nearly) all files at request of
331 # Bizar Software.
333 # Revision 1.9  2001/08/05 07:44:36  richard
334 # Instances are now opened by a special function that generates a unique
335 # module name for the instances on import time.
337 # Revision 1.8  2001/08/03 01:28:33  richard
338 # Used the much nicer load_package, pointed out by Steve Majewski.
340 # Revision 1.7  2001/08/03 00:59:34  richard
341 # Instance import now imports the instance using imp.load_module so that
342 # we can have instance homes of "roundup" or other existing python package
343 # names.
345 # Revision 1.6  2001/07/29 07:01:39  richard
346 # Added vim command to all source so that we don't get no steenkin' tabs :)
348 # Revision 1.5  2001/07/24 01:07:59  richard
349 # Added command-line arg handling to roundup-server so it's more useful
350 # out-of-the-box.
352 # Revision 1.4  2001/07/23 10:31:45  richard
353 # disabled the reloading until it can be done properly
355 # Revision 1.3  2001/07/23 08:53:44  richard
356 # Fixed the ROUNDUPS decl in roundup-server
357 # Move the installation notes to INSTALL
359 # Revision 1.2  2001/07/23 04:05:05  anthonybaxter
360 # actually quit if python version wrong
362 # Revision 1.1  2001/07/23 03:46:48  richard
363 # moving the bin files to facilitate out-of-the-boxness
365 # Revision 1.1  2001/07/22 11:15:45  richard
366 # More Grande Splite stuff
369 # vim: set filetype=python ts=4 sw=4 et si