[Zope-CVS] CVS: Products/Sessions - BrowserIdManager.py:1.1 LowConflictConnection.py:1.1 RAM_DB.py:1.1 SessionDataManager.py:1.1 SessionPermissions.py:1.1 SessionStorage.py:1.1 common.py:1.1 mountfail.dtml:1.1 SessionInterfaces.py:1.2

Chris McDonough chrism@zope.com
Wed, 31 Oct 2001 10:36:05 -0500


Update of /cvs-repository/Products/Sessions
In directory cvs.zope.org:/tmp/cvs-serv4229

Modified Files:
	SessionInterfaces.py 
Added Files:
	BrowserIdManager.py LowConflictConnection.py RAM_DB.py 
	SessionDataManager.py SessionPermissions.py SessionStorage.py 
	common.py mountfail.dtml 
Log Message:
Checkpoint checkin so Matt can take over.


=== Added File Products/Sessions/BrowserIdManager.py ===
__version__='$Revision: 1.1 $'[11:-2]
import Globals
from Persistence import Persistent
from ZODB import TimeStamp
from Acquisition import Implicit
from AccessControl.Owned import Owned
from AccessControl.Role import RoleManager
from App.Management import Tabs
from OFS.SimpleItem import Item
from OFS.ObjectManager import UNIQUE
from AccessControl import ClassSecurityInfo
import SessionInterfaces
from SessionPermissions import *
from common import DEBUG
import os, time, random, string, binascii, sys, re

b64_trans = string.maketrans('+/', '-.')
b64_untrans = string.maketrans('-.', '+/')

badtokenkeycharsin = re.compile('[\?&;, ]').search
badcookiecharsin = re.compile('[;, ]').search
twodotsin = re.compile('(\w*\.){2,}').search

_marker = []

constructBrowserIdManagerForm = Globals.DTMLFile('addIdManager',globals())

def constructBrowserIdManager(
    self, id, title='', tokenkey='_ZopeId', cookiepri=1, formpri=2,
    urlpri=0, cookiepath='/', cookiedomain='', cookielifedays=0,
    cookiesecure=0, REQUEST=None
    ):
    """ """
    # flip dictionary and take what's not 0 (god I hate HTML)
    d = {}
    for k,v in {'url':urlpri, 'form':formpri, 'cookies':cookiepri}.items():
        if v: d[v] = k
    ob = BrowserIdManager(id, title, tokenkey, d, cookiepath,
                          cookiedomain, cookielifedays, cookiesecure)
    self._setObject(id, ob)
    ob = self._getOb(id)
    if REQUEST is not None:
        return self.manage_main(self, REQUEST, update_menu=1)
    
class BrowserIdManagerErr(Exception): pass
    
