Example #1
0
 def renderHTTP(self, ctx):
     inevow.IRequest(ctx).setHeader("Content-Type", "text/xml")
     return rend.Page.renderHTTP(self, ctx)
Example #2
0
 def __init__(self, ctx):
     rend.Page.__init__(self)
     self.request = inevow.IRequest(ctx)
     self.nextURL = self.request.args.get("nextURL", ["/"])[0]
Example #3
0
    def checkLogin(self,
                   ctx,
                   session,
                   segments,
                   sessionURL=None,
                   httpAuthCredentials=None):
        """
        Associate the given request with the given session and:

            - log the user in to our portal, if they are accessing a login URL

            - log the user out from our portal (calling their logout callback),
              if they are logged in and accessing a logout URL

            - Move the request parameters saved on the session, if there are
              any, onto the request if a session just started or a login
              just succeeded.

        @return:

            - if the user is already logged in: a 2-tuple of requestObject,
              C{segments} (i.e. the segments parameter)

            - if the user is not logged in and not logging in, call login() to
              initialize an anonymous session, and return a 2-tuple of
              (rootResource, segments-parameter) from that anonymous session.
              This counts as logging in for the purpose of future calls to
              checkLogin.

            - if the user is accessing a login URL: a 2-tuple of the logged in
              resource object root and the remainder of the segments (i.e. the
              URL minus __login__) to be passed to that resource.

        """
        request = inevow.IRequest(ctx)
        session.touch()
        request.session = session
        root = url.URL.fromContext(request)
        if sessionURL is not None:
            root = root.child(sessionURL)
        request.rememberRootURL(str(root))

        spoof = False
        if getattr(session, 'sessionJustStarted', False):
            del session.sessionJustStarted
            spoof = True
        if getattr(session, 'justLoggedIn', False):
            del session.justLoggedIn
            spoof = True
        if spoof and hasattr(session, 'args'):
            request.args = session.args
            request.fields = session.fields
            request.content = io.StringIO()
            request.content.close()
            request.method = session.method
            request.received_headers = session.received_headers

            del session.args, session.fields, session.method, session.received_headers

        if segments and segments[0] in (LOGIN_AVATAR, LOGOUT_AVATAR):
            authCommand = segments[0]
        else:
            authCommand = None

        if httpAuthCredentials:
            # This is the FIRST TIME we have hit an HTTP auth session with our
            # credentials.  We are going to perform login.
            assert not authCommand, (
                "HTTP auth support isn't that robust.  "
                "Come up with something to do that makes sense here.")
            return self.login(request, session, httpAuthCredentials,
                              segments).addErrback(self.authRequiredError,
                                                   session)

        if authCommand == LOGIN_AVATAR:
            subSegments = segments[1:]

            def unmangleURL(xxx_todo_changeme):
                # Tell the session that we just logged in so that it will
                # remember form values for us.
                (res, segs) = xxx_todo_changeme
                session.justLoggedIn = True
                # Then, generate a redirect back to where we're supposed to be
                # by looking at the root of the site and calculating the path
                # down from there using the segments we were passed.
                u = url.URL.fromString(request.getRootURL())
                for seg in subSegments:
                    u = u.child(seg)
                return u, ()

            return self.login(request, session, self.getCredentials(request),
                              subSegments).addCallback(unmangleURL).addErrback(
                                  self.incorrectLoginError, ctx, subSegments,
                                  "Incorrect login.")
        elif authCommand == LOGOUT_AVATAR:
            self.explicitLogout(session)
            return urlToChild(ctx, *segments[1:]), ()
        else:
            r = session.resourceForPortal(self.portal)
            if r:
                ## Delegate our getChild to the resource our portal says is the right one.
                return r[0], segments
            else:
                # XXX I don't think that the errback here will work at all,
                # because the redirect loop would be infinite.  Perhaps this
                # should be closer to the HTTP auth path?
                return self.login(request, session, Anonymous(),
                                  segments).addErrback(
                                      self.incorrectLoginError, ctx, segments,
                                      'Anonymous access not allowed.')
Example #4
0
 def renderTitle(self, ctx, data):
     return "QSOS Repository/%s" % ("/".join(
         inevow.IRequest(ctx).prepath[1:]), )
Example #5
0
 def renderHTTP(self, ctx):
     request = inevow.IRequest(ctx)
     request.setHeader("content-type", "text/plain")
     return self._getContent()
