Example #1
0
 def lookup_app(self, environ):
     # Check again if the branch is blocked from being served, this is
     # mostly for tests. It's already checked in apps/transport.py
     if not self.branch.get_config().get_user_option_as_bool('http_serve',
                                                             default=True):
         raise httpexceptions.HTTPNotFound()
     self._url_base = environ['SCRIPT_NAME']
     self._path_info = environ['PATH_INFO']
     self._static_url_base = environ.get('loggerhead.static.url')
     if self._static_url_base is None:
         self._static_url_base = self._url_base
     self._environ = environ
     if self.served_url is _DEFAULT:
         public_branch = self.public_branch_url()
         if public_branch is not None:
             self.served_url = public_branch
         else:
             self.served_url = wsgiref.util.application_uri(environ)
     for hook in self.hooks['controller']:
         controller = hook(self, environ)
         if controller is not None:
             return controller
     path = request.path_info_pop(environ)
     if not path:
         raise httpexceptions.HTTPMovedPermanently(
             self.absolute_url('/changes'))
     if path == 'static':
         return static_app
     elif path == '+json':
         environ['loggerhead.as_json'] = True
         path = request.path_info_pop(environ)
     cls = self.controllers_dict.get(path)
     if cls is not None:
         return cls(self, self.get_history)
     raise httpexceptions.HTTPNotFound()
Example #2
0
 def __call__(self, environ, start_response):
     path_info = environ.setdefault('PATH_INFO', '')
     if path_info.startswith('/.olpcproxy/'):
         path_info_pop(environ)
         return static_app(environ, start_response)
     environ['olpcproxy.static_url'] = construct_url(environ, path_info='/.olpcproxy', with_query_string=False)
     environ['olpcproxy.static_path'] = static_dir
     return self.proxy(environ, start_response)
Example #3
0
 def debug(self, environ, start_response):
     assert request.path_info_pop(environ) == '_debug'
     next_part = request.path_info_pop(environ)
     method = getattr(self, next_part, None)
     if not method:
         exc = httpexceptions.HTTPNotFound(
             '%r not found when parsing %r' %
             (next_part, wsgilib.construct_url(environ)))
         return exc.wsgi_application(environ, start_response)
     if not getattr(method, 'exposed', False):
         exc = httpexceptions.HTTPForbidden('%r not allowed' % next_part)
         return exc.wsgi_application(environ, start_response)
     return method(environ, start_response)
Example #4
0
 def debug(self, environ, start_response):
     assert request.path_info_pop(environ) == '_debug'
     next_part = request.path_info_pop(environ)
     method = getattr(self, next_part, None)
     if not method:
         exc = httpexceptions.HTTPNotFound(
             '%r not found when parsing %r'
             % (next_part, wsgilib.construct_url(environ)))
         return exc.wsgi_application(environ, start_response)
     if not getattr(method, 'exposed', False):
         exc = httpexceptions.HTTPForbidden(
             '%r not allowed' % next_part)
         return exc.wsgi_application(environ, start_response)
     return method(environ, start_response)
Example #5
0
    def __call__(self, environ, start_response):
        """The meat of this operation.  Dispatches to the StaticURLParser for
        the plugin named in the URL.
        """

        # Need to match /static/:plugin_name/
        path_static = paste_request.path_info_pop(environ)
        if path_static != 'static':
            return self.default_parser.not_found(environ, start_response)

        plugin_name = paste_request.path_info_pop(environ)
        if plugin_name not in self.url_parsers:
            return self.default_parser.not_found(environ, start_response)

        return self.url_parsers[plugin_name](environ, start_response)
Example #6
0
    def __call__(self, environ, start_response):
        """The meat of this operation.  Dispatches to the StaticURLParser for
        the plugin named in the URL.
        """

        # Need to match /static/:plugin_name/
        path_static = paste_request.path_info_pop(environ)
        if path_static != 'static':
            return self.default_parser.not_found(environ, start_response)

        plugin_name = paste_request.path_info_pop(environ)
        if plugin_name not in self.url_parsers:
            return self.default_parser.not_found(environ, start_response)

        return self.url_parsers[plugin_name](environ, start_response)
Example #7
0
 def __call__(self, environ, start_response):
     path_info = environ.get('PATH_INFO', '')
     if not path_info:
         return self.add_slash(environ, start_response)
     if path_info == '/':
         # @@: This should obviously be configurable
         filename = 'index.html'
     else:
         filename = request.path_info_pop(environ)
     resource = os.path.normpath(self.resource_name + '/' + filename)
     if self.root_resource is not None and not resource.startswith(self.root_resource):
         # Out of bounds
         return self.not_found(environ, start_response)
     if not self.egg.has_resource(resource):
         return self.not_found(environ, start_response)
     if self.egg.resource_isdir(resource):
         # @@: Cache?
         child_root = self.root_resource is not None and self.root_resource or \
             self.resource_name
         return self.__class__(self.egg, resource, self.manager,
                               root_resource=child_root)(environ, start_response)
     if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
         return self.error_extra_path(environ, start_response)
     
     type, encoding = mimetypes.guess_type(resource)
     if not type:
         type = 'application/octet-stream'
     # @@: I don't know what to do with the encoding.
     try:
         file = self.egg.get_resource_stream(self.manager, resource)
     except (IOError, OSError), e:
         exc = httpexceptions.HTTPForbidden(
             'You are not permitted to view this file (%s)' % e)
         return exc.wsgi_application(environ, start_response)