class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
    """ browser id management class """

    meta_type = 'Browser Id Manager'

    manage_options=(
        {'label': 'Settings',
         'action':'manage_browseridmgr',
         },
        {'label': 'Security', 'action':'manage_access'},
        {'label': 'Ownership', 'action':'manage_owner'}
        )

    security = ClassSecurityInfo()
    security.setDefaultAccess('deny')
    security.setPermissionDefault(MGMT_SCREEN_PERM, ['Manager'])
    security.setPermissionDefault(ACCESS_CONTENTS_PERM,['Manager','Anonymous'])
    security.setPermissionDefault(CHANGE_IDMGR_PERM, ['Manager'])

    __replaceable__ = UNIQUE # singleton for now

    __implements__ = (SessionInterfaces.BrowserIdManagerInterface, )

    icon = 'misc_/Sessions/idmgr.gif'

    def __init__(
        self, id, title='', tokenkey='_ZopeId',
        tokenkeynamespaces={1:'cookies',2:'form'}, cookiepath=('/'),
        cookiedomain='', cookielifedays=0, cookiesecure=0, on=1
        ):

        self.id = id
        self.title = title
        self.setTokenKey(tokenkey)
        self.setTokenKeyNamespaces(tokenkeynamespaces)
        self.setCookiePath(cookiepath)
        self.setCookieDomain(cookiedomain)
        self.setCookieLifeDays(cookielifedays)
        self.setCookieSecure(cookiesecure)
        if on:
            self.turnOn()
        else:
            self.turnOff()

    # delegating methods follow
    # don't forget to change the name of the method in
    # delegation if you change a delegating method name

    security.declareProtected(ACCESS_CONTENTS_PERM, 'hasToken')
    def hasToken(self):
        """ Returns true if there is a current browser token, but does
        not create a browser token for the current request if one doesn't
        already exist """
        if not self.on:
            return self._delegateToParent('hasToken')
        if self.getToken(create=0): return 1
                
    security.declareProtected(ACCESS_CONTENTS_PERM, 'getToken')
    def getToken(self, create=1):
        """
        Examines the request and hands back browser token value or
        None if no token exists.  If there is no browser token
        and if 'create' is true, create one.  If cookies are are
        an allowable id key namespace and create is true, set one.  Stuff
        the token and the namespace it was found in into the REQUEST object
        for further reference during this request.  Delegate this call to
        a parent if we're turned off.
        """
        if not self.on:
            return self._delegateToParent('getToken', create)
        REQUEST = self.REQUEST
        # let's see if token has already been attached to request
        token = getattr(REQUEST, 'browser_token_', None)
        if token is not None:
            # it's already set in this request so we can just return it
            # if it's well-formed
            if not self._isAWellFormedToken(token):
                # somebody screwed with the REQUEST instance during
                # this request.
                raise BrowserIdManagerErr, (
                    'Ill-formed token in REQUEST.browser_token_:  %s' % token
                    )
            return token
        # fall through & ck id key namespaces if token is not in request.
        tk = self.token_key
        ns = self.token_key_namespaces
        for name in ns:
            token = getattr(REQUEST, name).get(tk, None)
            if token is not None:
                # hey, we got a token!
                if self._isAWellFormedToken(token):
                    # token is not "plain old broken"
                    REQUEST.browser_token_ = token
                    REQUEST.browser_token_ns_ = name
                    return token
        # fall through if token is invalid or not in key namespaces
        if create:
            # create a brand new token
            token = self._getNewToken()
            if 'cookies' in ns:
                self._setCookie(token, REQUEST)
            REQUEST.browser_token_ = token
            REQUEST.browser_token_ns_ = None
            return token
        # implies a return of None if:
        # (not create=1) and (invalid or ((not in req) and (not in ns)))

    security.declareProtected(ACCESS_CONTENTS_PERM, 'flushTokenCookie')
    def flushTokenCookie(self):
        """ removes the token cookie from the client browser """
        if not self.on:
            return self._delegateToParent('flushToken')
        if 'cookies' not in self.token_key_namespaces:
            raise BrowserIdManagerErr,('Cookies are not now being used as a '
                                       'browser token key namespace, thus '
                                       'the token cookie cannot be flushed.')
        self._setCookie('deleted', self.REQUEST, remove=1)

    security.declareProtected(ACCESS_CONTENTS_PERM, 'isTokenFromCookie')
    def isTokenFromCookie(self):
        """ returns true if browser token is from REQUEST.cookies """
        if not self.on:
            return self._delegateToParent('isTokenFromCookie')
        if not self.getToken(): # make sure the token is stuck on REQUEST
            raise BrowserIdManagerErr, 'There is no current browser token.'
        if getattr(self.REQUEST, 'browser_token_ns_') == 'cookies':
            return 1

    security.declareProtected(ACCESS_CONTENTS_PERM, 'isTokenFromForm')
    def isTokenFromForm(self):
        """ returns true if browser token is from REQUEST.form """
        if not self.on:
            return self._delegateToParent('isTokenFromForm')
        if not self.getToken(): # make sure the token is stuck on REQUEST
            raise BrowserIdManagerErr, 'There is no current browser token.'
        if getattr(self.REQUEST, 'browser_token_ns_') == 'form':
            return 1

    security.declareProtected(ACCESS_CONTENTS_PERM, 'isTokenNew')
    def isTokenNew(self):
        """
        returns true if browser token is 'new', meaning the token exists
        but it has not yet been acknowledged by the client (the client
        hasn't sent it back to us in a cookie or in a formvar).
        """
        if not self.on:
            return self._delegateToParent('isTokenNew')
        if not self.getToken(): # make sure the token is stuck on REQUEST
            raise BrowserIdManagerErr, 'There is no current browser token.'
        # ns will be None if new, negating None below returns 1, which
        # would indicate that it's new on this request
        return not getattr(self.REQUEST, 'browser_token_ns_')
    
    security.declareProtected(ACCESS_CONTENTS_PERM, 'encodeUrl')
    def encodeUrl(self, url, create=1):
        """
        encode a URL with the browser key as a postfixed query string
        element
        """
        if not self.on:
            return self._delegateToParent('encodeUrl', url)
        token = self.getToken(create)
        if token is None:
            raise BrowserIdManagerErr, 'There is no current browser token.'
        key = self.getTokenKey()
        if '?' in url:
            return '%s&%s=%s' % (url, key, token)
        else:
            return '%s?%s=%s' % (url, key, token)

    # non-delegating methods follow

    security.declareProtected(MGMT_SCREEN_PERM, 'manage_browseridmgr')
    manage_browseridmgr = Globals.DTMLFile('manageIdManager', globals())

    security.declareProtected(CHANGE_IDMGR_PERM,
                              'manage_changeBrowserIdManager')
    def manage_changeBrowserIdManager(
        self, title='', tokenkey='_ZopeId', cookiepri=1, formpri=2,
        cookiepath='/', cookiedomain='', cookielifedays=0, cookiesecure=0,
        on=0, REQUEST=None
        ):
        """ """
        d = {}
        for k,v in {'cookies':cookiepri, 'form':formpri}.items():
            if v: d[v] = k # I hate HTML
        self.title = title
        self.setTokenKey(tokenkey)
        self.setTokenKeyNamespaces(d)
        self.setCookiePath(cookiepath)
        self.setCookieDomain(cookiedomain)
        self.setCookieLifeDays(cookielifedays)
        self.setCookieSecure(cookiesecure)
        if on:
            self.turnOn()
        else:
            self.turnOff()
        if REQUEST is not None:
            return self.manage_browseridmgr(self, REQUEST)

    security.declareProtected(CHANGE_IDMGR_PERM, 'setTokenKey')
    def setTokenKey(self, k):
        """ sets browser token key string """
        if not (type(k) is type('') and k and not badtokenkeycharsin(k)):
            raise BrowserIdManagerErr, 'Bad id key string %s' % repr(k)
        self.token_key = k

    security.declareProtected(ACCESS_CONTENTS_PERM, 'getTokenKey')
    def getTokenKey(self):
        """ """
        return self.token_key

    security.declareProtected(CHANGE_IDMGR_PERM, 'setTokenKeyNamespaces')
    def setTokenKeyNamespaces(self,namespacesd={1:'cookies',2:'form'}):
        """
        accepts dictionary e.g. {1: 'cookies', 2: 'form'} as token
        id key allowable namespaces and lookup ordering priority
        where key is 'priority' with 1 being highest.
        """
        allowed = self.getAllTokenKeyNamespaces()
        for name in namespacesd.values():
            if name not in allowed:
                raise BrowserIdManagerErr, (
                    'Bad id key namespace %s' % repr(name)
                    )
        self.token_key_namespaces = []
        nskeys = namespacesd.keys()
        nskeys.sort()
        for priority in nskeys:
            self.token_key_namespaces.append(namespacesd[priority])

    security.declareProtected(ACCESS_CONTENTS_PERM, 'getTokenKeyNamespaces')
    def getTokenKeyNamespaces(self):
        """ """
        d = {}
        i = 1
        for name in self.token_key_namespaces:
            d[i] = name
            i = i + 1
        return d

    security.declareProtected(CHANGE_IDMGR_PERM, 'setCookiePath')
    def setCookiePath(self, path=''):
        """ sets cookie 'path' element for id cookie """
        if not (type(path) is type('') and not badcookiecharsin(path)):
            raise BrowserIdManagerErr, 'Bad cookie path %s' % repr(path)
        self.cookie_path = path
    
    security.declareProtected(ACCESS_CONTENTS_PERM, 'getCookiePath')
    def getCookiePath(self):
        """ """
        return self.cookie_path

    security.declareProtected(CHANGE_IDMGR_PERM, 'setCookieLifeDays')
    def setCookieLifeDays(self, days):
        """ offset for id cookie 'expires' element """
        if type(days) not in (type(1), type(1.0)):
            raise BrowserIdManagerErr,(
                'Bad cookie lifetime in days %s (requires integer value)'
                % repr(days)
                )
        self.cookie_life_days = int(days)

    security.declareProtected(ACCESS_CONTENTS_PERM, 'getCookieLifeDays')
    def getCookieLifeDays(self):
        """ """
        return self.cookie_life_days

    security.declareProtected(CHANGE_IDMGR_PERM, 'setCookieDomain')
    def setCookieDomain(self, domain):
        """ sets cookie 'domain' element for id cookie """
        if type(domain) is not type(''):
            raise BrowserIdManagerErr, (
                'Cookie domain must be string: %s' % repr(domain)
                )
        if not domain:
            self.cookie_domain = ''
            return
        if not twodotsin(domain):
            raise BrowserIdManagerErr, (
                'Cookie domain must contain at least two dots (e.g. '
                '".zope.org" or "www.zope.org") or it must be left blank. : '
                '%s' % `domain`
                )
        if badcookiecharsin(domain):
            raise BrowserIdManagerErr, (
                'Bad characters in cookie domain %s' % `domain`
                )
        self.cookie_domain = domain

    security.declareProtected(ACCESS_CONTENTS_PERM, 'getCookieDomain')
    def getCookieDomain(self):
        """ """
        return self.cookie_domain

    security.declareProtected(CHANGE_IDMGR_PERM, 'setCookieSecure')
    def setCookieSecure(self, secure):
        """ sets cookie 'secure' element for id cookie """
        self.cookie_secure = not not secure

    security.declareProtected(ACCESS_CONTENTS_PERM, 'getCookieSecure')
    def getCookieSecure(self):
        """ """
        return self.cookie_secure

    security.declareProtected(ACCESS_CONTENTS_PERM, 'getAllTokenKeyNamespaces')
    def getAllTokenKeyNamespaces(self):
        """
        These are the REQUEST namespaces searched when looking for an
        id key value.
        """
        return ('form', 'cookies')

    security.declareProtected(CHANGE_IDMGR_PERM, 'turnOn')
    def turnOn(self):
        """ """
        self.on = 1

    security.declareProtected(CHANGE_IDMGR_PERM, 'turnOff')
    def turnOff(self):
        """ """
        self.on = 0

    security.declareProtected(ACCESS_CONTENTS_PERM, 'isOn')
    def isOn(self):
        """ """
        return self.on

    # non-interface methods follow

    def _getNewToken(self, randint=random.randint, maxint=99999999):
        """ Returns 19-character string browser token
        'AAAAAAAABBBBBBBB'
        where:

        A == leading-0-padded 8-char string-rep'd random integer
        B == modified base64-encoded 11-char timestamp
        
        To be URL-compatible, base64 encoding is modified as follows:
          '=' end-padding is stripped off
          '+' is translated to '-'
          '/' is translated to '.'
        """
        return '%08i%s' % (randint(0, maxint-1), self._getB64TStamp())
    
    def _delegateToParent(self, *arg, **kw):
        fn = arg[0]
        rest = arg[1:]
        try:
            parent_sessidmgr=getattr(self.aq_parent, self.id)
            parent_fn = getattr(parent_sessidmgr, fn)
        except AttributeError:
            raise BrowserIdManagerErr, 'Browser id management disabled'
        return apply(parent_fn, rest, kw)

    def _setCookie(
        self, token, REQUEST, remove=0, now=time.time, strftime=time.strftime,
        gmtime=time.gmtime
        ):
        """ """
        expires = None
        if remove:
            expires = "Sun, 10-May-1971 11:59:00 GMT"
        elif self.cookie_life_days:
            expires = now() + self.cookie_life_days * 86400
            # Wdy, DD-Mon-YYYY HH:MM:SS GMT
            expires = strftime('%a %d-%b-%Y %H:%M:%S GMT',gmtime(expires))
        d = {'domain':self.cookie_domain,'path':self.cookie_path,
             'secure':self.cookie_secure,'expires':expires}

        if self.cookie_secure:
            URL1 = REQUEST.get('URL1', None)
            if URL1 is None:
                return # should we raise an exception?
            if string.split(URL1,':')[0] != 'https':
                return # should we raise an exception?
         
        cookies = REQUEST.RESPONSE.cookies
        cookie = cookies[self.token_key]= {}
        for k,v in d.items():
            if v:
                cookie[k] = v #only stuff things with true values
        cookie['value'] = token
        
    def _getB64TStamp(
        self, b2a=binascii.b2a_base64,gmtime=time.gmtime, time=time.time,
        b64_trans=b64_trans, split=string.split,
        TimeStamp=TimeStamp.TimeStamp, translate=string.translate
        ):
        t=time()
        ts=split(b2a(`apply(TimeStamp,(gmtime(t)[:5]+(t%60,)))`)[:-1],'=')[0]
        return translate(ts, b64_trans)

    def _getB64TStampToInt(
        self, ts, TimeStamp=TimeStamp.TimeStamp, b64_untrans=b64_untrans,
        a2b=binascii.a2b_base64, translate=string.translate
        ):
        return TimeStamp(a2b(translate(ts+'=',b64_untrans))).timeTime()

    def _getTokenPieces(self, token):
        """ returns browser token parts in a tuple consisting of rand_id,
        timestamp
        """
        return (token[:8], token[8:19])

    def _isAWellFormedToken(self, token, binerr=binascii.Error,
                            timestamperr=TimeStamp.error):
        try:
            rnd, ts = self._getTokenPieces(token)
            int(rnd)
            self._getB64TStampToInt(ts)
            return token
        except (TypeError, ValueError, AttributeError, IndexError, binerr,
                timestamperr):
            return None

    def _setId(self, id):
        if id != self.id:
            raise Globals.MessageDialog(
                title='Cannot rename',
                message='You cannot rename a browser id manager, sorry!',
                action ='./manage_main',)


