Ejemplo n.º 1
0
def setCachingHeadersOnRequest(request, cacheOptions, getTime=time.time):
	cacheTime = cacheOptions.cacheTime
	setRawHeaders = request.responseHeaders.setRawHeaders

	timeNow = getTime()
	# Even though twisted.web sets a Date header, set one ourselves to
	# make sure that Date + cacheTime == Expires.
	setRawHeaders('date', [datetimeToString(timeNow)])

	if cacheTime != 0:
		isSecure = request.isSecure()
		if isSecure and cacheOptions.httpsCachePublic:
			privacy = 'public'
		elif not isSecure and cacheOptions.httpCachePublic:
			privacy = 'public'
		else:
			privacy = 'private'

		setRawHeaders('expires',
			[datetimeToString(timeNow + cacheOptions.cacheTime)])
		setRawHeaders('cache-control',
			['max-age=%d, %s' % (cacheOptions.cacheTime, privacy)])
	else:
		setRawHeaders('expires', ['-1'])
		setRawHeaders('cache-control', ['max-age=0, private'])
Ejemplo n.º 2
0
def setCachingHeadersOnRequest(request, cacheOptions, getTime=time.time):
    cacheTime = cacheOptions.cacheTime
    setRawHeaders = request.responseHeaders.setRawHeaders

    timeNow = getTime()
    # Even though twisted.web sets a Date header, set one ourselves to
    # make sure that Date + cacheTime == Expires.
    setRawHeaders('date', [datetimeToString(timeNow)])

    if cacheTime != 0:
        isSecure = request.isSecure()
        if isSecure and cacheOptions.httpsCachePublic:
            privacy = 'public'
        elif not isSecure and cacheOptions.httpCachePublic:
            privacy = 'public'
        else:
            privacy = 'private'

        setRawHeaders('expires',
                      [datetimeToString(timeNow + cacheOptions.cacheTime)])
        setRawHeaders('cache-control',
                      ['max-age=%d, %s' % (cacheOptions.cacheTime, privacy)])
    else:
        setRawHeaders('expires', ['-1'])
        setRawHeaders('cache-control', ['max-age=0, private'])
Ejemplo n.º 3
0
   def rmelogin(self, res, req, has):
      if res and (('__len__' in dir(res) and len(res) > 0) or res!=None ) and len(has.split(":", 1)) > 1:
         if '__len__' in dir(res):
            user=res[0]
         else:
            user=res

         rme=dmcrypt.B64AESDecrypt(str(self.core.configGet('web', 'cookie_aeskey')), user.passwd, has.split(":", 1)[1])
         if len(rme.split()) == 3:
            u, lp, p = rme.split()
            if user.username == u and user.passwd == p:
               log.info("Cookie login succeed for user "+user.username)
               try:
                  expire=http.datetimeToString(time.time() + 3600*24*365*50)
               except:
                  expire=http.datetimeToString(time.time() + 3600*24*365*10)

               req.addCookie("Domotikad_rme", has,
                  path="/", secure=True, expires=expire)

               html = self.html.replace("@PATH@", '/__login__'+req.path)
               html = html.replace("@USERNAME@", str(user.username))
               html = html.replace("@PASSWORD@", str(lp))
               html = html.replace("@CHECKED@", "checked")
               html = html.replace("@SCRIPT@", str(self.getScript(req.path)))
               html = html.replace("@THEME@", str(self.core.configGet('web', 'logintheme')))
               log.debug("login html")
               return html

      req.addCookie("Domotikad_rme", has, path="/", secure=True, expires=http.datetimeToString(time.time()))
      return self.getStandardHTML(req.path)
Ejemplo n.º 4
0
    def datagramReceived(self, datagram, address):
        # Broadcast
        try:
            cmd, headers = parse_http_response(datagram)
            _log.debug("Received %s, %s from %r" % (
                cmd,
                headers,
                address,
            ))

            if cmd[0] == 'M-SEARCH' and cmd[1] == '*':

                _log.debug("Ignore list %s ignore %s" %
                           (self.ignore_list, address not in self.ignore_list))
                # Only reply to our requests
                if SERVICE_UUID in headers[
                        'st'] and address not in self.ignore_list:

                    for k, addrs in self._services.items():
                        for addr in addrs:
                            # Only tell local about local
                            if addr[0] == "127.0.0.1" and address[
                                    0] != "127.0.0.1":
                                continue

                            response = MS_RESP[SERVICE_UUID] % (
                                '%s:%d' % addr, str(
                                    time.time()), k, datetimeToString())
                            if "cert" in self._msearches_resp[
                                    SERVICE_UUID].keys():
                                response += "CERTIFICATE: {}\r\n\r\n".format(
                                    self._msearches_resp[SERVICE_UUID]["cert"])
                            _log.debug("Sending response: %s" % repr(response))
                            delay = random.randint(0,
                                                   min(5, int(headers['mx'])))
                            reactor.callLater(delay, self.send_it, response,
                                              address)
                elif CA_SERVICE_UUID in headers['st'] and address not in self.ignore_list\
                    and self._msearches_resp[CA_SERVICE_UUID]["sign"]:
                    _log.debug("CA try to sign")
                    # Raises exception if CA don't sign the CSR
                    ca = Ca(self._msearches_resp[CA_SERVICE_UUID]["name"],
                            headers["calvin_csr"])
                    _log.debug("CA signed %s" % ca.signed_cert)
                    if ca.signed_cert:
                        response = MS_RESP[CA_SERVICE_UUID] % (
                            '%s:%d' % address, str(time.time()),
                            datetimeToString(), ca.signed_cert)
                        _log.debug("Sending response: %s" % repr(response))
                        delay = random.randint(0, min(5, int(headers['mx'])))
                        reactor.callLater(delay, self.send_it, response,
                                          address)
        except:
            _log.exception("SSDP search received, but failed handling")
    def datagramReceived(self, datagram, address):
        # Broadcast
        try:
            cmd, headers = parse_http_response(datagram)
            _log.debug("Received %s, %s from %r" % (cmd, headers, address, ))

            if cmd[0] == 'M-SEARCH' and cmd[1] == '*':

                # Only reply to our requests
                if SERVICE_UUID in headers['st']:

                    for k, v in self._services.items():
                        addr = v
                        # Ignore 0.0.0.0, use the ip we where contacted on
                        if addr[0] == "0.0.0.0":
                            addr = (address[0], addr[1])

                        response = MS_RESP % ('%s:%d' % addr, str(time.time()),
                                              k, datetimeToString())

                        delay = random.randint(0, min(5, int(headers['mx'])))
                        reactor.callLater(delay, self.send_it,
                                          response, address)
        except:
            _log.exception("Error datagram received")