Example #6
0
 def renderHTTP(self, ctx):
     request = inevow.IRequest(ctx)
     request.startedWriting = 1
     return File(self.path, registry=self.registry)
Example #7
0
 def prefix(c, d):
     pre = inevow.IRequest(c).path
     if pre.endswith('/'):
         return pre
     return pre + '/'
Example #8
0
 def renderHTTP( self, ctx ):
     request = inevow.IRequest( ctx )
     if request.method == 'POST':
         return self.renderPOST( ctx )
     else:
         return self.renderGET( ctx )
Example #9
0
 def locateChild(self, ctx, segments):
     request = inevow.IRequest(ctx)
     request.setResponseCode(400)
     return self, ()
Example #10
0
    def submitted_cancel_installation(self, ctx, form, data):
        print 'submitted_cancel_installation'

        request = inevow.IRequest(ctx)
        request.redirect(request.URLPath().sibling('welcome.html'))
        return ''
Example #11
0
 def render_pythonClass(self, ctx, data):
     return self.pythonClass(inevow.IRequest(ctx), ctx.tag)
Example #12
0
    def submitted_select_target(self, ctx, form, data):
        print 'submitted_select_target'

        # XXX: target selection error messages as constants?
        fda = formalutils.FormDataAccessor(form, [], ctx)
        target = None
        recovery = False
        large_install = False
        try:
            target = form.data['selecttarget.target']
            print 'selected target: %s' % target

            medium = mediahelper.get_media().get_medium_by_device_name(target)
            if medium.get_size() < constants.DISK_SIZE_MINIMUM:
                fda.add_error('selecttarget.target',
                              'Minimum target medium size is 2 GB')
            if medium.is_write_protected():
                fda.add_error('selecttarget.target',
                              'Target medium is write-protected')

            if form.data.has_key('selecttarget.recovery'):
                recovery = form.data['selecttarget.recovery']

            if medium.get_size(
            ) >= constants.DISK_SIZE_MINIMUM_FOR_LARGE_INSTALL:
                large_install = True
        except:
            fda.add_error('selecttarget.target',
                          'Target medium cannot be selected')
        fda.finalize_validation()

        root = livecddb.get_livecd_database_root()
        root.setS(ns_ui.targetDevice, rdf.String, target)
        root.setS(ns_ui.attemptRecovery, rdf.Boolean, recovery)
        root.removeNodes(ns_ui.previousConfigurationRdfXml)
        root.removeNodes(ns_ui.previousInstalledVersion)

        # Recovery check here
        if recovery:
            print 'attempting recovery from %s' % target

            try:
                prev_cfg, prev_version = installhelpers.recover_existing_configuration(
                    target)
                if prev_cfg is not None:
                    root.setS(ns_ui.previousConfigurationRdfXml, rdf.String,
                              prev_cfg.encode('hex'))

                    if prev_version is not None:
                        root.setS(ns_ui.previousInstalledVersion, rdf.String,
                                  prev_version)
                    else:
                        pass
                else:
                    raise Exception('did not find recovery data')
            except:
                print 'recovery failed'

        # Select installation model based on target size
        root.setS(ns_ui.installLargeDisk, rdf.Boolean, large_install)

        print livecddb.dump_livecd_database()
        request = inevow.IRequest(ctx)
        request.redirect(request.URLPath().sibling('installconfirm.html'))
        return ''
Example #13
0
 def renderHTTP(self, ctx):
     request = inevow.IRequest(ctx)
     request.setHeader('Expires', 'Fri, 25 Nov 1966 08:22:00 EST')
     request.setHeader("Cache-Control", "no-store, no-cache, must-revalidate")
     request.setHeader("Pragma", "no-cache")
     return LivePage.renderHTTP(self, ctx)
Example #14
0
 def locateChild(self, ctx, segments):
     request = inevow.IRequest(ctx)
     request.prepath = request.prepath[3:]
     return request.site.resource, segments
Example #15
0
 def renderHTTP(self, ctx):
     req = inevow.IRequest(ctx)
     t = get_arg(req, "t")
     if t == "json":
         return self.render_JSON(req)
     return rend.Page.renderHTTP(self, ctx)
Example #16
0
 def want_json(self, ctx):
     output = get_arg(inevow.IRequest(ctx), "output", "").lower()
     if output.lower() == "json":
         return True
     return False