Example #8
0
 def __call__(self, environ, start_response):
     path_info = environ.get('PATH_INFO', '')
     if not path_info:
         return self.add_slash(environ, start_response)
     if path_info == '/':
         # @@: This should obviously be configurable
         filename = 'index.html'
     else:
         filename = request.path_info_pop(environ)
     full = os.path.join(self.directory, filename)
     if not os.path.exists(full):
         return self.not_found(environ, start_response)
     if os.path.isdir(full):
         # @@: Cache?
         return self.__class__(full)(environ, start_response)
     if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
         return self.error_extra_path(environ, start_response)
     if_none_match = environ.get('HTTP_IF_NONE_MATCH')
     if if_none_match:
         mytime = os.stat(full).st_mtime
         if str(mytime) == if_none_match:
             headers = []
             ETAG.update(headers, mytime)
             start_response('304 Not Modified', headers)
             return ['']  # empty body
     app = fileapp.FileApp(
         full,
         headers=[('Access-Control-Allow-Origin', '*'),
                  ('Access-Control-Allow-Headers',
                   'Content-Type, X-Requested-With, X-Requested-By'),
                  ('Access-Control-Allow-Methods', 'POST, GET')])
     if self.cache_seconds:
         app.cache_control(max_age=int(self.cache_seconds))
     return app(environ, start_response)
Example #9
0
    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)
Example #10
0
 def __call__( self, environ, start_response ):
     path_info = environ.get('PATH_INFO', '')
     if not path_info:
         #See if this is a static file hackishly mapped.
         if os.path.exists(self.directory) and os.path.isfile(self.directory):
             app = fileapp.FileApp(self.directory)
             if self.cache_seconds:
                 app.cache_control( max_age = int( self.cache_seconds ) )
             return app(environ, start_response)
         return self.add_slash(environ, start_response)
     if path_info == '/':
         # @@: This should obviously be configurable
         filename = 'index.html'
     else:
         filename = request.path_info_pop(environ)
     full = os.path.join(self.directory, filename)
     if not os.path.exists(full):
         return self.not_found(environ, start_response)
     if os.path.isdir(full):
         # @@: Cache?
         return self.__class__(full)(environ, start_response)
     if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
         return self.error_extra_path(environ, start_response)
     if_none_match = environ.get('HTTP_IF_NONE_MATCH')
     if if_none_match:
         mytime = os.stat(full).st_mtime
         if str(mytime) == if_none_match:
             headers = []
             ETAG.update(headers, mytime)
             start_response('304 Not Modified',headers)
             return [''] # empty body
     app = fileapp.FileApp(full)
     if self.cache_seconds:
         app.cache_control( max_age = int( self.cache_seconds ) )
     return app(environ, start_response)
Example #11
0
    def __call__(self, environ, start_response):
        path_info = environ.get("PATH_INFO", "")
        if not path_info:
            return self.add_slash(environ, start_response)
        if path_info == "/":
            # @@: This should obviously be configurable
            filename = "index.html"
        else:
            filename = request.path_info_pop(environ)
        full = self.normpath(os.path.join(self.directory, filename))
        if not full.startswith(self.root_directory):
            # Out of bounds
            return self.not_found(environ, start_response)
        if not os.path.exists(full):
            return self.not_found(environ, start_response)
        if os.path.isdir(full):
            # @@: Cache?
            return self.__class__(full, root_directory=self.root_directory, cache_max_age=self.cache_max_age)(
                environ, start_response
            )
        if environ.get("PATH_INFO") and environ.get("PATH_INFO") != "/":
            return self.error_extra_path(environ, start_response)
        if_none_match = environ.get("HTTP_IF_NONE_MATCH")
        if if_none_match:
            mytime = os.stat(full).st_mtime
            if str(mytime) == if_none_match:
                headers = []
                ETAG.update(headers, mytime)
                start_response("304 Not Modified", headers)
                return [""]  # empty body

        fa = self.make_app(full)
        if self.cache_max_age:
            fa.cache_control(max_age=self.cache_max_age)
        return fa(environ, start_response)
Example #12
0
    def __call__(self, environ, start_response):
        path_info = environ.get("PATH_INFO", "")
        if not path_info:
            return self.add_slash(environ, start_response)
        if path_info == "/":
            # @@: This should obviously be configurable
            filename = "index.html"
        else:
            filename = request.path_info_pop(environ)
        resource = os.path.normcase(os.path.normpath(self.resource_name + "/" + filename))
        if self.root_resource is not None and not resource.startswith(self.root_resource):
            # Out of bounds
            return self.not_found(environ, start_response)
        if not self.egg.has_resource(resource):
            return self.not_found(environ, start_response)
        if self.egg.resource_isdir(resource):
            # @@: Cache?
            child_root = self.root_resource is not None and self.root_resource or self.resource_name
            return self.__class__(self.egg, resource, self.manager, root_resource=child_root)(environ, start_response)
        if environ.get("PATH_INFO") and environ.get("PATH_INFO") != "/":
            return self.error_extra_path(environ, start_response)

        type, encoding = mimetypes.guess_type(resource)
        if not type:
            type = "application/octet-stream"
        # @@: I don't know what to do with the encoding.
        try:
            file = self.egg.get_resource_stream(self.manager, resource)
        except (IOError, OSError), e:
            exc = httpexceptions.HTTPForbidden("You are not permitted to view this file (%s)" % e)
            return exc.wsgi_application(environ, start_response)