Globals.InitializeClass(BrowserIdManager)


=== Added File Products/Sessions/LowConflictConnection.py ===
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# 
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

from ZODB.Connection import Connection
from ZODB.POSException import ConflictError
from cPickle import Unpickler
from cStringIO import StringIO
from common import DEBUG

class LowConflictConnection(Connection):
    def setstate(self, object):
        """
        Unlike the 'stock' Connection class' setstate, this method
        doesn't raise ConflictErrors.  This is potentially dangerous
        for applications that need absolute consistency, but
        sessioning is not one of those.
        """
        oid=object._p_oid
        invalid = self._invalid
        if invalid(None):
            # only raise a conflict if there was
            # a mass invalidation, but not if we see this
            # object's oid as invalid
            raise ConflictError, `oid`
        p, serial = self._storage.load(oid, self._version)
        file=StringIO(p)
        unpickler=Unpickler(file)
        unpickler.persistent_load=self._persistent_load
        unpickler.load()
        state = unpickler.load()
        if hasattr(object, '__setstate__'):
            object.__setstate__(state)
        else:
            d=object.__dict__
            for k,v in state.items(): d[k]=v
        object._p_serial=serial




=== Added File Products/Sessions/RAM_DB.py ===
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# 
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################
"""Mounted database support

$Id: RAM_DB.py,v 1.1 2001/10/31 15:36:04 chrism Exp $"""
__version__='$Revision: 1.1 $'[11:-2]