Ejemplo n.º 6
0
    def render_start(self, request, method):
        ip = request.getClientIP()
        self.log('RTSPResource.render_start(): client from %s requests %s' % (
            ip, method))
        self.log('RTSPResource.render_start(): uri %r' % request.path)

        self.render_startCSeqDate(request, method)
        request.setHeader('Server', SERVER_STRING)
        request.delHeader('Content-Type')

        # tests for 3gpp
        request.setHeader('Last-Modified', http.datetimeToString())
        request.setHeader('Cache-Control', 'must-revalidate')
        #request.setHeader('x-Accept-Retransmit', 'our-revalidate')
        #request.setHeader('x-Accept-Dynamic-Rate', '1')
        #request.setHeader('Content-Base', 'rtsp://core.fluendo.com/test.3gpp')
        #request.setHeader('Via', 'RTSP/1.0 288f9c2a')

        # hacks for Real
        if 'Real' in request.received_headers.get('user-agent', ''):
            self.debug('Detected Real client, sending specific headers')
            # request.setHeader('Public', 'OPTIONS, DESCRIBE, ANNOUNCE, PLAY,
            #                   SETUP, GET_PARAMETER, SET_PARAMETER, TEARDOWN')
            # Public seems to be the same as allowed-methods, and real clients
            # seem to respect SET_PARAMETER not listed here
            request.setHeader(
                'Public',
                'OPTIONS, DESCRIBE, ANNOUNCE, PLAY, SETUP, TEARDOWN')
            # without a RealChallenge1, clients don't even go past OPTIONS
            request.setHeader('RealChallenge1',
                              '28d49444034696e1d523f2819b8dcf4c')
Ejemplo n.º 7
0
    def process(self):
        """
        Process a request.

        Find the addressed resource in this request's L{Site},
        and call L{self.render()<Request.render()>} with it.

        @see: L{Site.getResourceFor()}
        """

        # get site from channel
        self.site = self.channel.site

        # set various default headers
        self.setHeader(b'server', version)
        self.setHeader(b'date', http.datetimeToString())

        # Resource Identification
        self.prepath = []
        self.postpath = list(map(unquote, self.path[1:].split(b'/')))

        # Short-circuit for requests whose path is '*'.
        if self.path == b'*':
            self._handleStar()
            return

        try:
            resrc = self.site.getResourceFor(self)
            if resource._IEncodingResource.providedBy(resrc):
                encoder = resrc.getEncoder(self)
                if encoder is not None:
                    self._encoder = encoder
            self.render(resrc)
        except:
            self.processingFailed(failure.Failure())
Ejemplo n.º 8
0
    def renderWebSocket(self):
        """
        Render a WebSocket request.
        
        If the request is not identified with a proper WebSocket handshake, the
        connection will be closed. Otherwise, the response to the handshake is
        sent and a C{WebSocketHandler} is created to handle the request.
        """
        print 'renderWebSocket'
        check = self._checkClientHandshake()
        if check is None:
            return
        handler = check
        self.startedWriting = True
        handshake = [
            'HTTP/1.1 101 Switching Protocols',
            'Date: %s' % datetimeToString(), 'Upgrade: PTTH/1.0',
            'Connection: Upgrade'
        ]
        for header in handshake:
            self.write('%s\r\n' % header)

        self.write('\r\n')
        self.channel.setRawMode()
        self.channel._transferDecoder = WebSocketFrameDecoder(self, handler)
Ejemplo n.º 9
0
    def renderHTTP(self, ctx):
        """
                Checks the file modification time from the client against the 
                modification time on the server.  Also checks the file cache to
                see if it needs to be refreshed.
                """
        request = inevow.IRequest(ctx)
        self._check_cache()
        temp_date = request.getHeader("If-Modified-Since")
        if temp_date:
            parsed_date = parsedate_tz(temp_date)
            if parsed_date:
                client_time = mktime_tz(parsed_date)
            else:
                client_time = 0
        else:
            client_time = 0