Example #13
0
 def __call__( self, environ, start_response ):
     path_info = environ.get('PATH_INFO', '')
     if not path_info:
         # See if this is a static file hackishly mapped.
         if os.path.exists(self.directory) and os.path.isfile(self.directory):
             app = fileapp.FileApp(self.directory)
             if self.cache_seconds:
                 app.cache_control( max_age=int( self.cache_seconds ) )
             return app(environ, start_response)
         return self.add_slash(environ, start_response)
     if path_info == '/':
         # @@: This should obviously be configurable
         filename = 'index.html'
     else:
         filename = request.path_info_pop(environ)
     full = os.path.join(self.directory, filename)
     if not os.path.exists(full):
         return self.not_found(environ, start_response)
     if os.path.isdir(full):
         # @@: Cache?
         return self.__class__(full)(environ, start_response)
     if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
         return self.error_extra_path(environ, start_response)
     if_none_match = environ.get('HTTP_IF_NONE_MATCH')
     if if_none_match:
         mytime = os.stat(full).st_mtime
         if str(mytime) == if_none_match:
             headers = []
             ETAG.update(headers, mytime)
             start_response('304 Not Modified', headers)
             return ['']  # empty body
     app = fileapp.FileApp(full)
     if self.cache_seconds:
         app.cache_control( max_age=int( self.cache_seconds ) )
     return app(environ, start_response)
Example #14
0
    def __call__(self, environ, start_response):
        # End of URL is now /diff/<rev_id>?context=<context_lines>
        # or /diff/<rev_id>/<rev_id>?context=<context_lines>
        # This allows users to choose how much context they want to see.
        # Old format was /diff/<rev_id>/<rev_id> or /diff/<rev_id>
        """Default method called from /diff URL."""
        z = time.time()

        args = []
        while True:
            arg = path_info_pop(environ)
            if arg is None:
                break
            args.append(arg)

        numlines = 3 # This is the default.

        opts = parse_querystring(environ)
        for opt in opts:
            if opt[0] == 'context':
                try:
                    numlines = int(opt[1])
                except ValueError:
                    pass

        revid_from = args[0]
        # Convert a revno to a revid if we get a revno.
        revid_from = self._history.fix_revid(revid_from)
        change = self._history.get_changes([revid_from])[0]

        if len(args) == 2:
            revid_to = self._history.fix_revid(args[1])
        elif len(change.parents) == 0:
            revid_to = NULL_REVISION
        else:
            revid_to = change.parents[0].revid

        repo = self._branch.branch.repository
        revtree1 = repo.revision_tree(revid_to)
        revtree2 = repo.revision_tree(revid_from)

        diff_content_stream = StringIO()
        show_diff_trees(revtree1, revtree2, diff_content_stream,
                        old_label='', new_label='', context=numlines)

        content = diff_content_stream.getvalue()

        self.log.info('/diff %r:%r in %r secs with %r context' % (revid_from, revid_to,
                                                  time.time() - z, numlines))

        revno1 = self._history.get_revno(revid_from)
        revno2 = self._history.get_revno(revid_to)
        filename = '%s_%s.diff' % (revno1, revno2)
        headers = [
            ('Content-Type', 'application/octet-stream'),
            ('Content-Length', str(len(content))),
            ('Content-Disposition', 'attachment; filename=%s' % (filename,)),
            ]
        start_response('200 OK', headers)
        return [content]
Example #15
0
 def get_args(self, environ):
     args = []
     while True:
         arg = path_info_pop(environ)
         if arg is None:
             break
         args.append(arg)
     return args
Example #16
0
 def __call__(self, req):
     app = self._subapps.get(path_info_pop(req.environ))
     if app:
         return app
     elif self._defapp:
         return self._defapp
     else:
         raise exc.HTTPNotFound('invalid request')
Example #17
0
    def process_request(self, req):
        app = self.apps[path_info_pop(req.environ)]
        def my_start_response(status, headers, exc=None):
          req.send_response(int(status.split(" ")[0]))
          for key, value in headers:
            req.send_header(key, value)
          req.end_headers()

        appiter = app(req.environ, my_start_response)
        for chunk in appiter:
          req.write(chunk)
        raise RequestDone
Example #18
0
    def process_request(self, req):
        app = self.apps[path_info_pop(req.environ)]

        def my_start_response(status, headers, exc=None):
            req.send_response(int(status.split(" ")[0]))
            for key, value in headers:
                req.send_header(key, value)
            req.end_headers()

        appiter = app(req.environ, my_start_response)
        for chunk in appiter:
            req.write(chunk)
        raise RequestDone
Example #19
0
 def view(self, environ, start_response):
     """
     View old exception reports
     """
     id = int(request.path_info_pop(environ))
     if id not in self.debug_infos:
         start_response('500 Server Error', [('Content-type', 'text/html')])
         return [
             "Traceback by id %s does not exist (maybe "
             "the server has been restarted?)" % id
         ]
     debug_info = self.debug_infos[id]
     return debug_info.wsgi_application(environ, start_response)