import Globals
from ZODB.Mount import MountPoint
import string
import OFS

class MountedRAM_DB(MountPoint, OFS.SimpleItem.Item):
    """
    A mounted RAM database with a basic interface for displaying the
    reason the database did not connect.
    """
    icon = 'p_/broken'
    manage_options = ({'label':'Traceback', 'action':'manage_traceback'},)
    meta_type = 'Broken Mounted RAM Database'
    
    def __init__(self, id, params=None):
        self.id = str(id)
        MountPoint.__init__(self, path='/', params)
        
    manage_traceback = Globals.DTMLFile('mountfail', globals())

    def _createDB(self, db = db):
        """ Create a mounted RAM database """
        from SessionStorage import SessionStorage
        from ZODB.DB import DB
        from LowConflictConnection import LowConflictConnection
        db = DB(SessionStorage())
        db.klass = LowConflictConnection
        return db
    
    def _getMountRoot(self, root):
        sdc = root.get('folder', None)
        if sdc is None:
            sdc = root['folder'] = OFS.Folder.Folder()
        return sdc
    
    def mount_error_(self):
        return self._v_connect_error




=== Added File Products/Sessions/SessionDataManager.py ===
import re, time, string, sys
import Globals
from OFS.SimpleItem import Item
from Acquisition import Implicit, Explicit, aq_base
from Persistence import Persistent
from AccessControl.Owned import Owned
from AccessControl.Role import RoleManager
from App.Management import Tabs
from zLOG import LOG, WARNING
from AccessControl import ClassSecurityInfo
import SessionInterfaces
from SessionPermissions import *
from common import DEBUG

