Exemple #1
0
    def __call__(self, environ, start_response):
        req = Request(environ)

        if req.path_info == '/catalog.json':
            urls = list(self.catalog(req))
            res = Response(
                    body=dumps(urls, indent=4),
                    content_type='application/json',
                    charset='utf-8')
        else:
            for handler in self.config['handlers']:
                url = '/' + handler['url'].lstrip('/')
                pattern = re.escape(url) # FIXME: slash and hack
                if re.search(pattern, req.path):
                    try:
                        if 'file' in handler:
                            res = get_handler(handler['file'])
                        elif 'dir' in handler:
                            path = req.path_info.lstrip('/').rsplit('.', 1)[0]
                            filepath = os.path.join(handler['dir'], path)
                            res = get_handler(filepath)
                    except OpenFileError, e:
                        res = Response(status='404 Not Found', body=e.value)
                    break
            else:
Exemple #2
0
def supported(filepath, handlers=None):
    """Test if a file has a corresponding handler.

    Returns a boolean.

    """
    try:
        get_handler(filepath, handlers)
        return True
    except ExtensionNotSupportedError:
        return False
Exemple #3
0
    def __call__(self, req):
        """WSGI application callable.

        Returns either a file download, directory listing or DAP response.

        """
        path = os.path.abspath(
            os.path.join(self.path, *req.path_info.split("/")))

        if not path.startswith(self.path):
            return HTTPForbidden()
        elif os.path.exists(path):
            if os.path.isdir(path):
                return self.index(path, req)
            else:
                return FileApp(path)

        # strip DAP extension (``.das``, eg) and see if the file exists
        base, ext = os.path.splitext(path)
        if os.path.isfile(base):
            req.environ["pydap.jinja2.environment"] = self.env
            app = ServerSideFunctions(get_handler(base, self.handlers))
            return req.get_response(app)
        else:
            return HTTPNotFound(comment=path)
Exemple #4
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')
        filepath = os.path.abspath(os.path.normpath(os.path.join(
                self.root,
                path_info.lstrip('/').replace('/', os.path.sep))))
        basename, extension = os.path.splitext(filepath)
        assert filepath.startswith(self.root)  # check for ".." exploit

        # try to set our renderer as the default, it none exists
        environ.setdefault('pydap.renderer', self.renderer) 

        # check for regular file or dir request
        if os.path.exists(filepath):
            # it is a file
            if os.path.isfile(filepath):
                # always serve if the file is in the static directory
                relative_filepath = os.path.relpath(filepath, self.root)
                if relative_filepath.startswith('.static' + os.path.sep):
                    pass
                # check that it is viewable according to the custom filter
                elif self.filter_restrict and self._is_hidden(filepath, True):
                    return HTTPNotFound()(environ, start_response)
		    		     
                return FileApp(filepath, content_encoding='')(environ, start_response)
            # it is a directory
            else:
                # check that it is viewable according to the custom filter
                # don't list directories beginning with a .
                if self.filter_restrict and self._is_hidden(filepath, True):
                    return HTTPNotFound()(environ, start_response)
                # return directory listing
                if not path_info.endswith('/'):
                    environ['PATH_INFO'] = path_info + '/'
                    return HTTPSeeOther(construct_url(environ))(environ, start_response)
                return self.index(environ, start_response,
                        'index.html', 'text/html')
        # else check for opendap request
        elif os.path.exists(basename):
            # Update environ with configuration keys (environ wins in case of conflict).
            for k in self.config:
                environ.setdefault(k, self.config[k])
            handler = get_handler(basename, self.handlers)
            return handler(environ, start_response)
        # check for catalog
        elif path_info.endswith('/%s' % self.catalog):
            environ['PATH_INFO'] = path_info[:path_info.rfind('/')]
            return self.index(environ, start_response,
                    'catalog.xml', 'text/xml')
        else:
            return HTTPNotFound()(environ, start_response)
Exemple #5
0
    def __call__(self, environ, start_response):
        req = Request(environ)

        if req.path_info == '/catalog.json':
            urls = list(self.catalog(req))
            res = Response(
                    body=dumps(urls, indent=4),
                    content_type='application/json',
                    charset='utf-8')
        else:
            for handler in self.config['handlers']:
                if re.match(handler['url'], req.path):
                    if 'file' in handler:
                        res = get_handler(handler['file'])
                    elif 'dir' in handler:
                        path = req.path[len(handler['url'].rstrip('/'))+1:].rsplit('.', 1)[0]
                        filepath = os.path.join(handler['dir'], path)
                        res = get_handler(filepath)
                    break
            else:
                res = Response(status='404 Not Found')

        return res(environ, start_response)
