Example #1
0
    def wmfactory_listing(self, request):
        if self.dirs is None:
            directory = os.listdir(self.path)
            directory.sort()
        else:
            directory = self.dirs

        files = []; dirs = []

        for path in directory:
            url = urllib.quote(path, "/")
            if os.path.isdir(os.path.join(self.path, path)):
                url = url + '/'
                dirs.append({'link':{"text": path + "/", "href":url},
                             'type': '[Directory]', 'encoding': ''})
            else:
                mimetype, encoding = getTypeAndEncoding(path, self.contentTypes,
                                                        self.contentEncodings,
                                                        self.defaultType)
                files.append({
                    'link': {"text": path, "href": url},
                    'type': '[%s]' % mimetype,
                    'encoding': (encoding and '[%s]' % encoding or '')})

        return files + dirs
Example #2
0
 def render(self, request):
     #print ""
     #print "StaticFile", request
     #print "StaticFile in", request.received_headers
     """You know what you doing."""
     self.restat()
     if self.type is None:
         self.type, self.encoding = static.getTypeAndEncoding(self.basename(),
                                                       self.contentTypes,
                                                       self.contentEncodings,
                                                       self.defaultType)
     if not self.exists():
         return self.childNotFound.render(request)
     if self.isdir():
         return self.redirect(request)
     #for content-length
     fsize = size = self.getFileSize()
     request.setHeader('accept-ranges', 'bytes')
     if self.type:
         request.setHeader('content-type', self.type)
     if self.encoding:
         request.setHeader('content-encoding', self.encoding)
     try:
         f = self.openForReading()
     except IOError, e:
         import errno
         if e[0] == errno.EACCES:
             return error.ForbiddenResource().render(request)
         else:
             raise
Example #3
0
def _render_file(file, request):
    """
    Begin sending the contents of this L{File} (or a subset of the
    contents, based on the 'range' header) to the given request.
    """
    file.restat(False)

    if file.type is None:
        file.type, file.encoding = getTypeAndEncoding(file.basename(),
                                                      file.contentTypes,
                                                      file.contentEncodings,
                                                      file.defaultType)

    if not file.exists():
        return file.childNotFound.render(request)

    if file.isdir():
        return file.redirect(request)

    request.setHeader('accept-ranges', 'bytes')

    try:
        fileForReading = file.openForReading()
    except IOError, e:
        import errno

        if e[0] == errno.EACCES:
            return ForbiddenResource().render(request)
        else:
            raise
Example #4
0
 def getFilesAndDirectories(self, directory):
     files = []
     dirs = []
     for path in directory:
         url = urllib.quote(path.encode('utf8'), "/")
         escapedPath = cgi.escape(path)
         if os.path.isdir(os.path.join(self.path, path)):
             url = url + '/'
             dirs.append({'text': escapedPath + "/", 'href': url,
                          'size': '', 'type': '[Directory]',
                          'encoding': ''})
         else:
             mimetype, encoding = static.getTypeAndEncoding(path, self.contentTypes,
                                                     self.contentEncodings,
                                                     self.defaultType)
             try:
                 size = os.stat(os.path.join(self.path, path)).st_size
             except OSError:
                 continue
             files.append({
                 'text': escapedPath, "href": url,
                 'type': '[%s]' % mimetype,
                 'encoding': (encoding and '[%s]' % encoding or ''),
                 'size': static.formatFileSize(size)})
     return dirs, files
Example #5
0
    def render(self, request):
        #print ""
        #print "BufferFile", request

        # FIXME detect when request is REALLY finished
        if request is None or request.finished :
            print "No request to render!"
            return ''

        """You know what you doing."""
        self.restat()

        if self.type is None:
            self.type, self.encoding = static.getTypeAndEncoding(self.basename(),
                                                          self.contentTypes,
                                                          self.contentEncodings,
                                                          self.defaultType)

        if not self.exists():
            return self.childNotFound.render(request)

        if self.isdir():
            return self.redirect(request)

        #for content-length
        if (self.target_size > 0):
            fsize = size = int(self.target_size)
        else:
            fsize = size = int(self.getFileSize())

        #print fsize

        if size == int(self.getFileSize()):
            request.setHeader('accept-ranges','bytes')

        if self.type:
            request.setHeader('content-type', self.type)
        if self.encoding:
            request.setHeader('content-encoding', self.encoding)

        try:
            f = self.openForReading()
        except IOError, e:
            import errno
            if e[0] == errno.EACCES:
                return error.ForbiddenResource().render(request)
            else:
                raise