Example #20
0
 def lookup_app(self, environ):
     # Check again if the branch is blocked from being served, this is
     # mostly for tests. It's already checked in apps/transport.py
     if self.branch.get_config().get_user_option('http_serve') == 'False':
         raise httpexceptions.HTTPNotFound()
     self._url_base = environ['SCRIPT_NAME']
     self._static_url_base = environ.get('loggerhead.static.url')
     if self._static_url_base is None:
         self._static_url_base = self._url_base
     self._environ = environ
     if self.served_url is _DEFAULT:
         public_branch = self.public_branch_url()
         if public_branch is not None:
             self.served_url = public_branch
         else:
             # Loggerhead only supports serving .bzr/ on local branches, so
             # we shouldn't suggest something that won't work.
             try:
                 util.local_path_from_url(self.branch.base)
                 self.served_url = self.url([])
             except breezy.errors.InvalidURL:
                 self.served_url = None
     for hook in self.hooks['controller']:
         controller = hook(self, environ)
         if controller is not None:
             return controller
     path = request.path_info_pop(environ)
     if not path:
         raise httpexceptions.HTTPMovedPermanently(
             self.absolute_url('/changes'))
     if path == 'static':
         return static_app
     elif path == '+json':
         environ['loggerhead.as_json'] = True
         path = request.path_info_pop(environ)
     cls = self.controllers_dict.get(path)
     if cls is not None:
         return cls(self, self.get_history)
     raise httpexceptions.HTTPNotFound()
Example #21
0
 def __call__(self, environ, start_response):
     environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
     environ['loggerhead.path_info'] = environ['PATH_INFO']
     if environ['PATH_INFO'].startswith('/static/'):
         segment = path_info_pop(environ)
         assert segment == 'static'
         return static_app(environ, start_response)
     elif environ['PATH_INFO'] == '/favicon.ico':
         return favicon_app(environ, start_response)
     elif environ['PATH_INFO'] == '/robots.txt':
         return robots_app(environ, start_response)
     else:
         transport = get_transport_for_thread(self.base)
         return BranchesFromTransportServer(transport, self)(environ,
                                                             start_response)
Example #22
0
 def view(self, environ, start_response):
     """
     View old exception reports
     """
     id = int(request.path_info_pop(environ))
     if id not in self.debug_infos:
         start_response(
             '500 Server Error',
             [('Content-type', 'text/html')])
         return [
             "Traceback by id %s does not exist (maybe "
             "the server has been restarted?)"
             % id]
     debug_info = self.debug_infos[id]
     return debug_info.wsgi_application(environ, start_response)
Example #23
0
 def __call__(self, environ, start_response):
     environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
     environ['loggerhead.path_info'] = environ['PATH_INFO']
     path_info = environ['PATH_INFO']
     if path_info.startswith('/static/'):
         segment = path_info_pop(environ)
         assert segment == 'static'
         return static_app(environ, start_response)
     elif path_info == '/favicon.ico':
         return favicon_app(environ, start_response)
     elif environ['PATH_INFO'] == '/robots.txt':
         return robots_app(environ, start_response)
     else:
         transport = get_transport_for_thread(self.base)
         # segments starting with ~ are user branches
         if path_info.startswith('/~'):
             segment = path_info_pop(environ)
             return BranchesFromTransportServer(
                 transport.clone(segment[1:]), self,
                 segment)(environ, start_response)
         else:
             return BranchesFromTransportServer(
                 transport.clone(self.trunk_dir), self)(environ,
                                                        start_response)
Example #24
0
 def __call__(self, environ, start_response):
     conf = environ['paste.config']['app_conf']
     environ['olpctag.base_path'] = environ['SCRIPT_NAME'] or '/'
     if 'olpctag.group_info' not in environ:
         if 'group' in conf:
             group_info = {
                 'slug': conf['group'],
                 'name': conf.get('group.name'),
                 'description': conf.get('group.description'),
                 'uri': conf.get('group.uri'),
                 }
         if asbool(conf.get('auto_group')):
             next = path_info_pop(environ)
             if not next:
                 if environ['SCRIPT_NAME'].endswith('/') and not environ['PATH_INFO']:
                     environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'][:-1]
                     environ['PATH_INFO'] = '/'
                 environ['olpctag.show_group_index'] = True
                 return self.app(environ, start_response)
             if not environ['PATH_INFO']:
                 # We went to /foo, need to redirect to /foo/
                 url = construct_url(environ, with_query_string=False)
                 url += '/'
                 if environ['QUERY_STRING']:
                     url += '?' + environ['QUERY_STRING']
                 exc = httpexceptions.HTTPMovedPermanently(
                     headers=[('Location', url)])
                 return exc(environ, start_response)
             group_info = {
                 'slug': next,
                 'name': None,
                 'description': None,
                 'uri': None,
                 }
         else:
             assert 0, "No group can be found"
         environ['olpctag.group_info'] = group_info
     else:
         group_info = environ['olpctag.group_info']
     try:
         g = model.Group.bySlug(group_info['slug'])
     except LookupError:
         g = model.Group(slug=group_info['slug'])
     for key in ['name', 'description', 'uri']:
         if group_info.get(key) and not getattr(g, key, None):
             setattr(g, key, group_info[key])
     environ['olpctag.group'] = g
     return self.app(environ, start_response)
Example #25
0
    def parse_args(self, environ):
        kwargs = dict(parse_querystring(environ))
        util.set_context(kwargs)
        args = []
        while True:
            arg = path_info_pop(environ)
            if arg is None:
                break
            args.append(arg)

        path = None
        if len(args) > 1:
            path = unicode('/'.join(args[1:]), 'utf-8')
        self.args = args
        self.kwargs = kwargs
        return path
Example #26
0
    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)
Example #27
0
    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)
