CherryPy / cherrypy / lib / filter / sessionfilter.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
"""
Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the CherryPy Team nor the names of its contributors 
      may be used to endorse or promote products derived from this software 
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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.
"""

""" Session implementation for CherryPy.
We use cherrypy.request to store some convenient variables as
well as data about the session for the current request. Instead of
polluting cherrypy.request we use a dummy object called
cherrypy.request._session (sess) to store these variables.

Variables used to store config options:
    - sess.sessionTimeout: timeout delay for the session
    - sess.sessionLocking: mechanism used to lock the session ('implicit' or 'explicit')

Variables used to store temporary variables:
    - sess.sessionStorage (instance of the class implementing the backend)


Variables used to store the session for the current request:
    - sess.sessionData: dictionary containing the actual session data
    - sess.sessionID: current session ID
    - sess.expirationTime: date/time when the current session will expire

Global variables (RAM backend only):
    - cherrypy._sessionLockDict: dictionary containing the locks for all sessionIDs
    - cherrypy._sessionHolder: dictionary containing the data for all sessions

"""

import datetime
import os
import pickle
import random
import sha
import StringIO
import time
import threading
import types

import basefilter


class EmptyClass:
    """ An empty class """
    pass


class SessionDeadlockError(Exception):
    """ The session could not acquire a lock after a certain time """
    pass


class SessionNotEnabledError(Exception):
    """ User forgot to set sessionFilter.on to True """
    pass


class SessionFilter(basefilter.BaseFilter):
    
    def beforeRequestBody(self):
        # We have to dynamically import cherrypy because Python can't handle
        #   circular module imports :-(
        global cherrypy
        import cherrypy
        conf = cherrypy.config.get
        
        cherrypy.request._session = EmptyClass()
        sess = cherrypy.request._session
        sess.toBeCleaned = True
        now = datetime.datetime.now()
        # Dont enable session if sessionFilter is off or if this is a
        #   request for static data
        if ((not conf('sessionFilter.on', False))
              or conf('staticFilter.on', False)):
            sess.sessionStorage = None
            return
        
        sess.locked = False # Not locked by default
        
        # Read config options
        sess.sessionTimeout = conf('sessionFilter.timeout', 60)
        sess.sessionLocking = conf('sessionFilter.locking', 'explicit')
        sess.onCreateSession = conf('sessionFilter.onCreateSession',
                                    lambda data: None)
        sess.onDeleteSession = conf('sessionFilter.onDeleteSession',
                                    lambda data: None)
        
        cleanUpDelay = conf('sessionFilter.cleanUpDelay', 5)
        cleanUpDelay = datetime.timedelta(seconds = cleanUpDelay * 60)
        
        cookieName = conf('sessionFilter.cookieName', 'sessionID')
        sess.deadlockTimeout = conf('sessionFilter.deadlockTimeout', 30)
        
        storage = conf('sessionFilter.storageType', 'Ram')
        storage = storage[0].upper() + storage[1:]
        
        # People can set their own custom class
        #   through sessionFilter.storageClass
        sess.sessionStorage = conf('sessionFilter.storageClass', None)
        if sess.sessionStorage is None:
            sess.sessionStorage = globals()[storage + 'Storage']()
        else:
            sess.sessionStorage = sess.sessionStorage()
        
        # Check if we need to clean up old sessions
        if cherrypy._sessionLastCleanUpTime + cleanUpDelay < now:
            sess.sessionStorage.cleanUp()
        
        # Check if request came with a session ID
        if cookieName in cherrypy.request.simpleCookie:
            # It did: we try to load the session data
            sess.sessionID = cherrypy.request.simpleCookie[cookieName].value
            
            # If using implicit locking, acquire lock
            if sess.sessionLocking == 'implicit':
                sess.sessionData = {'_id': sess.sessionID}
                sess.sessionStorage.acquireLock()
            
            data = sess.sessionStorage.load(sess.sessionID)
            # data is either None or a tuple (sessionData, expirationTime)
            if data is None or data[1] < now:
                # Expired session:
                # flush session data (but keep the same sessionID)
                sess.sessionData = {'_id': sess.sessionID}
            else:
                sess.sessionData = data[0]
        else:
            # No sessionID yet
            sess.sessionID = generateSessionID()
            sess.sessionData = {'_id': sess.sessionID}
            sess.onCreateSession(sess.sessionData)
        # Set response cookie
        cookie = cherrypy.response.simpleCookie
        cookie[cookieName] = sess.sessionID
        cookie[cookieName]['path'] = '/'
        cookie[cookieName]['max-age'] = sess.sessionTimeout * 60
        cookie[cookieName]['version'] = 1
    
    def beforeFinalize(self):
        def saveData(body, sess):
            try:
                # If the body is a generator, we have to save the data
                #   *after* the generator has been consumed
                if isinstance(body, types.GeneratorType):
                    for line in body:
                        yield line
                
                # Save session data
                t = datetime.timedelta(seconds = sess.sessionTimeout * 60)
                expirationTime = datetime.datetime.now() + t
                sess.sessionStorage.save(sess.sessionID, sess.sessionData,
                                         expirationTime)
                if sess.locked:
                    # Always release the lock if the user didn't release it
                    sess.sessionStorage.releaseLock()
                
                # If the body is not a generator, we save the data
                #   before the body is returned
                if not isinstance(body, types.GeneratorType):
                    for line in body:
                        yield line
            except:
                # Can't use try/finally because of yield
                self._clean()
                raise
            self._clean()
        
        sess = cherrypy.request._session
        if not sess.sessionStorage:
            # Sessions are not enabled: do nothing
            return
        
        # Make a wrapper around the body in order to save the session
        #   either before or after the body is returned
        cherrypy.response.body = saveData(cherrypy.response.body, sess)
        sess.toBeCleaned = False

    def onEndResource(self):
        # If RequestHandled is raised, beforeFinalize and afterErrorResponse
        #   are not called, so we release the session here
        sess = cherrypy.request._session
        if sess.toBeCleaned:
            self._clean()

    def afterErrorResponse(self):
        self._clean()
    
    def _clean(self):
        sess = cherrypy.request._session
        if not getattr(sess, 'sessionStorage', None):
            # Sessions are not enabled: do nothing
            return
        if getattr(sess, 'locked', None):
            # If the session is still locked we release the lock
            sess.sessionStorage.releaseLock()
        if getattr(sess, 'sessionStorage', None):
            del sess.sessionStorage