Example #6
0
 def prepare_serve(self, f, ip=None):
     id = self.generate_secure_token()
     
     if isinstance(f, types.StringTypes):
         filename = os.path.split(f)[1]
     else:
         filename = f.filename
     
     # detect content type here
     
     self.filelist[id] = {
         'method': RETRIEVE,
         'expiration': datetime.now() + URL_LIFETIME,
         'ip': ip,
         'file': f,
         'content-type': static.getTypeAndEncoding(filename, MIMETYPES, {}, 'application/octet-stream')[0],
     }
     
     return 'http%s://%s:%s/%s/%s/%s' % ((self.configfile.getboolean('general', 'usessl') and 's' or ''), self.ip, self.port, self.scheme, id, urllib.quote_plus(filename))
Example #7
0
def _render_file(file, request):
    """
    Begin sending the contents of this L{File} (or a subset of the
    contents, based on the 'range' header) to the given request.
    """
    file.restat(False)

    if file.type is None:
        file.type, file.encoding = getTypeAndEncoding(file.basename(),
                                                      file.contentTypes,
                                                      file.contentEncodings,
                                                      file.defaultType)

    if not file.exists():
        return file.childNotFound.render(request)

    if file.isdir():
        return file.redirect(request)

    request.setHeader('accept-ranges', 'bytes')

    try:
        fileForReading = file.openForReading()
    except IOError as e:
        import errno

        if e[0] == errno.EACCES:
            return ForbiddenResource().render(request)
        else:
            raise

    #if request.setLastModified(file.getmtime()) is CACHED:
    #    return ''

    producer = file.makeProducer(request, fileForReading)

    if request.method == 'HEAD':
        return ''

    producer.start()
    # and make sure the connection doesn't get closed
    return NOT_DONE_YET
Example #8
0
    def render_GET(self, request):
        """
        Begin sending the contents of this L{File} (or a subset of the
        contents, based on the 'range' header) to the given request.
        """

        from twisted.web.static import getTypeAndEncoding, resource, server

        # no really that's supposed to be "restat"
        self.restat(False)

        if self.type is None:
            self.type, self.encoding = getTypeAndEncoding(self.basename(),
                                              self.contentTypes,
                                              self.contentEncodings,
                                              self.defaultType)

        request.setHeader(str("Cache-Control"),
                str("no-cache, no-store, must-revalidate"))
        request.setHeader(str("Pragma"), str("no-cache"))
        request.setHeader(str("Expires"), str("0"))

        if not self.exists():
            return self.ensure_no_cache(self.childNotFound.render(request))

        if self.isdir():
            return self.redirect(request)

        request.setHeader(str('accept-ranges'), str('bytes'))

        try:
            fileForReading = self.openForReading()
        except IOError, e:
            import errno
            if e[0] == errno.EACCES:
                return resource.ForbiddenResource().render(request)
            else:
                raise
Example #9
0
 def getFilesAndDirectories(self, root, directory):
     files = []
     dirs = []
     for path in directory:
         url = urllib.quote(path.encode('utf8'), "/")
         escapedPath = cgi.escape(path)
         if os.path.isdir(os.path.join(root, path)):
             url = url + '/'
             dirs.append({
                 'name': path,
                 'text': escapedPath + "/",
                 'href': url,
                 'type': 'directory',
                 'size': '',
                 'encoding': ''})
         else:
             mimetype, encoding = static.getTypeAndEncoding(path, self.contentTypes,
                                                     self.contentEncodings,
                                                     self.defaultType)
             size = 0
             modtime = 0
             try:
                 fstat = os.stat(os.path.join(root, path))
                 size = fstat.st_size
                 modtime = time.mktime(datetime.utcfromtimestamp(fstat.st_ctime).timetuple())
             except OSError as e:
                 continue
             files.append({
                 'name': path,
                 'text': escapedPath,
                 "href": url,
                 'type': mimetype,
                 'size': size,
                 'modtime': modtime,
                 'encoding': (encoding and '%s' % encoding or '')})
     return dirs, files
Example #10
0
 # try to open
 try:
     fp = obj.open()
 except IOError, e:
     if e[0] == errno.EACCES:
         msg = "Can not access item %s."
         raise ForbiddenError(msg % str(obj.path))
     raise
 # check if cached
 last_modified = int(obj.getModificationTime())
 if self.setLastModified(last_modified) is http.CACHED:
     self.finish()
     return
 # content type + encoding
 obj.type, obj.enc = static.getTypeAndEncoding(obj.basename(),
                                               obj.content_types,
                                               obj.content_encodings,
                                               obj.default_type)
 if obj.type:
     self.setHeader('content-type', obj.type)
 if obj.enc:
     self.setHeader('content-encoding', obj.enc)
 # file size
 fsize = size = obj.getsize()
 self.setHeader('content-length', str(fsize))
 if self.method == HEAD:
     self.write('')
     self.finish()
     return
 # accept range
 self.setHeader('accept-ranges', 'bytes')
 range = self.getHeader('range')