Example #28
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')
        if not path_info:
            return self.add_slash(environ, start_response)
        directory = "%s" % self.directory
        if not path_info.startswith(
                '/%s/' % self.version) and version_re.match(
                    path_info) is None and directory == self.root_directory:
            directory = os.path.join(directory, self.version)
        if path_info == '/':
            # @@: This should obviously be configurable
            filename = 'index.html'
        else:
            filename = request.path_info_pop(environ)
        full = self.normpath(os.path.join(directory, filename))
        if not full.startswith(self.root_directory):
            # Out of bounds
            return self.not_found(environ, start_response)
        if not os.path.exists(full):
            return self.not_found(environ, start_response)
        if os.path.isdir(full):
            # @@: Cache?
            return self.__class__(full,
                                  root_directory=self.root_directory,
                                  version=self.version,
                                  cache_max_age=self.cache_max_age)(
                                      environ, start_response)
        if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
            return self.error_extra_path(environ, start_response)
        if_none_match = environ.get('HTTP_IF_NONE_MATCH')
        if if_none_match:
            mytime = os.stat(full).st_mtime
            if str(mytime) == if_none_match:
                headers = []
                ## FIXME: probably should be
                ## ETAG.update(headers, '"%s"' % mytime)
                ETAG.update(headers, mytime)
                start_response('304 Not Modified', headers)
                return ['']  # empty body

        fa = self.make_app(full)
        if self.cache_max_age:
            fa.cache_control(max_age=self.cache_max_age)
        return fa(environ, start_response)
Example #29
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')
        if not path_info:
            return self.add_slash(environ, start_response)
        if path_info == '/':
            # @@: This should obviously be configurable
            filename = 'index.html'
        else:
            filename = request.path_info_pop(environ)
        resource = os.path.normcase(
            os.path.normpath(self.resource_name + '/' + filename))
        if ((self.root_resource is not None)
                and (not resource.startswith(self.root_resource))):
            # Out of bounds
            return self.not_found(environ, start_response)
        if not pkg_resources.resource_exists(self.package_name, resource):
            return self.not_found(environ, start_response)
        if pkg_resources.resource_isdir(self.package_name, resource):
            # @@: Cache?
            child_root = (self.root_resource is not None and self.root_resource
                          or self.resource_name)
            return self.__class__(self.package_name,
                                  resource,
                                  root_resource=child_root,
                                  cache_max_age=self.cache_max_age)(
                                      environ, start_response)
        if (environ.get('PATH_INFO')
                and environ.get('PATH_INFO') != '/'):  # pragma: no cover
            return self.error_extra_path(environ, start_response)
        full = pkg_resources.resource_filename(self.package_name, resource)
        if_none_match = environ.get('HTTP_IF_NONE_MATCH')
        if if_none_match:
            mytime = os.stat(full).st_mtime
            if str(mytime) == if_none_match:
                headers = []
                ETAG.update(headers, mytime)
                start_response('304 Not Modified', headers)
                return ['']  # empty body

        fa = self.make_app(full)
        if self.cache_max_age:
            fa.cache_control(max_age=self.cache_max_age)
        return fa(environ, start_response)
Example #30
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')
        if not path_info:
            return self.add_slash(environ, start_response)
        if path_info == '/':
            # @@: This should obviously be configurable
            filename = 'index.html'
        else:
            filename = request.path_info_pop(environ)
        full = os.path.normcase(os.path.normpath(
            os.path.join(self.directory, filename)))
        if os.path.sep != '/':
            full = full.replace('/', os.path.sep)
        if self.root_directory is not None and not full.startswith(self.root_directory):
            # Out of bounds
            return self.not_found(environ, start_response)
        if not os.path.exists(full):
            if full.endswith('index.html') and not os.path.isfile(full):
                start_response('200 OK', [('Content-Type', 'text/html')])
                return [self.get_index_html()]
            return self.not_found(environ, start_response)
        if os.path.isdir(full):
            # @@: Cache?
            child_root = self.root_directory is not None and \
                self.root_directory or self.directory
            return self.__class__(full, root_directory=child_root,
                                  cache_max_age=self.cache_max_age)(environ,
                                                                   start_response)
        if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
            return self.error_extra_path(environ, start_response)
        if_none_match = environ.get('HTTP_IF_NONE_MATCH')
        if if_none_match:
            mytime = os.stat(full).st_mtime
            if str(mytime) == if_none_match:
                headers = []
                ETAG.update(headers, mytime)
                start_response('304 Not Modified', headers)
                return [''] # empty body

        fa = self.make_app(full)
        if self.cache_max_age:
            fa.cache_control(max_age=self.cache_max_age)
        return fa(environ, start_response)
Example #31
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')
        if not path_info:
            return self.add_slash(environ, start_response)
        if path_info == '/':
            # @@: This should obviously be configurable
            filename = 'index.html'
        else:
            filename = request.path_info_pop(environ)
        full = os.path.normcase(
            os.path.normpath(os.path.join(self.directory, filename)))
        if os.path.sep != '/':
            full = full.replace('/', os.path.sep)
        if self.root_directory is not None and not full.startswith(
                self.root_directory):
            # Out of bounds
            return self.not_found(environ, start_response)
        if not os.path.exists(full):
            return self.not_found(environ, start_response)
        if os.path.isdir(full):
            # @@: Cache?
            child_root = self.root_directory is not None and \
                self.root_directory or self.directory
            return self.__class__(full,
                                  root_directory=child_root,
                                  cache_max_age=self.cache_max_age)(
                                      environ, start_response)
        if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
            return self.error_extra_path(environ, start_response)
        if_none_match = environ.get('HTTP_IF_NONE_MATCH')
        if if_none_match:
            mytime = os.stat(full).st_mtime
            if str(mytime) == if_none_match:
                headers = []
                ETAG.update(headers, mytime)
                start_response('304 Not Modified', headers)
                return ['']  # empty body

        fa = self.make_app(full)
        if self.cache_max_age:
            fa.cache_control(max_age=self.cache_max_age)
        return fa(environ, start_response)
