示例#1
0
 def resolve(self, uri, base_uri=None):
     here = os.path.abspath('.')
     if uri.startswith('local:'):
         uri = uri[6:]
         resource = os.path.join(self.templates, uri)
         if os.path.exists(resource):
             return file(resource, 'rb')
         raise UriException(UriException.RESOURCE_ERROR,
                            uri=uri, loc=uri,
                            msg="The file did not exist in '%s'" % self.templates)
     elif uri.startswith('pkg:'):
         # format: package#path/to/file.xslt
         usage = 'usage: package_name#path/to/file'
         uri = uri[4:]
         package, sep, path = uri.partition('#')
         if not package or path:
             raise UriException(
                 UriException.RESOURCE_ERROR,
                 uri=uri, loc=uri,
                 msg="Invalid pkg_resources uri. \n %s" % usage
             )
         if pkg_resources.resource_exists(package, path):
             return pkg_resources.resource_stream(package, path)
         raise UriException(
             UriException.RESOURCE_ERROR,
             uri=uri, loc=uri,
             msg="'%s' was not found in the python package '%s'" % (path, package)
         )
     else:
         return self._orig_resolve(uri, base_uri)
示例#2
0
    def resolve(self, uri, base=None):
        if base:
           uri = self.normalize(uri, base)
        elif old4Suite:
            #workaround bug in older 4Suite, base resolve doesn't check supportedSchemes
            self.normalize(uri, uri)

        if self.uriwhitelist:
            for regex in self.uriwhitelist:
                if re.match(regex,uri):
                    break
            else:
                raise UriException(UriException.RESOURCE_ERROR, uri, 'Unauthorized') 
        if self.uriblacklist:
            for regex in self.uriblacklist:
                if re.match(regex,uri):
                    raise UriException(UriException.RESOURCE_ERROR, uri, 'Unauthorized') 
        return Uri.SchemeRegistryResolver.resolve(self, uri,base)
示例#3
0
    def resolveSiteScheme(self, uri, base=None):
        log.debug('resolving uri: ' + uri)
        if base:
            uri = self.normalize(uri, base) 
        paramMap = {}
        if isinstance(uri, unicode):
            #we need uri to be a string so paramMap below will contain strings not unicode
            uri = uri.encode('utf8') 
        path = uri

        i=path.find('?')
        if i!=-1:
            if path[i+1:]:
                for _paramStr in path[i+1:].split('&'):
                    _sp=_paramStr.split('=')
                    if len(_sp)==2:
                        _key, _value=_sp
                        _value=urllib.unquote_plus(_value)
                        if paramMap.has_key(_key):
                            # Already has a value: make a list out of it
                            if type(paramMap[_key])==type([]):
                                # Already is a list: append the new value to it
                                paramMap[_key].append(_value)
                            else:
                                # Only had one value so far: start a list
                                paramMap[_key]=[paramMap[_key], _value]
                        else:
                            paramMap[_key]=_value
            path = path[:i]
        if path and path[-1]=='/':
            path=path[:-1] # Remove trailing '/' if any
            trailingSlash = True
        else:
            trailingSlash = False
            
        if path.startswith('site://'):
            #print 'path', path
            name = path[len('site://'):] #assume we only get requests inside our home path
        else:
            name = path
        while name and name[0]=='/':
            name=name[1:] # Remove starting '/' if any e.g. from site:///

        if trailingSlash:
            paramMap['_path'] = name+'/'
        try:
            #print 'to resolve!', name, ' ', uri, paramMap
            contents = self.server.requestDispatcher.invoke__(name, **paramMap)
            #print 'resolved', name, ': ', contents
            if hasattr(contents, 'read'): #if its a stream
                return contents            
            if isinstance(contents, unicode):
                contents = contents.encode('utf8')
            return StringIO.StringIO( contents )
        except AttributeError, e: #not found'
            raise UriException(UriException.RESOURCE_ERROR, uri, 'Not Found')
示例#4
0
 def secureFilePathresolve(self, uri, base=None):
     if base:
         uri = self.normalize(uri, base)        
     path =  Uri.UriToOsPath(uri)
     for prefix in self.path:
         if os.path.abspath(path).startswith(os.path.abspath(prefix)):
             if fileCache:#todo: this only works if secure file access is on 
                 return StringIO.StringIO(fileCache.getValue(path))
             else:
                 return SiteUriResolver._resolveFile(path)                
     raise UriException(UriException.RESOURCE_ERROR, uri, 'Unauthorized') 