Example #11
0
    def render(self, request):
        # print ''
        # print 'BufferFile', request

        # FIXME detect when request is REALLY finished
        if request is None or request.finished:
            logger.info('No request to render!')
            return ''
        '''You know what you doing.'''
        self.restat()

        if self.type is None:
            self.type, self.encoding = static.getTypeAndEncoding(
                self.basename(),
                self.contentTypes,
                self.contentEncodings,
                self.defaultType,
            )

        if not self.exists():
            return self.childNotFound.render(request)

        if self.isdir():
            return self.redirect(request)

        # for content-length
        if self.target_size > 0:
            fsize = size = int(self.target_size)
        else:
            fsize = size = int(self.getFileSize())

        # print fsize

        if size == int(self.getFileSize()):
            request.setHeader(b'accept-ranges', b'bytes')

        if self.type:
            request.setHeader(b'content-type', to_bytes(self.type))
        if self.encoding:
            request.setHeader(b'content-encoding', to_bytes(self.encoding))

        try:
            f = self.openForReading()
        except IOError as e:
            import errno

            if e.errno == errno.EACCES:
                return resource.ForbiddenResource().render(request)
            else:
                raise
        if request.setLastModified(self.getmtime()) is http.CACHED:
            return ''
        trans = True

        range = request.getHeader('range')
        # print 'StaticFile', range

        tsize = size
        if range is not None:
            # This is a request for partial data...
            bytesrange = range.split('=')
            assert (bytesrange[0] == 'bytes'
                    ), 'Syntactically invalid http range header!'
            start, end = bytesrange[1].split('-', 1)
            if start:
                start = int(start)
                # Are we requesting something
                # beyond the current size of the file?
                if start >= self.getFileSize():
                    # Retry later!
                    logger.info(bytesrange)
                    logger.info('Requesting data beyond current scope -> '
                                'postpone rendering!')
                    self.upnp_retry = reactor.callLater(
                        1.0, self.render, request)
                    return server.NOT_DONE_YET

                f.seek(start)
                if end:
                    # print(f':{end}')
                    end = int(end)
                else:
                    end = size - 1
            else:
                lastbytes = int(end)
                if size < lastbytes:
                    lastbytes = size
                start = size - lastbytes
                f.seek(start)
                fsize = lastbytes
                end = size - 1
            size = end + 1
            fsize = end - int(start) + 1
            # start is the byte offset to begin, and end is the byte offset
            # to end..  fsize is size to send, tsize is the real size of
            # the file, and size is the byte position to stop sending.
            if fsize <= 0:
                request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
                fsize = tsize
                trans = False
            else:
                request.setResponseCode(http.PARTIAL_CONTENT)
                request.setHeader(
                    b'content-range',
                    f'bytes {str(start)}-{str(end)}/{str(tsize)} '.encode(
                        'ascii'),
                )
                # print 'StaticFile', start, end, tsize

        request.setHeader('content-length', str(fsize))

        if request.method == b'HEAD' or trans is False:
            # pretend we're a HEAD request, so content-length
            # won't be overwritten.
            request.method = b'HEAD'
            return ''
        # print 'StaticFile out', request.headers, request.code

        # return data
        # size is the byte position to stop sending, not how many bytes to send

        BufferFileTransfer(f, size - f.tell(), request)
        # and make sure the connection doesn't get closed
        return server.NOT_DONE_YET