BID_MGR_NAME = 'browser_id_manager'

bad_path_chars_in=re.compile('[^a-zA-Z0-9-_~\,\. \/]').search

class SessionDataManagerErr(Exception): pass

constructSessionDataManagerForm = Globals.DTMLFile('addDataManager', globals())

def constructSessionDataManager(self, id, title='', path=None)
    """ """
    ob = SessionDataManager(id, path, title)
    self._setObject(id, ob)
    if REQUEST is not None:
        return self.manage_main(self, REQUEST, update_menu=1)

class SessionDataManager(Item, Implicit, Persistent, RoleManager, Owned, Tabs):
    """ The Zope default session data manager implementation """

    meta_type = 'Session Data Manager'

    manage_options=(
        {'label': 'Settings',
         'action':'manage_sessiondatamgr',
         },
        {'label': 'Security',
         'action':'manage_access',
         },
        {'label': 'Ownership',
         'action':'manage_owner'
         },
        )

    security = ClassSecurityInfo()

    security.setDefaultAccess('deny')
    security.setPermissionDefault(CHANGE_DATAMGR_PERM, ['Manager'])
    security.setPermissionDefault(MGMT_SCREEN_PERM, ['Manager'])
    security.setPermissionDefault(ACCESS_CONTENTS_PERM,['Manager','Anonymous'])
    security.setPermissionDefault(ARBITRARY_SESSIONDATA_PERM,['Manager'])
    security.setPermissionDefault(ACCESS_SESSIONDATA_PERM,
                                  ['Manager','Anonymous'])

    icon='misc_/CoreSessionTracking/datamgr.gif'

    __implements__ = (SessionInterfaces.SessionDataManagerInterface, )

    manage_sessiondatamgr = Globals.DTMLFile('manageDataManager', globals())

    # INTERFACE METHODS FOLLOW

    security.declareProtected(ACCESS_SESSIONDATA_PERM, 'getSessionData')
    def getSessionData(self, create=1):
        """ """
        key = self.getBrowserIdManager().getToken(create=create)
        if key is not None:
            return self._getSessionDataObject(key)

    security.declareProtected(ACCESS_SESSIONDATA_PERM, 'hasSessionData')
    def hasSessionData(self):
        """ """
        if self.getBrowserIdManager().getToken(create=0):
            if self._hasSessionDataObject(key):
                return 1

    security.declareProtected(ARBITRARY_SESSIONDATA_PERM,'getSessionDataByKey')
    def getSessionDataByKey(self, key):
        return self._getSessionDataObjectByKey(key)
    
    security.declareProtected(ACCESS_CONTENTS_PERM, 'getBrowserIdManager')
    def getBrowserIdManager(self):
        """ """
        mgr = getattr(self, BID_MGR_NAME, None)
        if mgr is None:
            raise SessionDataManagerErr,(
                'No browser id manager named %s could be found.' % BID_MGR_NAME
                )
        return mgr

    # END INTERFACE METHODS
    
    def __init__(self, id, path=None, title=''):
        self.id = id
        self.setContainerPath(path)
        self.setTitle(title)

    security.declareProtected(CHANGE_DATAMGR_PERM, 'manage_changeSDM')
    def manage_changeSDM(self, title, path=None, REQUEST=None):
        """ """
        self.setContainerPath(path)
        self.setTitle(title)
        if REQUEST is not None:
            return self.manage_sessiondatamgr(self, REQUEST)

    security.declareProtected(CHANGE_DATAMGR_PERM, 'setTitle')
    def setTitle(self, title):
        """ """
        if not title: self.title = ''
        else: self.title = str(title)

    security.declareProtected(CHANGE_DATAMGR_PERM, 'setContainerPath')
    def setContainerPath(self, path=None):
        """ """
        if not path:
            self.obpath = None # undefined state
        elif type(path) is type(''):
            if bad_path_chars_in(path):
                raise SessionDataManagerErr, (
                    'Container path contains characters invalid in a Zope '
                    'object path'
                    )
            self.obpath = string.split(path, '/')
        elif type(path) in (type([]), type(())):
            self.obpath = list(path) # sequence
        else:
            raise SessionDataManagerErr, ('Bad path value %s' % path)
            
    security.declareProtected(MGMT_SCREEN_PERM, 'getContainerPath')
    def getContainerPath(self):
        """ """
        if self.obpath is not None:
            return string.join(self.obpath, '/')
        return '' # blank string represents undefined state
    
    def _hasSessionDataObject(self, key):
        """ """
        c = self._getSessionDataContainer()
        return c.has_key(key)

    def _getSessionDataObject(self, key):
        """ returns new or existing session data object """
        container = self._getSessionDataContainer()
        ob = container.new_or_existing(key)
        return ob.__of__(self)

    def _getSessionDataObjectByKey(self, key):
        """ returns new or existing session data object """
        container = self._getSessionDataContainer()
        ob = container.get(key)
        if ob is not None:
            return ob.__of__(self)

    def _getSessionDataContainer(self):
        """ Do not cache the results of this call.  Doing so breaks the
        transactions for mounted storages. """
        if self.obpath is None:
            err = 'Session data container is unspecified in %s' % self.getId()
            if DEBUG:
                LOG('Session Tracking', 0, err)
            raise SessionIdManagerErr, err
        # return an external data container
        try:
            # This should arguably use restrictedTraverse, but it
            # currently fails for mounted storages.  This might
            # be construed as a security hole, albeit a minor one.
            # unrestrictedTraverse is also much faster.
            if DEBUG and not hasattr(self, '_v_wrote_dc_type'):
                args = string.join(self.obpath, '/')
                LOG('Session Tracking', 0,
                    'External data container at %s in use' % args)
                self._v_wrote_dc_type = 1
            return self.unrestrictedTraverse(self.obpath)
        except:
            raise SessionDataManagerErr, (
                "External session data container '%s' not found." %
                string.join(self.obpath,'/')
                )

            