##
## Check to see if the file has been modified since the client's mtime
##
        request.setHeader('content-type', "text/javascript")
        if self.mtime > client_time:
            ## New version available.
            request.setLastModified(self.mtime)
            stamp = datetime.now() + timedelta(365)
            request.setHeader('expires',
                              datetimeToString(mktime(stamp.timetuple())))
            request.setHeader('content-length', str(len(self.data)))
            request.setHeader('content-type', "text/javascript")
            return self.data
        else:
            request.setResponseCode(http.NOT_MODIFIED)
            return "OK"
Ejemplo n.º 10
0
 def test_unmodified(self):
     """If-Modified-Since cache validator (negative)"""
     self.channel.lineReceived("If-Modified-Since: %s" % http.datetimeToString(100))
     self.channel.lineReceived("")
     result = self.transport.getvalue()
     self.failUnlessEqual(httpCode(result), http.NOT_MODIFIED)
     self.failUnlessEqual(httpBody(result), "")
Ejemplo n.º 11
0
 def test_modified(self):
     """If-Modified-Since cache validator (positive)"""
     self.channel.lineReceived("If-Modified-Since: %s" % http.datetimeToString(1))
     self.channel.lineReceived("")
     result = self.transport.getvalue()
     self.failUnlessEqual(httpCode(result), http.OK)
     self.failUnlessEqual(httpBody(result), "correct")
Ejemplo n.º 12
0
    def process(self):
        """
        Process a request.
        """

        # get site from channel
        self.site = self.channel.site

        # set various default headers
        self.setHeader(b'server', version)
        self.setHeader(b'date', http.datetimeToString())

        # Resource Identification
        self.prepath = []
        self.postpath = list(map(unquote, self.path[1:].split(b'/')))

        try:
            resrc = self.site.getResourceFor(self)
            if resource._IEncodingResource.providedBy(resrc):
                encoder = resrc.getEncoder(self)
                if encoder is not None:
                    self._encoder = encoder
            self.render(resrc)
        except:
            self.processingFailed(failure.Failure())
Ejemplo n.º 13
0
 def processWebSocket(self):
     self.site = self.channel.site
     self.setHeader('server', version)
     self.setHeader('date', datetimeToString())
     self.prepath = []
     self.postpath = map(unquote, self.path[1:].split('/'))
     self.renderWebSocket()
Ejemplo n.º 14
0
    def discoveryRequest(self, headers, xxx_todo_changeme2):
        """Process a discovery request.  The response must be sent to
        the address specified by (host, port)."""
        (host, port) = xxx_todo_changeme2
        self.info('Discovery request from (%s,%d) for %s', host, port,
                  headers['st'])
        self.info('Discovery request for %s', headers['st'])

        louie.send('Coherence.UPnP.Log', None, 'SSDP', host,
                   'M-Search for %s' % headers['st'])

        # Do we know about this service?
        for i in list(self.known.values()):
            if i['MANIFESTATION'] == 'remote':
                continue
            if (headers['st'] == 'ssdp:all' and i['SILENT'] == True):
                continue
            if (i['ST'] == headers['st'] or headers['st'] == 'ssdp:all'):
                response = []
                response.append('HTTP/1.1 200 OK')

                for k, v in list(i.items()):
                    if k == 'USN':
                        usn = v
                    if k not in ('MANIFESTATION', 'SILENT', 'HOST'):
                        response.append('%s: %s' % (k, v))
                response.append('DATE: %s' % datetimeToString())

                response.extend(('', ''))
                delay = random.randint(0, int(headers['mx']))

                reactor.callLater(delay, self.send_it, '\r\n'.join(response),
                                  (host, port), delay, usn)
    def datagramReceived(self, datagram, address):
        # Broadcast
        try:
            cmd, headers = parse_http_response(datagram)
            _log.debug("Received %s, %s from %r" % (
                cmd,
                headers,
                address,
            ))

            if cmd[0] == 'M-SEARCH' and cmd[1] == '*':

                # Only reply to our requests
                if SERVICE_UUID in headers['st']:

                    for k, v in self._services.items():
                        addr = v
                        # Ignore 0.0.0.0, use the ip we where contacted on
                        if addr[0] == "0.0.0.0":
                            addr = (address[0], addr[1])

                        response = MS_RESP % ('%s:%d' % addr, str(
                            time.time()), k, datetimeToString())

                        delay = random.randint(0, min(5, int(headers['mx'])))
                        reactor.callLater(delay, self.send_it, response,
                                          address)
        except:
            _log.exception("Error datagram received")
Ejemplo n.º 16
0
	def renderHTTP(self, ctx):
		"""
                Checks the file modification time from the client against the 
                modification time on the server.  Also checks the file cache to
                see if it needs to be refreshed.
                """
                request = inevow.IRequest(ctx)
                self._check_cache()
                temp_date = request.getHeader("If-Modified-Since")
                if temp_date:
                        parsed_date = parsedate_tz(temp_date)
                        if parsed_date:
                                client_time = mktime_tz(parsed_date)
                        else:
                                client_time = 0
                else:
                        client_time = 0
                ##
                ## Check to see if the file has been modified since the client's mtime
                ##
                request.setHeader('content-type', "text/javascript; charset=UTF-8")
                if self.mtime > client_time:
                        ## New version available.
                        request.setLastModified(self.mtime)
			stamp = datetime.now() + timedelta(365)
			request.setHeader('expires', datetimeToString(mktime(stamp.timetuple()))) 
                        request.setHeader('content-length', str(len(self.data)))
                        request.setHeader('content-type', "text/javascript; charset=UTF-8")
                        return self.data
                else:
                        request.setResponseCode(http.NOT_MODIFIED)
                        return "OK"