Example #17
0
    def renderHTTP(self, ctx):
        """You know what you doing."""
        self.fp.restat()

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

        if not self.fp.exists():
            return rend.FourOhFour()

        request = inevow.IRequest(ctx)

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

        # fsize is the full file size
        # size is the length of the part actually transmitted
        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 as e:
            import errno
            if e[0] == errno.EACCES:
                return ForbiddenResource().render(request)
            else:
                raise

        if request.setLastModified(
                self.fp.getModificationTime()) is http.CACHED:
            return ''

        try:
            range = request.getHeader('range')

            if range is not None:
                # This is a request for partial data...
                bytesrange = string.split(range, '=')
                assert bytesrange[0] == 'bytes',\
                       "Syntactically invalid http range header!"
                start, end = string.split(bytesrange[1], '-')
                if start:
                    f.seek(int(start))
                if end:
                    end = int(end)
                else:
                    end = fsize - 1
                request.setResponseCode(http.PARTIAL_CONTENT)
                request.setHeader(
                    'content-range',
                    "bytes %s-%s/%s" % (str(start), str(end), str(fsize)))
                #content-length should be the actual size of the stuff we're
                #sending, not the full size of the on-server entity.
                size = 1 + end - int(start)

            request.setHeader('content-length', str(size))
        except:
            traceback.print_exc(file=log.logfile)

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

        # return data
        FileTransfer(f, size, request)
        # and make sure the connection doesn't get closed
        return request.deferred
Example #18
0
 def json(self, ctx):
     inevow.IRequest(ctx).setHeader("content-type", "text/plain")
     data = json_check_and_repair_results(self.r)
     return json.dumps(data, indent=1) + "\n"
Example #19
0
def canvas(width, height, delegate, useCGI=False):
    C = cookie()
    if useCGI:
        global _canvasCGIService
        if _canvasCGIService is None:
            from nevow import appserver
            # Import reactor here to avoid installing default at startup
            from twisted.internet import reactor
            _canvasCGIService = reactor.listenTCP(
                0, appserver.NevowSite(Canvas(docFactory=canvasServerMessage)))
            _canvasCGIService.dispatchMap = {}
        port = _canvasCGIService.getHost().port
        prefix = '/'
        movie_url = url.here.click('/').secure(False, port)
    else:
        movie_url = url.here
        port = lambda c, d: inevow.IRequest(c).transport.server.port

        def prefix(c, d):
            pre = inevow.IRequest(c).path
            if pre.endswith('/'):
                return pre
            return pre + '/'

    _hookup[C] = delegate
    handlerInfo = []
    for handlerName in [
            'onMouseMove', 'onMouseDown', 'onMouseUp', 'onKeyDown', 'onKeyUp'
    ]:
        if getattr(delegate, handlerName, None) is not None:
            handlerInfo.append((handlerName, 1))

    movie_url = movie_url.child('nevow_canvas_movie.swf').add('cookie', C).add(
        'port', port).add('prefix', prefix)
    for (k, v) in handlerInfo:
        movie_url = movie_url.add(k, v)

    return tags._object(
        classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000",
        codebase=
        "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0",
        width=width,
        height=height,
        id=("Canvas-", C),
        align="middle"
    )[tags.param(name="allowScriptAccess", value="sameDomain"),
      tags.param(name="movie", value=movie_url),
      tags.param(name="quality", value="high"),
      tags.param(name="scale", value="noscale"),
      tags.param(name="bgcolor", value="#ffffff"),
      Tag('embed')(src=movie_url,
                   quality="high",
                   scale="noscale",
                   bgcolor="#ffffff",
                   width=width,
                   height=height,
                   name=("Canvas-", C),
                   align="middle",
                   allowScriptAccess="sameDomain",
                   type="application/x-shockwave-flash",
                   pluginspage="http://www.macromedia.com/go/getflashplayer")]
Example #20
0
 def render_return(self, ctx, data):
     req = inevow.IRequest(ctx)
     return_to = get_arg(req, "return_to", None)
     if return_to:
         return T.div[T.a(href=return_to)["Return to file/directory."]]
     return ""
Example #21
0
 def renderHTTP(self, ctx):
     # JSON only
     inevow.IRequest(ctx).setHeader("content-type", "text/plain")
     s = self.monitor.get_status().copy()
     s["finished"] = self.monitor.is_finished()
     return json.dumps(s, indent=1)
