Code

Add support for resuming (file) downloads.
[roundup.git] / cgi-bin / roundup.cgi
1 #!/usr/bin/env 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 # $Id: roundup.cgi,v 1.42 2005-05-18 05:39:21 richard Exp $
21 # python version check
22 from roundup import version_check
23 from roundup.i18n import _
24 import sys, time
26 #
27 ##  Configuration
28 #
30 # Configuration can also be provided through the OS environment (or via
31 # the Apache "SetEnv" configuration directive). If the variables
32 # documented below are set, they _override_ any configuation defaults
33 # given in this file. 
35 # TRACKER_HOMES is a list of trackers, in the form
36 # "NAME=DIR<sep>NAME2=DIR2<sep>...", where <sep> is the directory path
37 # separator (";" on Windows, ":" on Unix). 
39 # Make sure the NAME part doesn't include any url-unsafe characters like 
40 # spaces, as these confuse the cookie handling in browsers like IE.
42 # ROUNDUP_LOG is the name of the logfile; if it's empty or does not exist,
43 # logging is turned off (unless you changed the default below). 
45 # DEBUG_TO_CLIENT specifies whether debugging goes to the HTTP server (via
46 # stderr) or to the web client (via cgitb).
47 DEBUG_TO_CLIENT = False
49 # This indicates where the Roundup tracker lives
50 TRACKER_HOMES = {
51 #    'example': '/path/to/example',
52 }
54 # Where to log debugging information to. Use an instance of DevNull if you
55 # don't want to log anywhere.
56 class DevNull:
57     def write(self, info):
58         pass
59     def close(self):
60         pass
61     def flush(self):
62         pass
63 #LOG = open('/var/log/roundup.cgi.log', 'a')
64 LOG = DevNull()
66 #
67 ##  end configuration
68 #
71 #
72 # Set up the error handler
73
74 try:
75     import traceback, StringIO, cgi
76     from roundup.cgi import cgitb
77 except:
78     print "Content-Type: text/plain\n"
79     print _("Failed to import cgitb!\n\n")
80     s = StringIO.StringIO()
81     traceback.print_exc(None, s)
82     print s.getvalue()
85 #
86 # Check environment for config items
87 #
88 def checkconfig():
89     import os, string
90     global TRACKER_HOMES, LOG
92     # see if there's an environment var. ROUNDUP_INSTANCE_HOMES is the
93     # old name for it.
94     if os.environ.has_key('ROUNDUP_INSTANCE_HOMES'):
95         homes = os.environ.get('ROUNDUP_INSTANCE_HOMES')
96     else:
97         homes = os.environ.get('TRACKER_HOMES', '')
98     if homes:
99         TRACKER_HOMES = {}
100         for home in string.split(homes, os.pathsep):
101             try:
102                 name, dir = string.split(home, '=', 1)
103             except ValueError:
104                 # ignore invalid definitions
105                 continue
106             if name and dir:
107                 TRACKER_HOMES[name] = dir
108                 
109     logname = os.environ.get('ROUNDUP_LOG', '')
110     if logname:
111         LOG = open(logname, 'a')
113     # ROUNDUP_DEBUG is checked directly in "roundup.cgi.client"
117 # Provide interface to CGI HTTP response handling
119 class RequestWrapper:
120     '''Used to make the CGI server look like a BaseHTTPRequestHandler
121     '''
122     def __init__(self, wfile):
123         self.wfile = wfile
124     def write(self, data):
125         self.wfile.write(data)
126     def start_response(self, headers, response):
127         self.send_response(response)
128         for key, value in headers:
129             self.send_header(key, value)
130         self.end_headers()
131     def send_response(self, code):
132         self.write('Status: %s\r\n'%code)
133     def send_header(self, keyword, value):
134         self.write("%s: %s\r\n" % (keyword, value))
135     def end_headers(self):
136         self.write("\r\n")
139 # Main CGI handler
141 def main(out, err):
142     import os, string
143     import roundup.instance
144     path = string.split(os.environ.get('PATH_INFO', '/'), '/')
145     request = RequestWrapper(out)
146     request.path = os.environ.get('PATH_INFO', '/')
147     tracker = path[1]
148     os.environ['TRACKER_NAME'] = tracker
149     os.environ['PATH_INFO'] = string.join(path[2:], '/')
150     if TRACKER_HOMES.has_key(tracker):
151         # redirect if we need a trailing '/'
152         if len(path) == 2:
153             request.send_response(301)
154             # redirect
155             if os.environ.get('HTTPS', '') == 'on':
156                 protocol = 'https'
157             else:
158                 protocol = 'http'
159             absolute_url = '%s://%s%s/'%(protocol, os.environ['HTTP_HOST'],
160                 os.environ.get('REQUEST_URI', ''))
161             request.send_header('Location', absolute_url)
162             request.end_headers()
163             out.write('Moved Permanently')
164         else:
165             tracker_home = TRACKER_HOMES[tracker]
166             tracker = roundup.instance.open(tracker_home)
167             import roundup.cgi.client
168             if hasattr(tracker, 'Client'):
169                 client = tracker.Client(tracker, request, os.environ)
170             else:
171                 client = roundup.cgi.client.Client(tracker, request, os.environ)
172             try:
173                 client.main()
174             except roundup.cgi.client.Unauthorised:
175                 request.send_response(403)
176                 request.send_header('Content-Type', 'text/html')
177                 request.end_headers()
178                 out.write('Unauthorised')
179             except roundup.cgi.client.NotFound:
180                 request.send_response(404)
181                 request.send_header('Content-Type', 'text/html')
182                 request.end_headers()
183                 out.write('Not found: %s'%client.path)
185     else:
186         import urllib
187         request.send_response(200)
188         request.send_header('Content-Type', 'text/html')
189         request.end_headers()
190         w = request.write
191         w(_('<html><head><title>Roundup trackers index</title></head>\n'))
192         w(_('<body><h1>Roundup trackers index</h1><ol>\n'))
193         homes = TRACKER_HOMES.keys()
194         homes.sort()
195         for tracker in homes:
196             w(_('<li><a href="%(tracker_url)s/index">%(tracker_name)s</a>\n')%{
197                 'tracker_url': os.environ['SCRIPT_NAME']+'/'+
198                                urllib.quote(tracker),
199                 'tracker_name': cgi.escape(tracker)})
200         w(_('</ol></body></html>'))
203 # Now do the actual CGI handling
205 out, err = sys.stdout, sys.stderr
206 try:
207     # force input/output to binary (important for file up/downloads)
208     if sys.platform == "win32":
209         import os, msvcrt
210         msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
211         msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
212     checkconfig()
213     sys.stdout = sys.stderr = LOG
214     main(out, err)
215 except SystemExit:
216     pass
217 except:
218     sys.stdout, sys.stderr = out, err
219     out.write('Content-Type: text/html\n\n')
220     if DEBUG_TO_CLIENT:
221         cgitb.handler()
222     else:
223         out.write(cgitb.breaker())
224         ts = time.ctime()
225         out.write('''<p>%s: An error occurred. Please check
226             the server log for more infomation.</p>'''%ts)
227         print >> sys.stderr, 'EXCEPTION AT', ts
228         traceback.print_exc(0, sys.stderr)
230 sys.stdout.flush()
231 sys.stdout, sys.stderr = out, err
232 LOG.close()
234 # vim: set filetype=python ts=4 sw=4 et si