Ejemplo n.º 17
0
 def __init__(self):
     self.data = [
         'HTTP/1.1 101 FYI I am not a webserver\r\n',
         'Server: MambaWebSocketWrapper/1.0\r\n',
         'Date: {}\r\n'.format(datetimeToString()),
         'Upgrade: WebSocket\r\n', 'Connection: Upgrade\r\n'
     ]
Ejemplo n.º 18
0
    def createSession(self, ctx, segments):
        """Create a new session for this request, and redirect back to the path
        given by segments."""

        request = inevow.IRequest(ctx)

        newCookie = _sessionCookie()
        if self.useCookies:
            if self.secureCookies and request.isSecure():
                secure = True
            else:
                secure = False
            if self.persistentCookies and self.sessionLifetime:
                expires = http.datetimeToString(time.time() + self.sessionLifetime)
            else:
                expires = None
            request.addCookie(self.cookieKey, newCookie,
                              path="/%s" % '/'.join(request.prepath),
                              secure=secure, expires=expires)
        sz = self.sessions[newCookie] = self.sessionFactory(self, newCookie)
        sz.args = request.args
        sz.fields = getattr(request, 'fields', {})
        sz.content = request.content
        sz.method = request.method
        sz.received_headers = request.received_headers
        sz.checkExpired()
        return urlToChild(ctx, SESSION_KEY+newCookie, *segments)
Ejemplo n.º 19
0
    def datagramReceived(self, datagram, address):
        # Broadcast
        try:
            cmd, headers = parse_http_response(datagram)
            _log.debug("Received %s, %s from %r" % (cmd, headers, address, ))

            if cmd[0] == 'M-SEARCH' and cmd[1] == '*':

                _log.debug("Ignore list %s ignore %s" % (self.ignore_list, address not in self.ignore_list))
                # Only reply to our requests
                if SERVICE_UUID in headers['st'] and address not in self.ignore_list:

                    for k, addrs in self._services.items():
                        for addr in addrs:
                            # Only tell local about local
                            if addr[0] == "127.0.0.1" and address[0] != "127.0.0.1":
                                continue

                            response = MS_RESP % ('%s:%d' % addr, str(time.time()),
                                                  k, datetimeToString())
                            _log.debug("Sending response: %s" % repr(response))
                            delay = random.randint(0, min(5, int(headers['mx'])))
                            reactor.callLater(delay, self.send_it,
                                                  response, address)
        except:
            _log.exception("Error datagram received")
Ejemplo n.º 20
0
    def render_start(self, request, method):
        ip = request.getClientIP()
        self.log('RTSPResource.render_start(): client from %s requests %s' % (
            ip, method))
        self.log('RTSPResource.render_start(): uri %r' % request.path)

        self.render_startCSeqDate(request, method)
        request.setHeader('Server', SERVER_STRING)
        request.delHeader('Content-Type')

        # tests for 3gpp
        request.setHeader('Last-Modified', http.datetimeToString())
        request.setHeader('Cache-Control', 'must-revalidate')
        #request.setHeader('x-Accept-Retransmit', 'our-revalidate')
        #request.setHeader('x-Accept-Dynamic-Rate', '1')
        #request.setHeader('Content-Base', 'rtsp://core.fluendo.com/test.3gpp')
        #request.setHeader('Via', 'RTSP/1.0 288f9c2a')

        # hacks for Real
        if 'Real' in request.received_headers.get('user-agent', ''):
            self.debug('Detected Real client, sending specific headers')
            # request.setHeader('Public', 'OPTIONS, DESCRIBE, ANNOUNCE, PLAY,
            #                   SETUP, GET_PARAMETER, SET_PARAMETER, TEARDOWN')
            # Public seems to be the same as allowed-methods, and real clients
            # seem to respect SET_PARAMETER not listed here
            request.setHeader(
                'Public',
                'OPTIONS, DESCRIBE, ANNOUNCE, PLAY, SETUP, TEARDOWN')
            # without a RealChallenge1, clients don't even go past OPTIONS
            request.setHeader('RealChallenge1',
                              '28d49444034696e1d523f2819b8dcf4c')
Ejemplo n.º 21
0
Archivo: web.py Proyecto: gwylim/bravo
    def _cb_render_GET(self, chunk, request):
        # If the request finished already, then don't even bother preparing
        # the image.
        if request._disconnected:
            return

        request.setHeader('content-type', 'image/png')
        i = Image.new("RGB", (16, 16))
        pbo = i.load()
        for x, z in product(xrange(16), repeat=2):
            y = chunk.height_at(x, z)
            block = chunk.blocks[x, z, y]
            if block in block_colors:
                color = block_colors[block]
                if isinstance(color, tuple):
                    # Switch colors depending on height.
                    color = color[y / 5 % len(color)]
            else:
                color = default_color
            pbo[x, z] = names_to_colors[color]

        data = StringIO()
        i.save(data, "PNG")
        # cache image for 5 minutes
        request.setHeader("Cache-Control", "public, max-age=360")
        request.setHeader("Expires", datetimeToString(time.time() + 360))
        request.write(data.getvalue())
        request.finish()