class RamStorage:
    """ Implementation of the RAM backend for sessions """
    
    def load(self, id):
        return cherrypy._sessionDataHolder.get(id)
    
    def save(self, id, data, expirationTime):
        cherrypy._sessionDataHolder[id] = (data, expirationTime)
    
    def acquireLock(self):
        sess = cherrypy.request._session
        id = cherrypy.session['_id']
        lock = cherrypy._sessionLockDict.get(id)
        if lock is None:
            lock = threading.Lock()
            cherrypy._sessionLockDict[id] = lock
        startTime = time.time()
        while True:
            if lock.acquire(False):
                break
            if time.time() - startTime > sess.deadlockTimeout:
                raise SessionDeadlockError()
            time.sleep(0.5)
        sess.locked = True
    
    def releaseLock(self):
        sess = cherrypy.request._session
        id = cherrypy.session['_id']
        cherrypy._sessionLockDict[id].release()
        sess.locked = False
    
    def cleanUp(self):
        sess = cherrypy.request._session
        toBeDeleted = []
        now = datetime.datetime.now()
        for id, (data, expirationTime) in cherrypy._sessionDataHolder.iteritems():
            if expirationTime < now:
                toBeDeleted.append(id)
        for id in toBeDeleted:
            sess.onDeleteSession(cherrypy._sessionDataHolder[id])
            del cherrypy._sessionDataHolder[id]