Example #32
0
 def app_for_non_branch(self, environ):
     segment = path_info_pop(environ)
     if segment is None:
         raise httpexceptions.HTTPMovedPermanently.relative_redirect(
             environ['SCRIPT_NAME'] + '/', environ)
     elif segment == '':
         if self.name:
             name = self.name
         else:
             name = '/'
         return DirectoryUI(environ['loggerhead.static.url'],
                            self.transport, name)
     else:
         new_transport = self.transport.clone(segment)
         if self.name:
             new_name = urlutils.join(self.name, segment)
         else:
             new_name = '/' + segment
         return BranchesFromTransportServer(new_transport, self.root,
                                            new_name)
Example #33
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')
        if not path_info:
            return self.add_slash(environ, start_response)
        if path_info == '/':
            # @@: This should obviously be configurable
            filename = 'index.html'
        else:
            filename = request.path_info_pop(environ)
        resource = os.path.normcase(os.path.normpath(
                    self.resource_name + '/' + filename))
        if ( (self.root_resource is not None) and
            (not resource.startswith(self.root_resource)) ):
            # Out of bounds
            return self.not_found(environ, start_response)
        if not pkg_resources.resource_exists(self.package_name, resource):
            return self.not_found(environ, start_response)
        if pkg_resources.resource_isdir(self.package_name, resource):
            # @@: Cache?
            child_root = (self.root_resource is not None and
                          self.root_resource or self.resource_name)
            return self.__class__(
                self.package_name, resource, root_resource=child_root,
                cache_max_age=self.cache_max_age)(environ, start_response)
        if (environ.get('PATH_INFO')
            and environ.get('PATH_INFO') != '/'): # pragma: no cover
            return self.error_extra_path(environ, start_response) 
        full = pkg_resources.resource_filename(self.package_name, resource)
        if_none_match = environ.get('HTTP_IF_NONE_MATCH')
        if if_none_match:
            mytime = os.stat(full).st_mtime
            if str(mytime) == if_none_match:
                headers = []
                ETAG.update(headers, mytime)
                start_response('304 Not Modified', headers)
                return [''] # empty body

        fa = self.make_app(full)
        if self.cache_max_age:
            fa.cache_control(max_age=self.cache_max_age)
        return fa(environ, start_response)
Example #34
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')
        if not path_info:
            return self.add_slash(environ, start_response)
        if path_info == '/':
            # @@: This should obviously be configurable
            filename = 'index.html'
        else:
            filename = request.path_info_pop(environ)
        resource = os.path.normcase(os.path.normpath(
                    self.resource_name + '/' + filename))
        if self.root_resource is not None and not resource.startswith(self.root_resource):
            # Out of bounds
            return self.not_found(environ, start_response)
        if not self.egg.has_resource(resource):
            return self.not_found(environ, start_response)
        if self.egg.resource_isdir(resource):
            # @@: Cache?
            child_root = self.root_resource is not None and self.root_resource or \
                self.resource_name
            return self.__class__(self.egg, resource, self.manager,
                                  root_resource=child_root)(environ, start_response)
        if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
            return self.error_extra_path(environ, start_response)

        type, encoding = mimetypes.guess_type(resource)
        if not type:
            type = 'application/octet-stream'
        # @@: I don't know what to do with the encoding.
        try:
            file = self.egg.get_resource_stream(self.manager, resource)
        except (IOError, OSError) as e:
            exc = httpexceptions.HTTPForbidden(
                'You are not permitted to view this file (%s)' % e)
            return exc.wsgi_application(environ, start_response)
        start_response('200 OK',
                       [('content-type', type)])
        return fileapp._FileIter(file)