Ejemplo n.º 22
0
 def test_too_old_request(self):
     agent = authhmac.AuthHMACAgent(self.agent, "key", "secret")
     headers = Headers({'date': [datetimeToString(time.time() - 1500)]})
     bodyp = web.StringBodyProducer("some content")
     resp = yield agent.request('POST', self.request_url(""), headers,
                                bodyp)
     yield self.check_fail(resp)
Ejemplo n.º 23
0
 def process(self):
     "Process a request."
     # get site from channel
     self.site = self.channel.site
     # set various default headers
     self.setHeader('server', SERVER_ID)
     self.setHeader('date', http.datetimeToString())
     self.setHeader('content-type', "text/html")
     # Resource Identification
     url = self.path
     #remove trailing "/", if ever
     url = url.rstrip('/')
     _scheme, _netloc, path, _query, _fragment = urlsplit(url)
     self.prepath = []
     if path == "":
         self.postpath = []
     else:
         self.postpath = map(unquote, path[1:].split('/'))
     try:
         def deferred_rendering(r):
             self.render(r)
         resrc = self.site.getResourceFor(self)
         if resrc is None:
             self.setResponseCode(http.NOT_FOUND, "Error: No resource for path %s" % path)
             self.finish()
         elif isinstance(resrc, defer.Deferred):
             resrc.addCallback(deferred_rendering)
             resrc.addErrback(self.processingFailed)
         else:
             self.render(resrc)
     except:
         self.processingFailed(failure.Failure())
Ejemplo n.º 24
0
 def render(self, request: IRequest) -> bytes:
     # File expires a long time from now.
     # RFC-2616 section 14.21: "HTTP/1.1 servers SHOULD NOT send Expires
     # dates more than one year in the future."
     request.setHeader('expires',
                       datetimeToString(getTime() + 365 * secondsPerDay))
     return super().render(request)
Ejemplo n.º 25
0
    def _cb_render_GET(self, chunk, request):
        # If the request finished already, then don't even bother preparing
        # the image.
        if request._disconnected:
            return

        request.setHeader('content-type', 'image/png')
        i = Image.new("RGB", (16, 16))
        pbo = i.load()
        for x, z in XZ:
            y = chunk.height_at(x, z)
            block = chunk.blocks[x, z, y]
            if block in block_colors:
                color = block_colors[block]
                if isinstance(color, tuple):
                    # Switch colors depending on height.
                    color = color[y / 5 % len(color)]
            else:
                color = default_color
            pbo[x, z] = names_to_colors[color]

        data = StringIO()
        i.save(data, "PNG")
        # cache image for 5 minutes
        request.setHeader("Cache-Control", "public, max-age=360")
        request.setHeader("Expires", datetimeToString(time.time() + 360))
        request.write(data.getvalue())
        request.finish()
Ejemplo n.º 26
0
 def render_startCSeqDate(self, request, method):
     cseq = request.getHeader('CSeq')
     if cseq == None:
         cseq = 0
     request.setHeader('CSeq', cseq)
     request.setHeader('Date', http.datetimeToString())
     return
Ejemplo n.º 27
0
    def process(self):
        """
        Process a request.
        """

        # get site from channel
        self.site = self.channel.site

        # set various default headers
        self.setHeader(b'server', version)
        self.setHeader(b'date', http.datetimeToString())

        # Resource Identification
        self.prepath = []
        self.postpath = list(map(unquote, self.path[1:].split(b'/')))

        try:
            resrc = self.site.getResourceFor(self)
            if resource._IEncodingResource.providedBy(resrc):
                encoder = resrc.getEncoder(self)
                if encoder is not None:
                    self._encoder = encoder
            self.render(resrc)
        except:
            self.processingFailed(failure.Failure())
Ejemplo n.º 28
0
    def process(self):
        "Process a request."

        # get site from channel
        self.site = self.channel.site

        # set various default headers
        self.setHeader('server', SERVER_ID)
        self.setHeader('date', http.datetimeToString())
        self.setHeader('content-type', "text/html")

        # Resource Identification
        self.prepath = []
        self.postpath = map(unquote, self.path[1:].split('/'))
        try:
            def deferred_rendering(r):
                self.render(r)

            resrc = self.site.getResourceFor(self)
            if isinstance(resrc, defer.Deferred):
                resrc.addCallback(deferred_rendering)
                resrc.addErrback(self.processingFailed)
            else:
                self.render(resrc)
        except:
            self.processingFailed(failure.Failure())