=== Added File Products/Sessions/SessionPermissions.py ===
CHANGE_DATAMGR_PERM = 'Change Session Data Manager'
MGMT_SCREEN_PERM = 'View management screens'
ACCESS_CONTENTS_PERM = 'Access contents information'
ACCESS_SESSIONDATA_PERM = 'Access session data'
ARBITRARY_SESSIONDATA_PERM = 'Access arbitrary user session data'
CHANGE_IDMGR_PERM = 'Change Session Id Manager'
MANAGE_CONTAINER_PERM = 'Manage Session Data Container'


=== Added File Products/Sessions/SessionStorage.py ===
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# 
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

"""
A storage implementation which uses RAM to persist objects, much like
MappingStorage, but unlike MappingStorage needs not be packed to get rid of
non-cyclic garbage.  This is a ripoff of Jim's Packless bsddb3 storage.

$Id: SessionStorage.py,v 1.1 2001/10/31 15:36:04 chrism Exp $
"""

__version__ ='$Revision: 1.1 $'[11:-2]

from zLOG import LOG
from struct import pack, unpack
from common import DEBUG
from ZODB.referencesf import referencesf
from ZODB import POSException
from ZODB.BaseStorage import BaseStorage
try:
    from ZODB.ConflictResolution import ConflictResolvingStorage