Example #35
0
    def __call__(self, environ, start_response):
        request_is_private = (environ['SERVER_PORT'] == str(
            config.codebrowse.private_port))
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
        if environ['PATH_INFO'].startswith('/static/'):
            path_info_pop(environ)
            return static_app(environ, start_response)
        elif environ['PATH_INFO'] == '/favicon.ico':
            return favicon_app(environ, start_response)
        elif environ['PATH_INFO'] == '/robots.txt':
            return robots_app(environ, start_response)
        elif not request_is_private:
            if environ['PATH_INFO'].startswith('/+login'):
                return self._complete_login(environ, start_response)
            elif environ['PATH_INFO'].startswith('/+logout'):
                return self._logout(environ, start_response)
        path = environ['PATH_INFO']
        trailingSlashCount = len(path) - len(path.rstrip('/'))
        if request_is_private:
            # Requests on the private port are internal API requests from
            # something that has already performed security checks.  As
            # such, they get read-only access to everything.
            identity_url = LAUNCHPAD_SERVICES
            user = LAUNCHPAD_SERVICES
        else:
            identity_url = environ[self.session_var].get(
                'identity_url', LAUNCHPAD_ANONYMOUS)
            user = environ[self.session_var].get('user', LAUNCHPAD_ANONYMOUS)
        lp_server = get_lp_server(identity_url,
                                  branch_transport=self.get_transport())
        lp_server.start_server()
        try:

            try:
                branchfs = self.get_branchfs()
                transport_type, info, trail = branchfs.translatePath(
                    identity_url, urlutils.escape(path))
            except xmlrpclib.Fault as f:
                if check_fault(f, faults.PathTranslationError):
                    raise HTTPNotFound()
                elif check_fault(f, faults.PermissionDenied):
                    # If we're not allowed to see the branch...
                    if environ['wsgi.url_scheme'] != 'https':
                        # ... the request shouldn't have come in over http, as
                        # requests for private branches over http should be
                        # redirected to https by the dynamic rewrite script we
                        # use (which runs before this code is reached), but
                        # just in case...
                        env_copy = environ.copy()
                        env_copy['wsgi.url_scheme'] = 'https'
                        raise HTTPMovedPermanently(construct_url(env_copy))
                    elif user != LAUNCHPAD_ANONYMOUS:
                        # ... if the user is already logged in and still can't
                        # see the branch, they lose.
                        exc = HTTPUnauthorized()
                        exc.explanation = "You are logged in as %s." % user
                        raise exc
                    else:
                        # ... otherwise, lets give them a chance to log in
                        # with OpenID.
                        return self._begin_login(environ, start_response)
                else:
                    raise
            if transport_type != BRANCH_TRANSPORT:
                raise HTTPNotFound()
            trail = urlutils.unescape(trail).encode('utf-8')
            trail += trailingSlashCount * '/'
            amount_consumed = len(path) - len(trail)
            consumed = path[:amount_consumed]
            branch_name = consumed.strip('/')
            self.log.info('Using branch: %s', branch_name)
            if trail and not trail.startswith('/'):
                trail = '/' + trail
            environ['PATH_INFO'] = trail
            environ['SCRIPT_NAME'] += consumed.rstrip('/')
            branch_url = lp_server.get_url() + branch_name
            branch_link = urlparse.urljoin(config.codebrowse.launchpad_root,
                                           branch_name)
            cachepath = os.path.join(config.codebrowse.cachepath,
                                     branch_name[1:])
            if not os.path.isdir(cachepath):
                os.makedirs(cachepath)
            self.log.info('branch_url: %s', branch_url)
            private = info['private']
            if private:
                self.log.info("Branch is private")
            else:
                self.log.info("Branch is public")

            try:
                bzr_branch = safe_open(lp_server.get_url().strip(':/'),
                                       branch_url)
            except errors.NotBranchError as err:
                self.log.warning('Not a branch: %s', err)
                raise HTTPNotFound()
            bzr_branch.lock_read()
            try:
                view = BranchWSGIApp(bzr_branch,
                                     branch_name, {'cachepath': cachepath},
                                     self.graph_cache,
                                     branch_link=branch_link,
                                     served_url=None,
                                     private=private)
                return view.app(environ, start_response)
            finally:
                bzr_branch.repository.revisions.clear_cache()
                bzr_branch.repository.signatures.clear_cache()
                bzr_branch.repository.inventories.clear_cache()
                if bzr_branch.repository.chk_bytes is not None:
                    bzr_branch.repository.chk_bytes.clear_cache()
                bzr_branch.repository.texts.clear_cache()
                bzr_branch.unlock()
        finally:
            lp_server.stop_server()
Example #36
0
 def __call__(self, environ, start_response):
     path_info_pop(environ)
     path_info_pop(environ)
     #info("PATH_INFO = " + environ["PATH_INFO"]) 
     return WSGIApplication.__call__(self, environ, start_response)
Example #37
0
    def __call__(self, environ, start_response):
        base_url = self.config['controller']
        req_url = environ.get('PATH_INFO')
        if not req_url.startswith(base_url + '/') and req_url != base_url:
            return self.not_found(start_response)

        proc_start = time.time()

        try:
            assert self.access_key == environ.get('HTTP_AUTHORIZATION')
            log.debug('Access granted with key %s' % \
                environ.get('HTTP_AUTHORIZATION'))
        except:
            log.warn('Access unauthorized. Environment:\n%s' % environ)
            return self.auth_required(start_response)

        environ['SCRIPT_NAME'] = base_url
        environ['PATH_INFO'] = environ['PATH_INFO'].split(base_url)[1]

        servicename = path_info_pop(environ)
        # Describe myself
        if not servicename:
            desc = self.describe(start_response)
            log.info('Describing esb')
            log.debug('Returning %s' % desc[0])
            return desc

        try:
            service = self.services[servicename]['service']
        except:
            # There is no such service
            log.warn('Service %s not found or not working' % servicename)
            return self.not_found(start_response)
        
        methodname = path_info_pop(environ)
        if not methodname:
            # The request about the service itself
            desc = self.describe_service(servicename, start_response)
            log.info('Describing %s' % servicename)
            log.debug('Returning %s' % desc[0])
            return desc

        # A method was called
        try:
            method = getattr(service, methodname)
            assert getattr(method, 'webmethod', False)
        except:
            # The service does not have such a webmethod
            log.warn('A webmethod %s.%s not found' % (servicename, methodname))
            return self.not_found(start_response)

        kargs = dict()
        try:
            kargs = dict(parse_formvars(environ, include_get_vars=True))
            for karg in kargs.keys():
                kargs[karg] = from_json(kargs[karg])
        except:
            log.warn('Failed to parse parameters for %s.%s: %s' % (servicename,
                methodname, kargs))
            return self.request_error(start_response, 'Invalid parameters')

        # Extract the positional arguments:
        args = kargs.pop('__dwsargs__', [])

        # Call the method
        if is_testing():
            result = method(*args, **kargs)
            result = to_json(result)
        else:
            try:
                exec_start = time.time()
                result = method(*args, **kargs)
                exec_time = (time.time() - exec_start) * 1000

                log.info('%s.%s finished in %.2f ms' % (servicename,
                    methodname, exec_time))
                log.debug('\nArgs: %s\nKargs: %s\nResult: %s' % (args, kargs,
                    result))

                result = to_json(result)
                elixir.session.close()
            except Exception, e:
                exc = format_exc(e)
                start_response('500 Internal Server Error',
                    [('Content-Type', 'text/html')])

                log.error('%s.%s\n%s' % (servicename, methodname, exc))
                elixir.session.close()
                return ['Internal server error']