Ejemplo n.º 29
0
    def createSession(self, ctx, segments):
        """
        Create a new session for this request, and redirect back to the path
        given by segments.
        """

        request = inevow.IRequest(ctx)

        newCookie = _sessionCookie()
        if self.useCookies:
            if self.secureCookies and request.isSecure():
                secure = True
            else:
                secure = False
            if self.persistentCookies and self.sessionLifetime:
                expires = http.datetimeToString(time.time() +
                                                self.sessionLifetime)
            else:
                expires = None
            request.addCookie(self.cookieKey,
                              newCookie,
                              path="/%s" % '/'.join(request.prepath),
                              secure=secure,
                              expires=expires,
                              domain=self.cookieDomainForRequest(request))
        sz = self.sessions[newCookie] = self.sessionFactory(self, newCookie)
        sz.args = request.args
        sz.fields = request.fields
        sz.method = request.method
        sz.received_headers = request.received_headers
        sz.checkExpired()
        return urlToChild(ctx, SESSION_KEY + newCookie, *segments)
Ejemplo n.º 30
0
 def _setRequestHeaders(self, request):
     content = self.streamer.get_content_type()
     request.setHeader('Server', HTTP_SERVER)
     request.setHeader('Date', http.datetimeToString())
     request.setHeader('Connection', 'close')
     request.setHeader('Cache-Control', 'no-cache')
     request.setHeader('Cache-Control', 'private')
     request.setHeader('Content-type', content)
Ejemplo n.º 31
0
 def _setRequestHeaders(self, request, content=None, allow_cache=False):
     content = content or self.streamer.get_content_type()
     request.setHeader('Server', self.HTTP_SERVER)
     request.setHeader('Date', http.datetimeToString())
     if not allow_cache:
         request.setHeader('Cache-Control', 'no-cache')
         request.setHeader('Cache-Control', 'private')
     request.setHeader('Content-type', content)
Ejemplo n.º 32
0
 def __init__(self):
     self.data = [
         'HTTP/1.1 101 FYI I am not a webserver\r\n',
         'Server: MambaWebSocketWrapper/1.0\r\n',
         'Date: {}\r\n'.format(datetimeToString()),
         'Upgrade: WebSocket\r\n',
         'Connection: Upgrade\r\n'
     ]
Ejemplo n.º 33
0
 def test_modified(self):
     """
     If a request is made with an I{If-Modified-Since} header value with
     a timestamp indicating a time before the last modification of the
     requested resource, a 200 response is returned along with a response
     body containing the resource.
     """
     self._modifiedTest(modifiedSince=http.datetimeToString(1))
Ejemplo n.º 34
0
 def test_modified(self):
     """If-Modified-Since cache validator (positive)"""
     self.channel.lineReceived("If-Modified-Since: %s" %
                               http.datetimeToString(1))
     self.channel.lineReceived('')
     result = self.transport.getvalue()
     self.failUnlessEqual(httpCode(result), http.OK)
     self.failUnlessEqual(httpBody(result), "correct")
Ejemplo n.º 35
0
 def _setRequestHeaders(self, request, content=None, allow_cache=False):
     content = content or self.streamer.get_content_type()
     request.setHeader('Server', self.HTTP_SERVER)
     request.setHeader('Date', http.datetimeToString())
     if not allow_cache:
         request.setHeader('Cache-Control', 'no-cache')
         request.setHeader('Cache-Control', 'private')
     request.setHeader('Content-type', content)
Ejemplo n.º 36
0
 def test_unmodified(self):
     """If-Modified-Since cache validator (negative)"""
     self.channel.lineReceived("If-Modified-Since: %s" %
                               http.datetimeToString(100))
     self.channel.lineReceived('')
     result = self.transport.getvalue()
     self.failUnlessEqual(httpCode(result), http.NOT_MODIFIED)
     self.failUnlessEqual(httpBody(result), "")
Ejemplo n.º 37
0
 def test_modified(self):
     """
     If a request is made with an I{If-Modified-Since} header value with
     a timestamp indicating a time before the last modification of the
     requested resource, a 200 response is returned along with a response
     body containing the resource.
     """
     self._modifiedTest(modifiedSince=http.datetimeToString(1))
Ejemplo n.º 38
0
    def render_GET(self, request):
        if self._cache_timeout is not None:
            request.setHeader(b'cache-control',
                              'max-age={}, public'.format(self._cache_timeout))
            request.setHeader(
                b'expires',
                http.datetimeToString(time.time() + self._cache_timeout))

        return File.render_GET(self, request)
Ejemplo n.º 39
0
def rememberEmail(ctx, address):
    remembered = IEmailAddress(ctx)
    if remembered != address:
        request = inevow.IRequest(ctx)
        expires = http.datetimeToString(time.time() + 60*60*24*365)
        request.addCookie(COOKIE_KEY, address,
                          path="/", #TODO path="/%s" % '/'.join(request.prepath),
                          ##TODO secure=False,
                          expires=expires)
Ejemplo n.º 40
0
 def renderHTTP(self, ctx):
     request = inevow.IRequest(ctx)
     request.setHeader("content-type", self.type)
     request.setHeader("content-length", str(len(self.data)))
     if self.expires is not None:
         request.setHeader("expires",
                           http.datetimeToString(self.time() + self.expires))
     if request.method == "HEAD":
         return ''
     return self.data
Ejemplo n.º 41
0
 def renderHTTP(self, ctx):
     request = inevow.IRequest(ctx)
     request.setHeader("content-type", self.type)
     request.setHeader("content-length", str(len(self.data)))
     if self.expires is not None:
         request.setHeader(
             "expires", http.datetimeToString(self.time() + self.expires))
     if request.method == "HEAD":
         return ''
     return self.data