Exemple #6
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')
        filepath = os.path.abspath(os.path.normpath(os.path.join(
                self.root,
                path_info.lstrip('/').replace('/', os.path.sep))))
        basename, extension = os.path.splitext(filepath)
        assert filepath.startswith(self.root)  # check for ".." exploit

        # try to set our renderer as the default, it none exists
        environ.setdefault('pydap.renderer', self.renderer) 

        # check for regular file or dir request
        if os.path.exists(filepath):
            if os.path.isfile(filepath):
                # return file download
                return FileApp(filepath)(environ, start_response)
            else:
                # return directory listing
                if not path_info.endswith('/'):
                    environ['PATH_INFO'] = path_info + '/'
                    return HTTPSeeOther(construct_url(environ))(environ, start_response)
                return self.index(environ, start_response,
                        'index.html', 'text/html')
        # else check for opendap request
        elif os.path.exists(basename):
            # Update environ with configuration keys (environ wins in case of conflict).
            for k in self.config:
                environ.setdefault(k, self.config[k])
            handler = get_handler(basename, self.handlers)
            return handler(environ, start_response)
        # check for catalog
        elif path_info.endswith('/%s' % self.catalog):
            environ['PATH_INFO'] = path_info[:path_info.rfind('/')]
            return self.index(environ, start_response,
                    'catalog.xml', 'text/xml')
        else:
            return HTTPNotFound()(environ, start_response)
Exemple #7
0
def supported(filepath, handlers):
    try:
        get_handler(filepath, handlers)
        return True
    except ExtensionNotSupportedError:
        return False
Exemple #8
0
 def test_no_handler_available(self):
     """Test exception raised when file not supported."""
     with self.assertRaises(ExtensionNotSupportedError):
         get_handler("file.bar")
Exemple #9
0
 def test_get_handler(self):
     """Test that we can load a specific handler."""
     handlers = load_handlers(MockWorkingSet())
     handler = get_handler("file.foo", handlers)
     self.assertIsInstance(handler, MockHandler)
Exemple #10
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO', '')

        environ['file_root'] = self.root

        environ['login_url'] = self.login_url
        environ['home_url'] = self.home_url
        environ['record_info_uri'] = self.record_info_uri

        environ['saml_trusted_ca_dir'] = self.saml_trusted_ca_dir
        environ['authz_service_uri'] = self.authz_service_uri
        environ['attr_service_uri'] = self.attr_service_uri

        environ.setdefault('pydap.renderer', self.renderer)

        is_directory = False

        filepath = os.path.abspath(
            os.path.normpath(
                os.path.join(self.root,
                             path_info.lstrip('/').replace('/', os.path.sep))))
        basename, extension = os.path.splitext(filepath)
        assert filepath.startswith(self.root)  # check for ".." exploit

        # check whether the path ends with a slash
        if path_info.endswith(os.path.sep):
            # check for regular file or dir request
            if os.path.exists(filepath):
                # it is actually a file
                if os.path.isfile(filepath):
                    return HTTPNotFound()(environ, start_response)
                # it is a directory
                else:
                    is_directory = True

        # Check if the filepath is a path in the archive
        if self._is_data_path(filepath):

            form = parse_formvars(environ)

            if is_directory:

                if len(form) > 0:
                    glob = form.get('glob', '')
                    depth = int(form.get('depth', '1'))

                    try:
                        multi_file_view = MultiFileView(
                            environ, start_response, filepath, glob, depth)

                        action = form.get('action', '')
                        if action.lower() == 'download':

                            # Download mutiple files.
                            return multi_file_view.download_files()
                        else:

                            # Preview mutiple files for download.
                            return multi_file_view.list_files()

                    except ValueError as e:
                        logger.error(
                            ("An exception has occurred parsing "
                             "multiple files for {0}: {1}".format(filepath,
                                                                  e)))
            else:

                if 'plot' in form:
                    file_plot_view = FilePlotView(environ, start_response,
                                                  filepath, form)

                    if form.get('plot') == 'img':

                        # Generate a plot image from the file.
                        return file_plot_view.generate()
                    else:

                        # Load a form for plotting a file.
                        return file_plot_view.form()

            # No specific action taken.
            # Log access.
            logger.info(
                format_access_message(environ, is_directory=is_directory))

        # Check if the filepath without its extension is a path in the archive
        elif self._is_data_path(basename):

            # File could be being handled by a handler.
            handler = get_handler(basename, self.handlers)

            # Log access.
            logger.info(format_access_message(environ, extension, handler))

        return super(CEDAFileServer, self).__call__(environ, start_response)
Exemple #11
0
 def test_no_handler_available(self):
     """Test exception raised when file not supported."""
     with self.assertRaises(ExtensionNotSupportedError):
         get_handler("file.bar")
Exemple #12
0
 def test_get_handler(self):
     """Test that we can load a specific handler."""
     handlers = load_handlers(MockWorkingSet())
     handler = get_handler("file.foo", handlers)
     self.assertIsInstance(handler, MockHandler)