Example #12
0
    def render_GET(self, request):
        pagename = request.path[1:].lower()
        session = request.getSession()          
        if 'controlaula/' in pagename:
            if Configs.TEACHER_UID == pagename[12:]:
                self.teacher_login = Configs.TEACHER_UID
                session.uid = Configs.TEACHER_UID
                request.redirect('/index.html')
                return '{}'
            else:
                request.redirect('/student/chat.html')
                return '{}'            
            
        if  pagename == '':
            request.path='/index.html'
            pagename='index.html'
        #if (request.host.host!='127.0.0.1' or self.teacher_login!=session.uid) and pagename=='index.html':
        if (request.host.host!='127.0.0.1' or self.teacher_login!=session.uid) and (pagename[-4:] == 'html' or pagename[-1:] == '/'):
            request.path='/student/chat.html'
            pagename='student/chat.html'

        #Announce the teacher after the first try of accesing the web interface            
        if not self.publish_service.online:
            self.publish_service.publish()
            
        # Check if requested file exists.    
        if request.path[:13]=='/loginimages/' or request.path[:10]=='/sendfile/':
            requestedfile=os.path.join(Configs.APP_DIR ,request.path[1:])
        elif '/controlaula-chat' in request.path:
                self.channels['controlaula-chat'].append(request)
                return server.NOT_DONE_YET           
        elif request.path[:9]=='/student/':
                requestedfile = os.path.join(self.PageDir,request.path[9:])                
        else:    
                requestedfile = os.path.join(self.PageDir,request.path[1:])

        if pagename == "controlaula":
            requestedfile=os.path.join(Configs.APP_DIR,'controlaula.html')
            
        requestedfile=unquote(requestedfile)
        if not os.path.isfile(requestedfile):
            # Didn't find it? Return an error.
            request.setResponseCode(404)
            return"""
            <html><head><title>404 - No Such Resource</title></head>
            <body><h1>No Such Resource</h1>
            <p>File not found: %s - No such file.</p></body></html>
            """ % requestedfile

        # Look for the requested file.
        f=static.File(requestedfile)

        
        if f.type is None:
            f.type, f.encoding = static.getTypeAndEncoding(requestedfile,
                f.contentTypes,
                f.contentEncodings,
                f.defaultType)        
        
        if f.type:
            ctype=f.type.split(":")[0]
            # Send the headers.
            request.setHeader('content-type', ctype)
            
        if f.encoding:
            request.setHeader('content-encoding', f.encoding)
        # Send the page.               
        if twisted.version.major >= 9:
            static.NoRangeStaticProducer(request,f.openForReading()).start()
        else:
            static.FileTransfer(f.openForReading(), f.getFileSize(), request)
        return server.NOT_DONE_YET
Example #13
0
    def _getFilesAndDirectories(self, directory):
        """
        Helper returning files and directories in given directory listing, with
        attributes to be used to build a table content with
        C{self.linePattern}.

        @return: tuple of (directories, files)
        @rtype: C{tuple} of C{list}
        """

        files = []
        dirs = []
        dirs.append({'text':"<i>Parent Directory</i>", 'href': "..",
                    'size': '', 'type': '',
#                    'encoding': '',
                    'mtime': "",
                    'commstr': ""
        })
        for path in directory:
            if path[0] == ".":      # ignore filenames that begin with "."
                continue
            mtime = time.asctime(time.localtime(os.path.getmtime(os.path.join(self.path, path))))

            url = urllib.quote(path, "/")
            escapedPath = cgi.escape(path)
            # print "path %s url %s escapedPath %s" %(path, url, escapedPath)
            if os.path.isdir(os.path.join(self.path, path)):
                url = url + '/'
                dirs.append({'text': escapedPath + "/", 'href': url,
                             'size': '', 'type': '[Directory]',
#                             'encoding': '',
                             'mtime': mtime,
                             'commstr': ''
                })
            else:
                mimetype, encoding = getTypeAndEncoding(path, self.contentTypes,
                    self.contentEncodings,
                    self.defaultType)
                try:
                    size = os.stat(os.path.join(self.path, path)).st_size
                except OSError:
                    continue

                extension = os.path.splitext(path)[1]
                if extension == ".dbm":					# ignore .dbm files
                    continue
                if extension == ".db":                  # if it's ".db"
                    str = path[:-3]
                    extension = os.path.splitext(str)[1]
                    if extension == ".dbm":             # and if there's also a ".dbm"
                        continue                        # just ignore it - MacOSX (esp. Mountain Lion) likes to
                                                        # add .dbm.db (see comment in snmpsimd.py) - so don't show it


                theCommStr = ""
                if (extension == ".snmprec") or (extension == ".sapwalk") or (extension == ".snmpwalk"):
                    bdLen = len(myBaseDir) + len("/data/")
                    theCommStr = self.path[bdLen:]      # get the path up to .../data
                    if theCommStr != "":                # if it's non-empty
                        theCommStr += "/"               # append the "/"
                    theCommStr += path[:-len(extension)]   # append the file name, less the extension

                ## ** Comment **
                ##   Add attributes the the "elements" displayed in each line

                files.append({
                    'text': escapedPath, "href": url,
                    'type': '[%s]' % mimetype,
#                    'encoding': (encoding and '[%s]' % encoding or ''),
                    'size': formatFileSize(size),
                    'mtime': mtime,
                    'commstr': theCommStr,
                    }
                )
        return dirs, files
Example #14
0
def getContentTypeAndEncoding(resource):
    r_type, r_encoding = getTypeAndEncoding(
        resource.basename(), resource.contentTypes,
        resource.contentEncodings, resource.defaultType)
    return r_type, r_encoding