Ejemplo n.º 42
0
   def locateChild(self, ctx, name):
      request = inevow.IRequest(ctx)
      if not self.mind.loginsaved:
         log.debug("LocateChild in RootAuthPage Ming Args: "+str(self.mind.args))
         self.mind.loginsaved = True
         self.mind.perms = self.perms
         if 'rememberMe' in self.mind.args:
            log.debug("Setting rememberMe cookie for avatar "+str(self.avatarId))
            #session = inevow.ISession(ctx)
            rme=dmcrypt.B64AESEncrypt(str(self.core.configGet('web', 'cookie_aeskey')), self.perms.passwd, 
                                       " ".join([self.perms.username, self.perms.loginpwd, self.perms.passwd]))
            try:
               expire=http.datetimeToString(time.time() + 3600*24*365*50)
            except:
               expire=http.datetimeToString(time.time() + 3600*24*365*10)

            request.addCookie("Domotikad_rme", str(self.perms.id)+':'+rme, 
               path="/", secure=True, expires=expire)
      return RootPage.locateChild(self, ctx, name)
Ejemplo n.º 43
0
 def render_startCSeqDate(self, request, method):
     """
     Set CSeq and Date on response to given request.
     This should be done even for errors.
     """
     cseq = request.getHeader('CSeq')
     if cseq == None:
         cseq = 0
     request.setHeader('CSeq', cseq)
     request.setHeader('Date', http.datetimeToString())
Ejemplo n.º 44
0
 def add_cookie(self, name, payload, expires=None, max_age=None, domain=None, path=None, secure=None):
     self._check_header_not_sent()
     if expires:
         utctimestamp = time.mktime(expires.utctimetuple())
         expires = twhttp.datetimeToString(utctimestamp)
     if max_age:
         max_age = max_age.days * 24 * 60 * 60 + max_age.seconds
     self._request._ref.addCookie(
         name, payload, expires=expires, domain=domain, path=path, max_age=max_age, comment=None, secure=secure
     )
Ejemplo n.º 45
0
 def processWebSocket(self):
     """
     Process a specific web socket request.
     """
     self.site = self.channel.site
     self.setHeader('server', version)
     self.setHeader('date', datetimeToString())
     self.prepath = []
     self.postpath = map(unquote, self.path[1:].split('/'))
     self.renderWebSocket()
Ejemplo n.º 46
0
 def renderHTTP(self, ctx):
    request = inevow.IRequest(ctx)
    rmec=request.getCookie("Domotikad_rme")
    # XXX Come si fa a capire SE esiste? ritorna davvero None?
    if rmec:
       request.addCookie("Domotikad_rme", str(rmec), path="/", secure=True,
          expires=http.datetimeToString(time.time()))
    request.setHeader('Location', self.locpath)
    request.setResponseCode(302)
    log.debug("SPECIAL LOGOUT "+self.locpath)
    return 'Logging out...'
Ejemplo n.º 47
0
	def renderHTTP(self, ctx):
                request = inevow.IRequest(ctx)
		request.setHeader('content-type', "text/javascript; charset=UTF-8")
		if request.getHeader("If-Modified-Since"):
			request.setResponseCode(http.NOT_MODIFIED)
			return "OK"
		else:
			stamp = datetime.now() + timedelta(365)
			request.setHeader('expires', datetimeToString(mktime(stamp.timetuple())))
			request.setHeader('content-length', str(len(self.full_js)))
			return self.full_js
Ejemplo n.º 48
0
    def render_GET(self, request):
        if self._cache_timeout is not None:
            request.setHeader(b'cache-control', u'max-age={}, public'.format(self._cache_timeout).encode('utf8'))
            request.setHeader(b'expires', http.datetimeToString(time.time() + self._cache_timeout))

        # set response headers for cross-origin requests
        #
        if self._allow_cross_origin:
            set_cross_origin_headers(request)

        return File.render_GET(self, request)
Ejemplo n.º 49
0
    def _check_download_condition(self, request, info, media_stat,
                                  last_modified):
        head_request = request.replace(method='HEAD')
        head_request.meta['media_stat'] = media_stat
        head_request.meta['media_last_modified'] = last_modified
        head_request.headers['If-Modified-Since'] = \
            http.datetimeToString(last_modified)

        dfd = self.crawler.engine.download(head_request, info.spider)
        dfd.addBoth(self._handle_download_head, head_request, info)
        return dfd
Ejemplo n.º 50
0
    def render_GET(self, request):
        if self._cache_timeout is not None:
            request.setHeader(b'cache-control', u'max-age={}, public'.format(self._cache_timeout).encode('utf8'))
            request.setHeader(b'expires', http.datetimeToString(time.time() + self._cache_timeout))

        # set response headers for cross-origin requests
        #
        if self._allow_cross_origin:
            set_cross_origin_headers(request)

        return File.render_GET(self, request)
Ejemplo n.º 51
0
    def test_websocket_protocol(self):

        self.port.dataReceived(data)
        self.assertEqual(
            self.tr.value(), 'HTTP/1.1 101 FYI I am not a webserver\r\n'
            'Server: MambaWebSocketWrapper/1.0\r\n'
            'Date: {}\r\n'
            'Upgrade: WebSocket\r\n'
            'Connection: Upgrade\r\n'
            'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo='
            '\r\n\r\n'.format(datetimeToString()))