Example #38
0
    def __call__(self, environ, start_response):
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
        if environ['PATH_INFO'].startswith('/static/'):
            path_info_pop(environ)
            return static_app(environ, start_response)
        elif environ['PATH_INFO'] == '/favicon.ico':
            return favicon_app(environ, start_response)
        elif environ['PATH_INFO'] == '/robots.txt':
            return robots_app(environ, start_response)
        elif environ['PATH_INFO'].startswith('/+login'):
            return self._complete_login(environ, start_response)
        elif environ['PATH_INFO'].startswith('/+logout'):
            return self._logout(environ, start_response)
        path = environ['PATH_INFO']
        trailingSlashCount = len(path) - len(path.rstrip('/'))
        user = environ[self.session_var].get('user', LAUNCHPAD_ANONYMOUS)
        lp_server = get_lp_server(user, branch_transport=self.get_transport())
        lp_server.start_server()
        try:

            try:
                transport_type, info, trail = self.branchfs.translatePath(
                    user, urlutils.escape(path))
            except xmlrpclib.Fault as f:
                if check_fault(f, faults.PathTranslationError):
                    raise HTTPNotFound()
                elif check_fault(f, faults.PermissionDenied):
                    # If we're not allowed to see the branch...
                    if environ['wsgi.url_scheme'] != 'https':
                        # ... the request shouldn't have come in over http, as
                        # requests for private branches over http should be
                        # redirected to https by the dynamic rewrite script we
                        # use (which runs before this code is reached), but
                        # just in case...
                        env_copy = environ.copy()
                        env_copy['wsgi.url_scheme'] = 'https'
                        raise HTTPMovedPermanently(construct_url(env_copy))
                    elif user != LAUNCHPAD_ANONYMOUS:
                        # ... if the user is already logged in and still can't
                        # see the branch, they lose.
                        exc = HTTPUnauthorized()
                        exc.explanation = "You are logged in as %s." % user
                        raise exc
                    else:
                        # ... otherwise, lets give them a chance to log in
                        # with OpenID.
                        return self._begin_login(environ, start_response)
                else:
                    raise
            if transport_type != BRANCH_TRANSPORT:
                raise HTTPNotFound()
            trail = urlutils.unescape(trail).encode('utf-8')
            trail += trailingSlashCount * '/'
            amount_consumed = len(path) - len(trail)
            consumed = path[:amount_consumed]
            branch_name = consumed.strip('/')
            self.log.info('Using branch: %s', branch_name)
            if trail and not trail.startswith('/'):
                trail = '/' + trail
            environ['PATH_INFO'] = trail
            environ['SCRIPT_NAME'] += consumed.rstrip('/')
            branch_url = lp_server.get_url() + branch_name
            branch_link = urlparse.urljoin(
                config.codebrowse.launchpad_root, branch_name)
            cachepath = os.path.join(
                config.codebrowse.cachepath, branch_name[1:])
            if not os.path.isdir(cachepath):
                os.makedirs(cachepath)
            self.log.info('branch_url: %s', branch_url)
            base_api_url = allvhosts.configs['api'].rooturl
            branch_api_url = '%s/%s/%s' % (
                base_api_url,
                'devel',
                branch_name,
                )
            self.log.info('branch_api_url: %s', branch_api_url)
            req = urllib2.Request(branch_api_url)
            private = False
            try:
                # We need to determine if the branch is private
                response = urllib2.urlopen(req)
            except urllib2.HTTPError as response:
                code = response.getcode()
                if code in (400, 401, 403, 404):
                    # There are several error codes that imply private data.
                    # 400 (bad request) is a default error code from the API
                    # 401 (unauthorized) should never be returned as the
                    # requests are always from anon. If it is returned
                    # however, the data is certainly private.
                    # 403 (forbidden) is obviously private.
                    # 404 (not found) implies privacy from a private team or
                    # similar situation, which we hide as not existing rather
                    # than mark as forbidden.
                    self.log.info("Branch is private")
                    private = True
                self.log.info(
                    "Branch state not determined; api error, return code: %s",
                    code)
                response.close()
            else:
                self.log.info("Branch is public")
                response.close()

            try:
                bzr_branch = safe_open(
                    lp_server.get_url().strip(':/'), branch_url)
            except errors.NotBranchError as err:
                self.log.warning('Not a branch: %s', err)
                raise HTTPNotFound()
            bzr_branch.lock_read()
            try:
                view = BranchWSGIApp(
                    bzr_branch, branch_name, {'cachepath': cachepath},
                    self.graph_cache, branch_link=branch_link,
                    served_url=None, private=private)
                return view.app(environ, start_response)
            finally:
                bzr_branch.repository.revisions.clear_cache()
                bzr_branch.repository.signatures.clear_cache()
                bzr_branch.repository.inventories.clear_cache()
                if bzr_branch.repository.chk_bytes is not None:
                    bzr_branch.repository.chk_bytes.clear_cache()
                bzr_branch.repository.texts.clear_cache()
                bzr_branch.unlock()
        finally:
            lp_server.stop_server()