except:
    LOG('Session Tracking', 100,
        ('Not able to use ConflictResolvingStorage for SessionStorage, '
         'this is suboptimal.  Upgrade to Zope 2.3.2 or later to '
         'make use of conflict resolution.'))
    class ConflictResolvingStorage: pass

class ReferenceCountError(POSException.POSError):
    """ An error occured while decrementing a reference to an object in
    the commit phase. The object's reference count was below zero."""

class SessionStorageError(POSException.POSError):
    """ A Session Storage exception occurred.  This probably indicates that
    there is a low memory condition or a tempfile space shortage.  Check
    available tempfile space and RAM consumption and restart the server
    process."""

class SessionStorage(BaseStorage, ConflictResolvingStorage):

    def __init__(self, name='SessionStorage'):
        """
        index -- mapping of oid to current serial
        referenceCount -- mapping of oid to count
        oreferences -- mapping of oid to a sequence of its referenced oids
        opickle -- mapping of oid to pickle
        """
        BaseStorage.__init__(self, name)

        self._index={}
        self._referenceCount={}
        self._oreferences={}
        self._opickle={}
        self._tmp = []
        self._oid = '\0\0\0\0\0\0\0\0'

    def __len__(self):
        return len(self._index)

    def getSize(self):
        return 0

    def _clear_temp(self):
        self._tmp = []
        
    def close(self):
        """
        Close the storage
        """
    
    def load(self, oid, version):
        self._lock_acquire()
        try:
            s=self._index[oid]
            p=self._opickle[oid]
            return p, s # pickle, serial
        finally:
            self._lock_release()

    def loadSerial(self, oid, serial):
        """ only a stub to make conflict resolution work! """
        self._lock_acquire()
        try:
            return self._opickle[oid]
        finally:
            self._lock_release()
            
    def store(self, oid, serial, data, version, transaction):
        if transaction is not self._transaction:
            raise POSException.StorageTransactionError(self, transaction)
        if version:
            raise POSException.Unsupported, "Versions aren't supported"

        self._lock_acquire()
        try:
            if self._index.has_key(oid):
                oserial=self._index[oid]
                if serial != oserial:
                    if hasattr(self, 'tryToResolveConflict'):
                        data=self.tryToResolveConflict(
                            oid, oserial, serial, data
                            )
                        if not data:
                            raise POSException.ConflictError, (serial,oserial)
                    else:
                        raise POSException.ConflictError, (serial,oserial)
                
            serial=self._serial
            self._tmp.append((oid, data))
            return serial
        finally:
            self._lock_release()


    def _finish(self, tid, u, d, e):
        zeros={}
        referenceCount=self._referenceCount
        referenceCount_get=referenceCount.get
        oreferences=self._oreferences
        serial=self._serial
        index=self._index
        opickle=self._opickle

        # iterate over all the objects touched by/created within this
        # transaction
        for entry in self._tmp:
            oid, data = entry[:]
            referencesl=[]
            referencesf(data, referencesl)
            references={}
            for roid in referencesl:
                references[roid]=1
            referenced=references.has_key

            # Create a reference count for this object if one
            # doesn't already exist
            if referenceCount_get(oid) is None:
                referenceCount[oid] = 0
                #zeros[oid]=1

            # update references that are already associated with this
            # object
            roids = oreferences.get(oid, [])
            for roid in roids:
                if referenced(roid):
                    # still referenced, so no need to update
                    # remove it from the references dict so it doesn't
                    # get "added" in the next clause
                    del references[roid]
                else:
                    # Delete the stored ref, since we no longer
                    # have it
                    oreferences[oid].remove(roid)
                    # decrement refcnt:
                    rc = referenceCount_get(roid, 1)
                    rc=rc-1
                    if rc < 0:
                        # This should never happen
                        raise ReferenceCountError, (
                            "%s (Oid %s had refcount %s)" %
                            (ReferenceCountError.__doc__,`roid`,rc)
                            )
                    referenceCount[roid] = rc
                    if rc==0:
                        zeros[roid]=1

            # Create a reference list for this object if one
            # doesn't already exist
            if oreferences.get(oid) is None:
                oreferences[oid] = []

            # Now add any references that weren't already stored
            for roid in references.keys():
                oreferences[oid].append(roid)
                # Create/update refcnt
                rc=referenceCount_get(roid, 0)
                if rc==0 and zeros.get(roid) is not None:
                    del zeros[roid]
                referenceCount[roid] = rc+1

            index[oid] =  serial
            opickle[oid] = data

        if zeros:
            for oid in zeros.keys():
                if oid == '\0\0\0\0\0\0\0\0': continue
                self._takeOutGarbage(oid)

        self._tmp = []

    def _takeOutGarbage(self, oid):
        # take out the garbage.
        referenceCount=self._referenceCount
        referenceCount_get=referenceCount.get
        try: del referenceCount[oid]
        except: pass
        try: del self._opickle[oid]
        except: pass
        try: del self._index[oid]
        except: pass

        # Remove/decref references
        roids = self._oreferences.get(oid, [])
        while roids:
            roid = roids.pop(0)
            # decrement refcnt:
            rc=referenceCount_get(roid, 0)
            if rc==0:
                self._takeOutGarbage(roid)
            elif rc < 0:
                raise ReferenceCountError, (
                    "%s (Oid %s had refcount %s)" %
                    (ReferenceCountError.__doc__,`roid`,rc)
                    )
            else:
                referenceCount[roid] = rc - 1
        try: del self._oreferences[oid]
        except: pass
                
    def pack(self, t, referencesf):
        self._lock_acquire()
        try:
            rindex={}
            referenced=rindex.has_key
            rootl=['\0\0\0\0\0\0\0\0']

            # mark referenced objects
            while rootl:
                oid=rootl.pop()
                if referenced(oid): continue
                p = self._opickle[oid]
                referencesf(p, rootl)
                rindex[oid] = None

            # sweep unreferenced objects
            for oid in self._index.keys():
                if not referenced(oid):
                    self._takeOutGarbage(oid)
        finally:
            self._lock_release()



    