Ejemplo n.º 52
0
    def datagramReceived(self, datagram, address):
        # Broadcast
        try:
            cmd, headers = parse_http_response(datagram)
            _log.debug("Received %s, %s from %r" % (cmd, headers, address, ))

            if cmd[0] == 'M-SEARCH' and cmd[1] == '*':

                _log.debug("Ignore list %s ignore %s" % (self.ignore_list, address not in self.ignore_list))
                # Only reply to our requests
                if SERVICE_UUID in headers['st'] and address not in self.ignore_list:

                    for k, addrs in self._services.items():
                        for addr in addrs:
                            # Only tell local about local
                            if addr[0] == "127.0.0.1" and address[0] != "127.0.0.1":
                                continue

                            response = MS_RESP[SERVICE_UUID] % ('%s:%d' % addr, str(time.time()),
                                                  k, datetimeToString())
                            if "cert" in self._msearches_resp[SERVICE_UUID].keys():
                                response += "CERTIFICATE: {}\r\n\r\n".format(self._msearches_resp[SERVICE_UUID]["cert"])
                            _log.debug("Sending response: %s" % repr(response))
                            delay = random.randint(0, min(5, int(headers['mx'])))
                            reactor.callLater(delay, self.send_it,
                                                  response, address)
                elif CA_SERVICE_UUID in headers['st'] and address not in self.ignore_list\
                    and self._msearches_resp[CA_SERVICE_UUID]["sign"]:
                    _log.debug("CA try to sign")
                    # Raises exception if CA don't sign the CSR
                    ca = Ca(self._msearches_resp[CA_SERVICE_UUID]["name"], headers["calvin_csr"])
                    _log.debug("CA signed %s" % ca.signed_cert)
                    if ca.signed_cert:
                        response = MS_RESP[CA_SERVICE_UUID] % ('%s:%d' % address, str(time.time()),
                                              datetimeToString(), ca.signed_cert)
                        _log.debug("Sending response: %s" % repr(response))
                        delay = random.randint(0, min(5, int(headers['mx'])))
                        reactor.callLater(delay, self.send_it,
                                              response, address)
        except:
            _log.exception("SSDP search received, but failed handling")
Ejemplo n.º 53
0
 def createTestCases(respFormat,
                     levels,
                     ifModifiedSince,
                     contentType=None,
                     dataFile=None,
                     retCode=200,
                     respHeaders=None,
                     **kwargs):
     return [(qs, contentType, retCode, {
         'If-Modified-Since': datetimeToString(ifModifiedSince)
     }, respHeaders, dataFile)
             for qs in createQueryStrings(respFormat, levels, **kwargs)]
Ejemplo n.º 54
0
 def __init__(self, bucket=None, object_name=None, data="",
              content_type=None, metadata={}, *args, **kwargs):
     super(Query, self).__init__(*args, **kwargs)
     self.bucket = bucket
     self.object_name = object_name
     self.data = data
     self.content_type = content_type
     self.metadata = metadata
     self.date = datetimeToString()
     if not self.endpoint or not self.endpoint.host:
         self.endpoint = AWSServiceEndpoint(S3_ENDPOINT)
     self.endpoint.set_method(self.action)
Ejemplo n.º 55
0
 def renderHTTP(self, ctx):
     request = inevow.IRequest(ctx)
     request.setHeader('content-type', "text/javascript")
     if request.getHeader("If-Modified-Since"):
         request.setResponseCode(http.NOT_MODIFIED)
         return "OK"
     else:
         stamp = datetime.now() + timedelta(365)
         request.setHeader('expires',
                           datetimeToString(mktime(stamp.timetuple())))
         request.setHeader('content-length', str(len(self.full_js)))
         return self.full_js
Ejemplo n.º 56
0
 def test_unmodified(self):
     """
     If a request is made with an I{If-Modified-Since} header value with
     a timestamp indicating a time after the last modification of the
     request resource, a 304 response is returned along with an empty
     response body.
     """
     self.channel.lineReceived("If-Modified-Since: %s"
                               % http.datetimeToString(100))
     self.channel.lineReceived('')
     result = self.transport.getvalue()
     self.failUnlessEqual(httpCode(result), http.NOT_MODIFIED)
     self.failUnlessEqual(httpBody(result), "")
Ejemplo n.º 57
0
 def render_start(self, request, method):
     ip = request.getClientIP()
     print 'RTSPResource.render_start(): client from %s requests %s' % (ip, method)
     print 'RTSPResource.render_start(): uri %r' % request.path
     self.render_startCSeqDate(request, method)
     request.setHeader('Server', SERVER_STRING)
     request.delHeader('Content-Type')
     request.setHeader('Last-Modified', http.datetimeToString())
     request.setHeader('Cache-Control', 'must-revalidate')
     if 'Real' in request.received_headers.get('user-agent', ''):
         print 'Detected Real client, sending specific headers'
         request.setHeader('Public', 'OPTIONS, DESCRIBE, ANNOUNCE, PLAY, SETUP, TEARDOWN')
         request.setHeader('RealChallenge1', '28d49444034696e1d523f2819b8dcf4c')