File: tracd

package info (click to toggle)
trac 0.8.1-3sarge7
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,532 kB
  • ctags: 1,038
  • sloc: python: 9,526; cs: 2,392; xml: 261; makefile: 98; sh: 7
file content (328 lines) | stat: -rwxr-xr-x 11,285 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/usr/bin/env python
# -*- coding: iso8859-1 -*-
#
# Copyright (C) 2003, 2004 Edgewall Software
# Copyright (C) 2003, 2004 Jonas Borgstrm <jonas@edgewall.com>
#
# Trac is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Trac is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Author: Jonas Borgstrm <jonas@edgewall.com>
#
# Todo:
# - External auth using mod_proxy / squid.


import os
import re
import sys
import md5
import time
import shutil
import getopt
import locale
import urllib
import urllib2
import mimetypes
import SocketServer
import BaseHTTPServer

import svn.core

import trac.core
import trac.util
from trac import Session
from trac.Href import Href
from trac import auth, siteconfig
from trac.Environment import Environment


class DigestAuth:
    """A simple HTTP DigestAuth implementation (rfc2617)"""
    MAX_NONCES = 100
    def __init__(self, htdigest, realm):
        self.active_nonces = []
        self.hash = {}
        self.realm = realm
        self.load_htdigest(htdigest, realm)

    def load_htdigest(self, filename, realm):
        """
        Load account information from apache style htdigest files,
        only users from the specified realm are used
        """
        fd = open(filename, 'r')
        for line in fd.readlines():
            u, r, a1 = line.strip().split(':')
            if r == realm:
                self.hash[u] = a1
        if self.hash == {}:
            print >> sys.stderr, "Warning: found no users in realm:", realm
        
    def parse_auth_header(self, authorization):
        values = {}
        for value in urllib2.parse_http_list(authorization):
            n, v = value.split('=', 1)
            if v[0] == '"' and v[-1] == '"':
                values[n] = v[1:-1]
            else:
                values[n] = v
        return values

    def send_auth_request(self, req, stale='false'):
        """
        Send a digest challange to the browser. Record used nonces
        to avoid replay attacks.
        """
        nonce = trac.util.hex_entropy()
        self.active_nonces.append(nonce)
        if len(self.active_nonces) > DigestAuth.MAX_NONCES:
            self.active_nonces = self.active_nonces[-DigestAuth.MAX_NONCES:]
        req.send_response(401)
        req.send_header('WWW-Authenticate',
                        'Digest realm="%s", nonce="%s", qop="auth", stale="%s"'
                        % (self.realm, nonce, stale))
        req.end_headers()

    def do_auth(self, req):
        if not 'Authorization' in req.headers or \
               req.headers['Authorization'][:6] != 'Digest':
            self.send_auth_request(req)
            return None
        auth = self.parse_auth_header(req.headers['Authorization'][7:])
        required_keys = ['username', 'realm', 'nonce', 'uri', 'response',
                           'nc', 'cnonce']
        # Invalid response?
        for key in required_keys:
            if not auth.has_key(key):
                self.send_auth_request(req)
                return None
        # Unknown user?
        if not self.hash.has_key(auth['username']):
            self.send_auth_request(req)
            return None

        kd = lambda x: md5.md5(':'.join(x)).hexdigest()
        a1 = self.hash[auth['username']]
        a2 = kd([req.command, auth['uri']])
        # Is the response correct?
        correct = kd([a1, auth['nonce'], auth['nc'],
                      auth['cnonce'], auth['qop'], a2])
        if auth['response'] != correct:
            self.send_auth_request(req)
            return None
        # Is the nonce active, if not ask the client to use a new one
        if not auth['nonce'] in self.active_nonces:
            self.send_auth_request(req, stale='true')
            return None
        self.active_nonces.remove(auth['nonce'])
        return auth['username']


class TracHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    pass

class TracHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler,
                             trac.core.Request):
    url_re = re.compile('/(?P<project>[^/\?]+)'
                        '(?P<path_info>/?[^\?]*)?'
                        '(?:\?(?P<query_string>.*))?')
    server_version = 'tracd/' + trac.__version__

    env = None

    def read(self, len):
        return self.rfile.read(len)

    def write(self, data):
        self.wfile.write(data)

    def init_request(self):
        trac.core.Request.init_request(self)
        self.remote_addr = str(self.client_address[0])
        self.hdf.setValue('HTTP.Host', self.server.http_host)
        self.hdf.setValue('HTTP.Protocol', 'http')
        self.hdf.setValue('HTTP.PathInfo', self.path_info)
        if self.headers.has_key('Cookie'):
            self.incookie.load(self.headers['Cookie'])

    def get_header(self, name):
        return self.headers.get(name)

    def parse_path(self, path):
        m = self.url_re.findall(self.path)
        if not m:
            raise trac.util.TracError('Unknown URI')
        self.project_name, self.path_info, self.query_string = m[0]
        if not self.server.projects.has_key(self.project_name):
            raise trac.util.TracError('Unknown Project')
        self.path_info = urllib.unquote(self.path_info)
        self.env = self.server.projects[self.project_name]
        self.log = self.env.log
        self.cgi_location = '/' + self.project_name
        self.base_url = 'http://%s/%s' % (self.server.http_host, self.project_name)

    def log_message(self, format, *args):
        if self.env:
            self.log.debug(format%args)

    def do_project_index(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.end_headers()
        self.write('<html><head><title>Available Projects</title></head>')
        self.write('<body><h1>Available Projects</h1><ul>')
        for project in self.server.projects.keys():
            self.write('<li><a href="%s">%s</a></li>' % (project, project))
        self.write('</ul></body><html>')

    def do_htdocs_req(self, path):
        """This function serves request for static img/css files"""
        path = urllib.unquote(path)
        # Make sure the path doesn't contain any dangerous ".."-parts.
        path = '/'.join(filter(lambda x: x not in ['..', ''],
                               path.split('/')))
        filename = os.path.join(siteconfig.__default_htdocs_dir__,
                                os.path.normcase(path))
        try:
            f = open(filename, 'rb')
        except IOError:
            self.send_error(404, path)
            return
        self.send_response(200)
        mtype, enc = mimetypes.guess_type(filename)
        stat = os.fstat(f.fileno())
        content_length = stat[6]
        last_modified = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
                                      time.gmtime(stat[8]))
        self.send_header('Content-Type', mtype)
        self.send_header('Conten-Length', str(content_length))
        self.send_header('Last-Modified', last_modified)
        self.end_headers()
        shutil.copyfileobj(f, self.wfile)

    def do_POST(self):
        self.do_trac_req()

    def do_HEAD(self):
        self.do_GET()
        
    def do_GET(self):
        if self.path[0:13] == '/':
            self.do_project_index()
        elif self.path[0:13] == '/trac_common/':
            self.do_htdocs_req(self.path[13:])
        else:
            self.do_trac_req()
        
    def do_trac_req(self):
        try:
            self.parse_path(self.path)
        except:
            self.send_error(404, 'Unknown request')
            return
        try:
            self.do_real_trac_req()
        except Exception, e:
            trac.core.send_pretty_error(e, self.env, self)

    def do_real_trac_req(self):
        start = time.time()
        self.init_request()

        self.remote_user = None
        if self.path_info == '/login':
            if not self.env.auth:
                raise trac.util.TracError('Authentication not enabled. '
                                          'Please use the tracd --auth option.\n')

            self.remote_user = self.env.auth.do_auth(self)
            if not self.remote_user:
                return

        # Parse arguments
        args = trac.core.parse_args(self.command, self.path_info,
                                    self.query_string,
                                    self.rfile, None, self.headers)

        trac.core.dispatch_request(self.path_info, args, self, self.env)

        self.log.debug('Total request time: %f s', time.time() - start)


def usage():
    print 'usage: %s [options] <projenv> [projenv] ...' % sys.argv[0]
    print '\nOptions:\n'
    print '-a --auth [project],[htdigest_file],[realm]'
    print '-p --port [port]\t\tPort number to use (default: 80)'
    print '-b --hostname [hostname]\tIP to bind to (default: \'\')'
    print
    sys.exit(1)
        
def main():
    locale.setlocale(locale.LC_ALL, '')
    port = 80
    hostname = ''
    auths = {}
    projects = {}
    try:
        opts, args = getopt.getopt(sys.argv[1:], "a:p:b:",
                                   ["auth=", "port=", "hostname="])
    except getopt.GetoptError:
        usage()
    for o, a in opts:
        if o in ("-a", "--auth"):
            info = a.split(',', 3)
            if len(info) != 3:
                usage()
            p, h, r = info
            auths[p] = DigestAuth(h, r)
        if o in ("-p", "--port"):
            port = int(a)
        elif o in ("-b", "--hostname"):
            hostname = a

    if not args:
        usage()
        
    server_address = (hostname, port)
    httpd = TracHTTPServer(server_address, TracHTTPRequestHandler)
    if httpd.server_port == 80:
        httpd.http_host = httpd.server_name
    else:
        httpd.http_host = '%s:%d' % (httpd.server_name, httpd.server_port)
    
    for path in args:
        # Remove trailing slashes
        while path and not os.path.split(path)[1]:
            path = os.path.split(path)[0]
        project = os.path.split(path)[1]
        # We assume the projenv filenames follow the following
        # naming convention: /some/path/project
        auth = auths.get(project, None)
        env = Environment(path)
        # Upgrade the database schema if needed
        env.upgrade(backup=1)
        env.href = Href('/' + project)
        env.abs_href = Href('http://%s/%s' % (httpd.http_host, project))
        projects[project] = env
        projects[project].set_config('trac', 'htdocs_location',
                                     '/trac_common/')
        projects[project].auth = auth
        
    httpd.projects = projects
    httpd.serve_forever()

if __name__ == '__main__':
    main()