Example #22
0
 def render_runtime(self, ctx, data):
     req = inevow.IRequest(ctx)
     runtime = time.time() - req.processing_started_timestamp
     return ctx.tag["runtime: %s seconds" % runtime]
 def log(self, ctx):
     request = inevow.IRequest(ctx)
     self.logged.append(
         ('fakeLog', request.getClientIP(), request.method,
          request.uri, request.clientproto, request.code,
          request.sentLength))
Example #24
0
 def beforeRender(self, ctx):
     inevow.IRequest(ctx).setHeader("Content-Type", "application/application+xml; charset=UTF-8")
Example #25
0
 def renderHTTP(self, ctx):
     request = inevow.IRequest(ctx)
     request.setResponseCode(503)
     request.setHeader("retry-after", "3600")
     return rend.Page.renderHTTP(self, ctx)
Example #26
0
 def child_(self, ctx):
     entry = inevow.ISession(ctx).getLoggedInRoot().loggedIn
     u = inevow.IRequest(ctx).URLPath()
     return u.child(str(entry.dn))
Example #27
0
 def renderHTTP(self, ctx):
     request = inevow.IRequest(ctx)
     request.setResponseCode(http.FORBIDDEN)
     return ("<html><head><title>Forbidden</title></head>"
             "<body><h1>Forbidden</h1>Request was forbidden.</body></html>")
Example #28
0
    def renderHTTP(self, ctx):
        request = inevow.IRequest(ctx)

        ge = request.args.get('size', [""])[0]

        if ge:
            size = 'size="%s",' % ge
        else:
            size = ""

        def outputData(fi):
            request.setHeader("content-type", "image/png")
            request.setHeader("content-length", str(len(fi)))

            return fi

        def fail(fi):
            print fi
            print "Errors"
            return "-"

        nodes = [
            '  "ME" [label="", style=invis, shapefile="/usr/local/tcs/tums/images/vulani-globe-64.png"];'
        ]
        edges = []

        dupes = []

        sgs = []

        ext = []

        ccnt = 0
        for server, mailboxes in self.sysconf.Mail.get("branchtopology",
                                                       {}).items():
            edges.append('  ME -> SVR_%s;' % server.replace('.', ''))
            sg = []
            sg.append(
                '  "SVR_%s" [label="%s", fontsize=12, labelloc="b", shapefile="/usr/local/tcs/tums/images/mail-server.png"];'
                % (server.replace('.', ''), server))
            #edges.append('  "SVR_%s"  -> "cluster_g%sA";' % (server.replace('.', ''), ccnt))
            for box in mailboxes:
                edges.append('  SVR_%s -> MBOX_%s;' % (server.replace(
                    '.', ''), sha.sha(box + server).hexdigest()))

                if box in dupes:
                    #edges.append('  "SVR_%s" -> "MBOX_%s";' % (server.replace('.', ''), sha.sha(box).hexdigest()))
                    sg.append(
                        '  "MBOX_%s" [label="%s",shape="box",style="filled",color="red"];'
                        % (sha.sha(box + server).hexdigest(), box))
                else:
                    dupes.append(box)
                    sg.append(
                        '  "MBOX_%s" [label="%s", shape="rectangle", peripheries=0];'
                        % (sha.sha(box + server).hexdigest(), box))

            sgs.append(sg)
            ccnt += 1

        subs = ""
        for i, sub in enumerate(sgs):
            subs += "subgraph \"cluster_g%sA\" {\n" % i
            subs += "\n".join(sub)
            subs += "\n}\n"

        graph = """digraph G {
            graph[rankdir="LR", %s ratio=1];
            ranksep=2;
            node[fontsize=10];
            %s
            %s
            %s
        }\n""" % (size, '\n'.join(nodes), subs, '\n'.join(edges))

        return WebUtils.processWriter("/usr/bin/fdp -Tpng",
                                      graph).addCallbacks(outputData, fail)
Example #29
0
 def childFactory(self, ctx, node):
     """Backward compatibility with previous API"""
     if node in ["equipment", "search", "complete", "past", "images"]:
         inevow.IRequest(ctx).rememberRootURL()
         return RedirectApi()
     return None
Example #30
0
def foafAgent(ctx):
    h = inevow.IRequest(ctx).getHeader('x-foaf-agent')
    assert h is not None, "no foaf agent"
    return URIRef(h)