def handler(req): options = req.get_options() if options.has_key('TracLocale'): locale.setlocale(locale.LC_ALL, options['TracLocale']) else: locale.setlocale(locale.LC_ALL, '') # Allow specifying the python eggs cache directory using SetEnv if req.subprocess_env.has_key('PYTHON_EGG_CACHE'): os.environ['PYTHON_EGG_CACHE'] = req.subprocess_env['PYTHON_EGG_CACHE'] mpr = ModPythonRequest(req, options) project_opts = dict_translate(options, ('TracEnv', 'TRAC_ENV'), ('TracEnvParentDir', 'TRAC_ENV_PARENT_DIR'), ('TracEnvIndexTemplate', 'TRAC_ENV_INDEX_TEMPLATE'), ('TracTemplateVars', 'TRAC_TEMPLATE_VARS')) env = get_environment(mpr, project_opts) if not env: send_project_index(mpr, project_opts) return apache.OK req.content_type = 'text/html' try: dispatch_request(mpr.path_info, mpr, env) except Exception, e: send_pretty_error(e, env, mpr)
def run(): try: # Make FreeBSD use blocking I/O like other platforms import fcntl for stream in [sys.stdin, sys.stdout]: fd = stream.fileno() flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK) except ImportError: pass try: # Use binary I/O on Windows import msvcrt msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) except ImportError: pass locale.setlocale(locale.LC_ALL, '') req = CGIRequest() env = get_environment(req, os.environ, threaded=False) if not env: send_project_index(req, os.environ) return try: dispatch_request(req.path_info, req, env) except Exception, e: send_pretty_error(e, env, req)
def _handler(_req): req = CGIRequest(_req.params, _req.stdin, _req.stdout) env = get_environment(req, os.environ) if not env: send_project_index(req, os.environ) return try: dispatch_request(req.path_info, req, env) except Exception, e: send_pretty_error(e, env, req)
def test_environment_not_found(self): """User error reported when environment is not found.""" env_path = self.env_path + '$' # Arbitrarily modified path environ = self._make_environ(PATH_INFO='/', env_path=env_path) dispatch_request(environ, self._make_start_response()) content = self.response_sent.getvalue() self.assertEqual( "Trac Error\n\nTracError: No Trac environment found at %s\n" "IOError: [Errno 2] No such file or directory: '%s'" % (env_path, os.path.join(env_path, 'VERSION')), content)
def test_internal_error_for_non_admin(self): self._set_config(admin_trac_url='.') environ = self._make_environ(PATH_INFO='/raise-exception') dispatch_request(environ, self._make_start_response()) content = self.response_sent.getvalue() self.assert_internal_error(content) self.assertIn('There was an internal error in Trac.', content) self.assertIn('<p>\nTo that end, you could', content) self.assertNotIn('This is probably a local installation issue.', content) self.assertNotIn('<h2>Found a bug in Trac?</h2>', content)
def run(): locale.setlocale(locale.LC_ALL, '') req = CGIRequest() env = get_environment(req, os.environ, threaded=False) if not env: send_project_index(req, os.environ) return try: dispatch_request(req.path_info, req, env) except Exception, e: send_pretty_error(e, env, req)
def _do_trac_req(self): if self.path == '/': path_info = '/' req = TracHTTPRequest(self, '', '') self.server.send_project_index(req) return m = self.url_re.findall(self.path) if not m: self.send_error(400, 'Bad Request') return project_name, path_info, query_string = m[0] project_name = urllib.unquote(project_name) path_info = urllib.unquote(path_info) req = TracHTTPRequest(self, project_name, query_string) try: opts = self.server.get_env_opts(project_name) except KeyError: # unrecognized project self.server.send_project_index(req) return env = get_environment(req, opts) if not env: self.server.send_project_index(req) return req.remote_user = None if path_info == '/login': auth = self.server.auths.get(project_name) if not auth: raise util.TracError('Authentication not enabled. ' 'Please use the tracd --auth option.\n') req.remote_user = auth.do_auth(self) if not req.remote_user: return try: start = time.time() dispatch_request(path_info, req, env) env.log.debug('Total request time: %f s', time.time() - start) except socket.error, (code, msg): if code == errno.EPIPE or code == 10053: # Windows env.log.info('Lost connection to client: %s' % self.address_string()) else: raise
def test_internal_error_without_admin_trac_url_for_admin(self): self._set_config(admin_trac_url='') environ = self._make_environ(PATH_INFO='/raise-exception', REMOTE_USER='******') dispatch_request(environ, self._make_start_response()) content = self.response_sent.getvalue() self.assert_internal_error(content) self.assertNotIn('There was an internal error in Trac.', content) self.assertIn('This is probably a local installation issue.', content) self.assertNotIn('a ticket at the admin Trac to report', content) self.assertIn('<h2>Found a bug in Trac?</h2>', content) self.assertIn('<p>\nOtherwise, please', content) self.assertIn(' action="https://trac.edgewall.org/newticket"', content)
def test_trac_error(self): self._set_config(admin_trac_url='.') environ = self._make_environ(PATH_INFO='/raise-exception', QUERY_STRING='type=tracerror') dispatch_request(environ, self._make_start_response()) content = self.response_sent.getvalue() self.assertEqual('500 Internal Server Error', self.status_sent[0]) self.assertEqual('text/html;charset=utf-8', self.headers_sent['Content-Type']) self.assertIn('<h1>Trac Error</h1>', content) self.assertIn('<p class="message">The TracError message</p>', content) self.assertNotIn('<strong>Trac detected an internal error:</strong>', content) self.assertNotIn('There was an internal error in Trac.', content)
def __call__(self, environ, start_response): https = environ.get("HTTPS", "off") if self.secure and https != 'on': return redirect_https(environ, start_response) if self.parent: project = path_info_pop(environ) if project: if not os.path.isdir('{0}/{1}'.format(self.path, project)): start_response("404 Not Found", [('content-type', 'text/html')]) return self.template.render({'message': 'Trac name {0} does\'t exist.'.format(project)}, format='xhtml', template="wsgiplugin.notfound") environ['trac.env_path'] = os.path.join(self.path, project) try: return dispatch_request(environ, start_response) except HTTPForbidden: if environ.get('REMOTE_USER'): #We have SOMETHING set in REMOTE_USER - so Forbidden start_response("200 OK", [('content-type', 'text/html')]) return self.template.render({}, format='xhtml', template="wsgiplugin.unauthorized") else: url = '/login_form?came_from=%s' % construct_url(environ) start_response("302 Temporary Redirect", [('Location', url)]) return [] except HTTPNotFound, e: start_response("404 Not Found", [('content-type', 'text/html')]) return self.template.render({'message': e}, format='xhtml', template="wsgiplugin.notfound") else: return self._send_index(environ, start_response)
def __call__(self, environ, start_response): https = environ.get("HTTPS", "off") if self.secure and https != 'on': return redirect_https(environ, start_response) if self.parent: project = path_info_pop(environ) if project: environ['trac.env_path'] = os.path.join(self.path, project) return dispatch_request(environ, start_response) else: return self._send_index(environ, start_response) else: environ['trac.env_path'] = self.path return dispatch_request(environ, start_response)
def process_request(self, req): _, _, rewrite, options = self.rewrites[self.tag_index[req.tag]] try: new_path = req.md.expand(rewrite) except re.error: raise RewriteError, "Invalid rewrite string given: '%s'" % rewrite self.log.debug("TracRewrite: New path is '%s'" % new_path) if 'r' in options: req.redirect(new_path) elif 'n' in options: pass elif 'l' in options: raise RewriteError, "Internal rewrites don't actually work yet. Check back after 0.10 get finalized a bit more" dispatch_request(new_path, req, self.env) return False # This indicates that a response has already been sent else: raise RewriteError, "No valid options found in '%s'. Please specify a valid rewrite type." % options
def process_request(self, req): _, _, rewrite, options = self.rewrites[self.tag_index[req.tag]] try: new_path = req.md.expand(rewrite) except re.error: raise RewriteError, "Invalid rewrite string given: '%s'"%rewrite self.log.debug("TracRewrite: New path is '%s'"%new_path) if 'r' in options: req.redirect(new_path) elif 'n' in options: pass elif 'l' in options: raise RewriteError, "Internal rewrites don't actually work yet. Check back after 0.10 get finalized a bit more" dispatch_request(new_path, req, self.env) return False # This indicates that a response has already been sent else: raise RewriteError, "No valid options found in '%s'. Please specify a valid rewrite type."%options
def application(environ, start_request): if not 'trac.env_parent_dir' in environ: environ.setdefault('trac.env_path', '/var/lib/trac/sites/{}'.format(os.environ.get('TRAC_PROJECT_NAME', ''))) if 'PYTHON_EGG_CACHE' in environ: os.environ['PYTHON_EGG_CACHE'] = environ['PYTHON_EGG_CACHE'] elif 'trac.env_path' in environ: os.environ['PYTHON_EGG_CACHE'] = \ os.path.join(environ['trac.env_path'], '.egg-cache') elif 'trac.env_parent_dir' in environ: os.environ['PYTHON_EGG_CACHE'] = \ os.path.join(environ['trac.env_parent_dir'], '.egg-cache') from trac.web.main import dispatch_request return dispatch_request(environ, start_request)
def _send_project(self, req, path_info): start_response = req._start_response environ = copy.copy(req.environ) class hacked_start_response(object): def __init__(self, start_response, log): if hasattr(start_response, 'log'): raise Exception("BOOM!") self.start_response = start_response self.log = log def __call__(self, *args): self.log.debug('TracForgeDispatch: start_response called with (%s)', ', '.join(repr(x) for x in args)) return self.start_response(*args) environ['SCRIPT_NAME'] = req.href.projects('/') environ['PATH_INFO'] = path_info environ['trac.env_parent_dir'] = os.path.dirname(self.env.path) if 'TRAC_ENV' in environ: del environ['TRAC_ENV'] if 'trac.env_path' in environ: # WARNING: this is a really FRAGILE HACK!! # # The code here used to delete the 'trac.env_path' key from environ, # but then other code in web/main.py would use setdefault to bring # it back to life... with the wrong value. Code later in that file # checks environ['trac.env_path'] as a truth value and treats empty # results as absent. environ['trac.env_path'] = '' environ['tracforge_master_link'] = req.href.projects() # Remove mod_python option to avoid conflicts if 'mod_python.subprocess_env' in environ: del environ['mod_python.subprocess_env'] if 'mod_python.options' in environ: del environ['mod_python.options'] self.log.debug('TracForgeDispatch: environ %r', environ) self.log.debug('TracForgeDispatch: Calling next dispatch_request') try: if not hasattr(start_response, 'log'): self.log.debug('TracForgeDispatch: Setting start_request logging hack') #start_response = hacked_start_response(start_response, self.log) req._response = dispatch_request(environ, start_response) except RequestDone: self.log.debug('TracForgeDispatch: Masking inner RequestDone') self.log.debug('TracForgeDispatch: Done')
def match_request(self, req): if req.path_info.startswith('/projects/'): path_info = req.path_info[10:].lstrip('/') if path_info: self.log.debug( 'TracForgeDispatch: Starting WSGI relaunch for %s (%s)', path_info, req.method) self.log.debug('SN = %s PI = %s', req.environ['SCRIPT_NAME'], req.environ['PATH_INFO']) project_name = path_info.split('/', 1)[0] # Check that we aren't trying to recurse (possible link loop) if project_name == os.path.basename(self.env.path): req.redirect(req.href()) project = Project(self.env, project_name) # Assert permissions on the desination environment if not project.exists: raise TracError('No such project "%s"', project.name) if not project.valid: raise TracError('Project %s is invalid:\n%s', project.name, project.env.exc) # Check that we have permissions in the desired project authname = RequestDispatcher(self.env).authenticate(req) project_perm = PermissionCache(project.env, authname) project_perm.require('PROJECT_LIST') start_response = req._start_response environ = copy.copy(req.environ) # Setup the environment variables environ['SCRIPT_NAME'] = req.href.projects(project.name) environ['PATH_INFO'] = path_info[len(project.name):] environ['trac.env_path'] = project.env_path if 'TRAC_ENV' in environ: del environ['TRAC_ENV'] if 'TRAC_ENV_PARENT_DIR' in environ: del environ['TRAC_ENV_PARENT_DIR'] if 'trac.env_parent' in environ: del environ['trac.env_parent_dir'] environ['tracforge_master_link'] = req.href.projects() # Remove mod_python options to avoid conflicts if 'mod_python.subprocess_env' in environ: del environ['mod_python.subprocess_env'] if 'mod_python.options' in environ: del environ['mod_python.options'] req._response = dispatch_request(environ, start_response) raise RequestDone
def application(environ, start_request): if not 'trac.env_parent_dir' in environ: environ.setdefault( 'trac.env_path', '/var/lib/trac/sites/{}'.format( os.environ.get('TRAC_PROJECT_NAME', ''))) if 'PYTHON_EGG_CACHE' in environ: os.environ['PYTHON_EGG_CACHE'] = environ['PYTHON_EGG_CACHE'] elif 'trac.env_path' in environ: os.environ['PYTHON_EGG_CACHE'] = \ os.path.join(environ['trac.env_path'], '.egg-cache') elif 'trac.env_parent_dir' in environ: os.environ['PYTHON_EGG_CACHE'] = \ os.path.join(environ['trac.env_parent_dir'], '.egg-cache') from trac.web.main import dispatch_request return dispatch_request(environ, start_request)
def application(environ, start_request): environ.setdefault('trac.env_path', os.path.join(os.environ['APPL_PHYSICAL_PATH'], 'trac')) # or # os.environ['TRAC_ENV'] = os.path.join(os.environ['APPL_PHYSICAL_PATH'], 'trac') os.environ['PYTHON_EGG_CACHE'] = os.path.join(os.environ['APPL_PHYSICAL_PATH'], 'python_modules', 'eggs') # fix SCRIPT_NAME & PATH_INFO app_virt_path = os.environ.get('APPL_VIRTUAL_PATH') path_info = environ.get('PATH_INFO') if app_virt_path and path_info: if path_info.startswith(app_virt_path): environ['PATH_INFO'] = path_info[len(app_virt_path):] environ['SCRIPT_NAME'] = app_virt_path return dispatch_request(environ, start_request)
def match_request(self, req): if req.path_info.startswith("/projects/"): path_info = req.path_info[10:].lstrip("/") if path_info: self.log.debug("TracForgeDispatch: Starting WSGI relaunch for %s (%s)", path_info, req.method) self.log.debug("SN = %s PI = %s", req.environ["SCRIPT_NAME"], req.environ["PATH_INFO"]) project_name = path_info.split("/", 1)[0] # Check that we aren't trying to recurse (possible link loop) if project_name == os.path.basename(self.env.path): req.redirect(req.href()) project = Project(self.env, project_name) # Assert permissions on the desination environment if not project.exists: raise TracError('No such project "%s"', project.name) if not project.valid: raise TracError("Project %s is invalid:\n%s", project.name, project.env.exc) # Check that we have permissions in the desired project authname = RequestDispatcher(self.env).authenticate(req) project_perm = PermissionCache(project.env, authname) project_perm.require("PROJECT_LIST") start_response = req._start_response environ = copy.copy(req.environ) # Setup the environment variables environ["SCRIPT_NAME"] = req.href.projects(project.name) environ["PATH_INFO"] = path_info[len(project.name) :] environ["trac.env_path"] = project.env_path if "TRAC_ENV" in environ: del environ["TRAC_ENV"] if "TRAC_ENV_PARENT_DIR" in environ: del environ["TRAC_ENV_PARENT_DIR"] if "trac.env_parent" in environ: del environ["trac.env_parent_dir"] environ["tracforge_master_link"] = req.href.projects() # Remove mod_python options to avoid conflicts if "mod_python.subprocess_env" in environ: del environ["mod_python.subprocess_env"] if "mod_python.options" in environ: del environ["mod_python.options"] req._response = dispatch_request(environ, start_response) raise RequestDone
def application(environ, start_request): environ.setdefault('trac.env_path', os.path.join(os.environ['APPL_PHYSICAL_PATH'], 'trac')) # or # os.environ['TRAC_ENV'] = os.path.join(os.environ['APPL_PHYSICAL_PATH'], 'trac') os.environ['PYTHON_EGG_CACHE'] = os.path.join( os.environ['APPL_PHYSICAL_PATH'], 'python_modules', 'eggs') # fix SCRIPT_NAME & PATH_INFO app_virt_path = os.environ.get('APPL_VIRTUAL_PATH') path_info = environ.get('PATH_INFO') if app_virt_path and path_info: if path_info.startswith(app_virt_path): environ['PATH_INFO'] = path_info[len(app_virt_path):] environ['SCRIPT_NAME'] = app_virt_path return dispatch_request(environ, start_request)
def handler(environ, start_response): if environ['REQUEST_URI'][:11] == '/code/login': def unauthorized(): start_response( '401 Authorization Required', [ ('WWW-Authenticate', 'Basic realm="ESP Project"'), ('Content-Type', 'text/html') ] ) return '<html><head><title>401 Authorization Required</title></head><body><h1>401 Authorization Required</h1></body></html>' # Decode the input try: # Require basic authentication method, auth = environ['HTTP_AUTHORIZATION'].split(' ', 1) if method.lower() != 'basic': return unauthorized() username, password = auth.strip().decode('base64').split(':') except: #(KeyError, ValueError, base64.binascii.Error) return unauthorized() # Check that the user exists try: from django.contrib.auth.models import User from esp.datatree.models import get_lowest_parent from esp.users.models import UserBit user = User.objects.get(username=username, is_active=True) except User.DoesNotExist: return unauthorized() # Check the password and any permission given if not ( user.check_password(password) and user.is_authenticated() ): return unauthorized() qsc = get_lowest_parent('Q/Static/' + environ['REQUEST_URI'].strip('/')) verb = get_lowest_parent('V/Flags/Public') if not UserBit.UserHasPerms(user, qsc, verb): return unauthorized() # By now we've verified the user's login and permissions environ['REMOTE_USER'] = username # Eventually pass all requests to Trac from trac.web.main import dispatch_request return dispatch_request(environ, start_response)
def __call__(self, environ, start_response): req = Request(environ) step = req.path_info.strip('/') try: if step in [i[0] for i in self.steps]: # determine which step we are on index = [i[0] for i in self.steps].index(step) else: # delegate to Trac environ['trac.env_parent_dir'] = self.directory environ['trac.env_index_template'] = self.index # data for index template if req.remote_user and self.remote_user_name: # XXX fails if unicode req.remote_user = str( self.remote_user_name(req.remote_user)) data = { 'remote_user': req.remote_user or '', 'auth': self.auth and 'yes' or '' } environ['trac.template_vars'] = ','.join( ["%s=%s" % (key, value) for key, value in data.items()]) return dispatch_request(environ, start_response) # if self.auth, enforce remote_user to be set if self.auth and not req.remote_user: return exc.HTTPUnauthorized()(environ, start_response) # if POST-ing, validate the request and store needed information errors = [] name, step = self.steps[index] base_url = req.url.rsplit(step.name, 1)[0] project = req.params.get('project') if req.method == 'POST': # check for project existence if not project and index: res = exc.HTTPSeeOther("No session found", location="create-project") return res(environ, start_response) if index: if project not in self.projects: errors.append('Project not found') project_data = self.projects.get(project) errors = step.errors(project_data, req.POST) if not index: project_data = self.projects[project] = {} # set *after* error check so that `create-project` doesn't find itself project_data['base_url'] = base_url if not errors: # success step.transition(project_data, req.POST) # find the next step and redirect to it while True: index += 1 if index == len(self.steps): destination = self.done % self.projects[project][ 'vars'] time.sleep(1) # XXX needed? self.projects.pop( project) # successful project creation break else: name, step = self.steps[index] if step.display(project_data): destination = '%s?project=%s' % ( self.steps[index][0], project) break else: step.transition(project_data, {}) res = exc.HTTPSeeOther(destination, location=destination) return res(environ, start_response) else: # GET project_data = self.projects.get(project, {}) project_data['base_url'] = base_url if index and project not in self.projects: res = exc.HTTPSeeOther("No session found", location="create-project") return res(environ, start_response) # render the template and return the response data = step.data(project_data) data['req'] = req data['errors'] = errors template = self.loader.load(step.template) html = template.generate(**data).render('html', doctype='html') res = Response(content_type='text/html', body=html) return res(environ, start_response) except: # error handling exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() buffer = StringIO() traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback, limit=20, file=buffer) res = exc.HTTPServerError(buffer.getvalue()) return res(environ, start_response)
def __call__(self, environ, start_response): req = Request(environ) step = req.path_info.strip('/') try: if step in [i[0] for i in self.steps]: # determine which step we are on index = [i[0] for i in self.steps].index(step) else: # delegate to Trac environ['trac.env_parent_dir'] = self.directory environ['trac.env_index_template'] = self.index # data for index template if req.remote_user and self.remote_user_name: # XXX fails if unicode req.remote_user = str(self.remote_user_name(req.remote_user)) data = { 'remote_user': req.remote_user or '', 'auth': self.auth and 'yes' or '' } environ['trac.template_vars'] = ','.join(["%s=%s" % (key, value) for key, value in data.items()]) return dispatch_request(environ, start_response) # if self.auth, enforce remote_user to be set if self.auth and not req.remote_user: return exc.HTTPUnauthorized()(environ, start_response) # if POST-ing, validate the request and store needed information errors = [] name, step = self.steps[index] base_url = req.url.rsplit(step.name, 1)[0] project = req.params.get('project') if req.method == 'POST': # check for project existence if not project and index: res = exc.HTTPSeeOther("No session found", location="create-project") return res(environ, start_response) if index: if project not in self.projects: errors.append('Project not found') project_data = self.projects.get(project) errors = step.errors(project_data, req.POST) if not index: project_data = self.projects[project] = {} # set *after* error check so that `create-project` doesn't find itself project_data['base_url'] = base_url if not errors: # success step.transition(project_data, req.POST) # find the next step and redirect to it while True: index += 1 if index == len(self.steps): destination = self.done % self.projects[project]['vars'] time.sleep(1) # XXX needed? self.projects.pop(project) # successful project creation break else: name, step = self.steps[index] if step.display(project_data): destination = '%s?project=%s' % (self.steps[index][0], project) break else: step.transition(project_data, {}) res = exc.HTTPSeeOther(destination, location=destination) return res(environ, start_response) else: # GET project_data = self.projects.get(project, {}) project_data['base_url'] = base_url if index and project not in self.projects: res = exc.HTTPSeeOther("No session found", location="create-project") return res(environ, start_response) # render the template and return the response data = step.data(project_data) data['req'] = req data['errors'] = errors template = self.loader.load(step.template) html = template.generate(**data).render('html', doctype='html') res = Response(content_type='text/html', body=html) return res(environ, start_response) except: # error handling exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() buffer = StringIO() traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback, limit=20, file=buffer) res = exc.HTTPServerError(buffer.getvalue()) return res(environ, start_response)
def application(environ, start_request): os.environ['TRAC_ENV'] = '/usr/src/wiki/trac/europython' os.environ['PYTHON_EGG_CACHE'] = '/usr/src/wiki/trac/europython/eggs' from trac.web.main import dispatch_request return dispatch_request(environ, start_request)
if environ.get('REMOTE_USER'): #We have SOMETHING set in REMOTE_USER - so Forbidden start_response("200 OK", [('content-type', 'text/html')]) return self.template.render({}, format='xhtml', template="wsgiplugin.unauthorized") else: url = '/login_form?came_from=%s' % construct_url(environ) start_response("302 Temporary Redirect", [('Location', url)]) return [] except HTTPNotFound, e: start_response("404 Not Found", [('content-type', 'text/html')]) return self.template.render({'message': e}, format='xhtml', template="wsgiplugin.notfound") else: return self._send_index(environ, start_response) else: environ['trac.env_path'] = self.path return dispatch_request(environ, start_response) def _send_index(self, environ, start_response): projects = [] for env_name in os.listdir(self.path): env_path = os.path.join(self.path, env_name) try: env = open_environment(env_path) env_perm = PermissionCache(PermissionSystem(env).get_user_permissions(environ.get("REMOTE_USER", "anonymous"))) if env_perm.has_permission('WIKI_VIEW'): projects.append({ 'name': env.project_name, 'description': env.project_description, # XXX: get rid of the double / in the beginning