class FileStorage:
    """ Implementation of the File backend for sessions """
    
    SESSION_PREFIX = 'session-'
    LOCK_SUFFIX = '.lock'
    
    def load(self, id):
        filePath = self._getFilePath(id)
        try:
            f = open(filePath, "rb")
            data = pickle.load(f)
            f.close()
            return data
        except IOError:
            return None
    
    def save(self, id, data, expirationTime):
        filePath = self._getFilePath(id)
        f = open(filePath, "wb")
        pickle.dump((data, expirationTime), f)
        f.close()
    
    def acquireLock(self):
        sess = cherrypy.request._session
        filePath = self._getFilePath(cherrypy.session['_id'])
        lockFilePath = filePath + self.LOCK_SUFFIX
        self._lockFile(lockFilePath)
        sess.locked = True
    
    def releaseLock(self):
        sess = cherrypy.request._session
        filePath = self._getFilePath(cherrypy.session['_id'])
        lockFilePath = filePath + self.LOCK_SUFFIX
        self._unlockFile(lockFilePath)
        sess.locked = False
    
    def cleanUp(self):
        sess = cherrypy.request._session
        storagePath = cherrypy.config.get('sessionFilter.storagePath')
        now = datetime.datetime.now()
        # Iterate over all files in the dir/ and exclude non session files
        #   and lock files
        for fname in os.listdir(storagePath):
            if (fname.startswith(self.SESSION_PREFIX)
                and not fname.endswith(self.LOCK_SUFFIX)):
                # We have a session file: lock it, load it and check
                #   if it's expired
                filePath = os.path.join(storagePath, fname)
                lockFilePath = filePath + self.LOCK_SUFFIX
                self._lockFile(lockFilePath)
                try:
                    f = open(filePath, "rb")
                    data, expirationTime = pickle.load(f)
                    f.close()
                    if expirationTime < now:
                        # Session expired: deleting it
                        id = fname[len(self.SESSION_PREFIX):]
                        sess.onDeleteSession(data)
                        os.unlink(filePath)
                except IOError:
                    # We can't access the file ... nevermind
                    pass
                self._unlockFile(lockFilePath)
    
    def _getFilePath(self, id):
        storagePath = cherrypy.config.get('sessionFilter.storagePath')
        fileName = self.SESSION_PREFIX + id
        filePath = os.path.join(storagePath, fileName)
        if not os.path.normpath(filePath).startswith(storagePath):
            raise cherrypy.HTTPError(400, "Invalid session id in cookie.")
        return filePath
    
    def _lockFile(self, path):
        sess = cherrypy.request._session
        startTime = time.time()
        while True:
            try:
                lockfd = os.open(path, os.O_CREAT|os.O_WRONLY|os.O_EXCL)
            except OSError:
                if time.time() - startTime > sess.deadlockTimeout:
                    raise SessionDeadlockError()
                time.sleep(0.5)
            else:
                os.close(lockfd) 
                break
    
    def _unlockFile(self, path):
        os.unlink(path)


class PostgreSQLStorage:
    """ Implementation of the PostgreSQL backend for sessions. It assumes
        a table like this:

            create table session (
                id varchar(40),
                data text,
                expiration_time timestamp
            )
    """
    
    def __init__(self):
        self.db = cherrypy.config.get('sessionFilter.getDB')()
        self.cursor = self.db.cursor()
    
    def __del__(self):
        if self.cursor:
            self.cursor.close()
        self.db.commit()
    
    def load(self, id):
        # Select session data from table
        self.cursor.execute(
            'select data, expiration_time from session where id=%s',
            (id,))
        rows = self.cursor.fetchall()
        if not rows:
            return None
        data, expirationTime = rows[0]
        # Unpickle data
        f = StringIO.StringIO(data)
        data = pickle.load(f)
        return (data, expirationTime)
    
    def save(self, id, data, expirationTime):
        # Try to delete session if it was already there
        self.cursor.execute(
            'delete from session where id=%s',
            (id,))
        # Pickle data
        f = StringIO.StringIO()
        pickle.dump(data, f)
        # Insert new session data
        self.cursor.execute(
            'insert into session (id, data, expiration_time) values (%s, %s, %s)',
            (id, f.getvalue(), expirationTime))
    
    def acquireLock(self):
        # We use the "for update" clause to lock the row
        self.cursor.execute(
            'select id from session where id=%s for update',
            (cherrypy.session['_id'],))
    
    def releaseLock(self):
        # We just close the cursor and that will remove the lock
        #   introduced by the "for update" clause
        self.cursor.close()
        self.cursor = None
    
    def cleanUp(self):
        sess = cherrypy.request._session
        now = datetime.datetime.now()
        self.cursor.execute(
            'select data from session where expiration_time < %s',
            (now,))
        rows = self.cursor.fetchall()
        for row in rows:
            sess.onDeleteSession(row[0])
        self.cursor.execute(
            'delete from session where expiration_time < %s',
            (now,))


def generateSessionID():
    """ Return a new sessionID """
    return sha.new('%s' % random.random()).hexdigest()


# Users access sessions through cherrypy.session, but we want this
#   to be thread-specific so we use a special wrapper that forwards
#   calls to cherrypy.session to a thread-specific dictionary called
#   cherrypy.request._session.sessionData
class SessionWrapper:
    
    def __getattr__(self, name):
        sess = cherrypy.request._session
        if sess.sessionStorage is None:
            raise SessionNotEnabledError()
        # Create thread-specific dictionary if needed
        sess.sessionData = getattr(sess, 'sessionData', {})
        if name == 'acquireLock':
            return sess.sessionStorage.acquireLock
        elif name == 'releaseLock':
            return sess.sessionStorage.releaseLock
        return getattr(sess.sessionData, name)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.