示例#5
0
    def _orig_resolve(self, uri, baseUri=None):
        """
        This function takes a URI or a URI reference plus a base URI, produces
        a normalized URI using the normalize function if a base URI was given,
        then attempts to obtain access to an entity representing the resource
        identified by the resulting URI, returning the entity as a stream (a
        Python file-like object).

        Raises a UriException if the URI scheme is unsupported or if a stream
        could not be obtained for any reason.
        """
        if baseUri is not None:
            uri = self.normalize(uri, baseUri)
            scheme = Uri.GetScheme(uri)
        else:
            scheme = Uri.GetScheme(uri)
            # since we didn't use normalize(), we need to verify here
            if scheme not in Uri.DEFAULT_URI_SCHEMES:
                if scheme is None:
                    raise ValueError('When the URI to resolve is a relative '
                        'reference, it must be accompanied by a base URI.')
                else:
                    raise UriException(UriException.UNSUPPORTED_SCHEME,
                                       scheme=scheme,
                                       resolver=self.__class__.__name__)

        # Bypass urllib for opening local files. This means we don't get all
        # the extra metadata that urllib adds to the stream (Last-modified,
        # Content-Length, a poorly guessed Content-Type, and the URI), but
        # we also avoid its potentially time-consuming socket.gethostbyname()
        # calls, which aren't even warranted and are part of urllib's dubious
        # interpretation of RFC 1738.
        if scheme == 'file':
            path = Uri.UriToOsPath(uri, attemptAbsolute=False)
            try:
                stream = file(path, 'rb')
            except IOError, e:
                raise UriException(UriException.RESOURCE_ERROR,
                                   loc='%s (%s)' % (uri, path),
                                   uri=uri, msg=str(e))
示例#6
0
    def resolvePathScheme(self, uri, base=None):
        path = uri
        if path.startswith('path:'):
            path = path[len('path:'):]
        path = urllib.url2pathname(path)

        unauthorized = False
        for prefix in self.path:            
            filepath = os.path.join(prefix.strip(), path)
            #check to make sure the path url was trying to sneak outside the path (i.e. by using ..)
            if self.server.SECURE_FILE_ACCESS:
                if not os.path.abspath(filepath).startswith(os.path.abspath(prefix)):
                    unauthorized = True
                    continue
            unauthorized = False
            if os.path.exists(filepath):
                if fileCache:
                    return StringIO.StringIO(fileCache.getValue(filepath))
                else:
                    return SiteUriResolver._resolveFile(filepath)

        if unauthorized:
            raise UriException(UriException.RESOURCE_ERROR, uri, 'Unauthorized')                 
        raise UriException(UriException.RESOURCE_ERROR, uri, 'Not Found')
示例#7
0
        # interpretation of RFC 1738.
        if scheme == 'file':
            path = Uri.UriToOsPath(uri, attemptAbsolute=False)
            try:
                stream = file(path, 'rb')
            except IOError, e:
                raise UriException(UriException.RESOURCE_ERROR,
                                   loc='%s (%s)' % (uri, path),
                                   uri=uri, msg=str(e))
        else:
            # urllib2.urlopen, wrapped by us, will suffice for http, ftp,
            # data and gopher
            try:
                stream = Uri.UrlOpen(uri)
            except IOError, e:
                raise UriException(UriException.RESOURCE_ERROR,
                                   uri=uri, loc=uri, msg=str(e))
        return stream

    def resolve(self, uri, base_uri=None):
        here = os.path.abspath('.')
        if uri.startswith('local:'):
            uri = uri[6:]
            resource = os.path.join(self.templates, uri)
            if os.path.exists(resource):
                return file(resource, 'rb')
            raise UriException(UriException.RESOURCE_ERROR,
                               uri=uri, loc=uri,
                               msg="The file did not exist in '%s'" % self.templates)
        elif uri.startswith('pkg:'):
            # format: package#path/to/file.xslt
            usage = 'usage: package_name#path/to/file'
示例#8
0
 def _resolveFile(path):
     try:
         stream = open(path, 'rb')
     except IOError, e:
         raise UriException(UriException.RESOURCE_ERROR, path, str(e))