=== Added File Products/Sessions/common.py ===
import os
DEBUG = os.environ.get('CST_DEBUG', '')


=== Added File Products/Sessions/mountfail.dtml ===
<HTML><HEAD><TITLE>Mount Failure Traceback</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" LINK="#000099" VLINK="#555555">
<dtml-var manage_tabs>

<h3>Mount Failure Traceback</h3>

<dtml-let exc=mount_error_>
<dtml-if exc>
<strong>Error type:</strong> <dtml-var "exc[0]" html_quote><br>
<strong>Error value:</strong> <dtml-var "exc[1]" html_quote><br>
<pre>
<dtml-var "exc[2]" html_quote>
</pre>
<dtml-else>
Database not mounted.
</dtml-if>
</dtml-let>

</BODY>
</HTML>


=== Products/Sessions/SessionInterfaces.py 1.1.1.1 => 1.2 ===
 
-class BrowserIdManager(
+class BrowserIdManagerInterface(
     Interface.Base
     ):
     """
@@ -96,7 +96,7 @@
         a token key namespace at the time of the call.
         """
 
-class SessionDataManager(
+class SessionDataManagerInterface(
     Interface.Base
     ):
     """
@@ -110,6 +110,8 @@
     def getBrowserIdManager(self):
         """
         Returns the nearest acquirable browser id manager.
+
+        Raises SessionDataManagerErr if no browser id manager can be found.
 
         Permission required: Access session data
         """