trac-ticketlinks / scripts / tracd

#!/usr/bin/env python
# -*- coding: iso8859-1 -*-
#
# Copyright (C) 2003, 2004 Edgewall Software
# Copyright (C) 2003, 2004 Jonas Borgström <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 Borgström <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()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.