2012-10-28 05:12:08 +08:00
|
|
|
import datetime
|
2008-08-21 05:12:45 +08:00
|
|
|
import errno
|
2007-09-16 05:29:14 +08:00
|
|
|
import os
|
2007-12-05 04:24:22 +08:00
|
|
|
import tempfile
|
2008-06-23 13:08:07 +08:00
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
from django.conf import settings
|
2008-08-14 11:57:18 +08:00
|
|
|
from django.contrib.sessions.backends.base import SessionBase, CreateError
|
2007-12-05 04:24:22 +08:00
|
|
|
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
|
2012-10-28 05:12:08 +08:00
|
|
|
from django.utils import timezone
|
2008-06-23 13:08:07 +08:00
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
class SessionStore(SessionBase):
|
|
|
|
"""
|
|
|
|
Implements a file based session store.
|
|
|
|
"""
|
|
|
|
def __init__(self, session_key=None):
|
2012-10-28 05:12:08 +08:00
|
|
|
self.storage_path = type(self)._get_storage_path()
|
2008-01-06 20:53:09 +08:00
|
|
|
self.file_prefix = settings.SESSION_COOKIE_NAME
|
2007-09-16 05:29:14 +08:00
|
|
|
super(SessionStore, self).__init__(session_key)
|
2008-01-06 20:53:09 +08:00
|
|
|
|
2012-10-28 05:12:08 +08:00
|
|
|
@classmethod
|
|
|
|
def _get_storage_path(cls):
|
|
|
|
try:
|
|
|
|
return cls._storage_path
|
|
|
|
except AttributeError:
|
|
|
|
storage_path = getattr(settings, "SESSION_FILE_PATH", None)
|
|
|
|
if not storage_path:
|
|
|
|
storage_path = tempfile.gettempdir()
|
|
|
|
|
|
|
|
# Make sure the storage path is valid.
|
|
|
|
if not os.path.isdir(storage_path):
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"The session storage path %r doesn't exist. Please set your"
|
|
|
|
" SESSION_FILE_PATH setting to an existing directory in which"
|
|
|
|
" Django can store session data." % storage_path)
|
|
|
|
|
|
|
|
cls._storage_path = storage_path
|
|
|
|
return storage_path
|
|
|
|
|
2011-02-09 10:13:24 +08:00
|
|
|
VALID_KEY_CHARS = set("abcdef0123456789")
|
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
def _key_to_file(self, session_key=None):
|
|
|
|
"""
|
|
|
|
Get the file associated with this session key.
|
|
|
|
"""
|
|
|
|
if session_key is None:
|
2011-11-28 01:52:24 +08:00
|
|
|
session_key = self._get_or_create_session_key()
|
2008-01-06 20:53:09 +08:00
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
# Make sure we're not vulnerable to directory traversal. Session keys
|
2008-06-23 13:08:07 +08:00
|
|
|
# should always be md5s, so they should never contain directory
|
|
|
|
# components.
|
2011-02-09 10:13:24 +08:00
|
|
|
if not set(session_key).issubset(self.VALID_KEY_CHARS):
|
2008-06-23 13:08:07 +08:00
|
|
|
raise SuspiciousOperation(
|
2011-02-09 10:13:24 +08:00
|
|
|
"Invalid characters in session key")
|
2008-01-06 20:53:09 +08:00
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
return os.path.join(self.storage_path, self.file_prefix + session_key)
|
2008-01-06 20:53:09 +08:00
|
|
|
|
2012-10-28 05:12:08 +08:00
|
|
|
def _last_modification(self):
|
|
|
|
"""
|
|
|
|
Return the modification time of the file storing the session's content.
|
|
|
|
"""
|
|
|
|
modification = os.stat(self._key_to_file()).st_mtime
|
|
|
|
if settings.USE_TZ:
|
|
|
|
modification = datetime.datetime.utcfromtimestamp(modification)
|
|
|
|
modification = modification.replace(tzinfo=timezone.utc)
|
|
|
|
else:
|
|
|
|
modification = datetime.datetime.fromtimestamp(modification)
|
|
|
|
return modification
|
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
def load(self):
|
|
|
|
session_data = {}
|
|
|
|
try:
|
2012-05-05 20:01:38 +08:00
|
|
|
with open(self._key_to_file(), "rb") as session_file:
|
2008-08-31 04:50:41 +08:00
|
|
|
file_data = session_file.read()
|
2012-05-05 20:01:38 +08:00
|
|
|
# Don't fail if there is no data in the session file.
|
|
|
|
# We may have opened the empty placeholder file.
|
|
|
|
if file_data:
|
|
|
|
try:
|
|
|
|
session_data = self.decode(file_data)
|
|
|
|
except (EOFError, SuspiciousOperation):
|
|
|
|
self.create()
|
2012-10-28 05:12:08 +08:00
|
|
|
|
|
|
|
# Remove expired sessions.
|
|
|
|
expiry_age = self.get_expiry_age(
|
|
|
|
modification=self._last_modification(),
|
|
|
|
expiry=session_data.get('_session_expiry'))
|
|
|
|
if expiry_age < 0:
|
|
|
|
session_data = {}
|
|
|
|
self.delete()
|
|
|
|
self.create()
|
2008-08-14 11:57:18 +08:00
|
|
|
except IOError:
|
2010-08-05 19:49:58 +08:00
|
|
|
self.create()
|
2007-09-16 05:29:14 +08:00
|
|
|
return session_data
|
|
|
|
|
2008-08-14 11:57:18 +08:00
|
|
|
def create(self):
|
|
|
|
while True:
|
|
|
|
self._session_key = self._get_new_session_key()
|
|
|
|
try:
|
|
|
|
self.save(must_create=True)
|
|
|
|
except CreateError:
|
|
|
|
continue
|
|
|
|
self.modified = True
|
|
|
|
self._session_cache = {}
|
|
|
|
return
|
|
|
|
|
|
|
|
def save(self, must_create=False):
|
2008-08-31 04:50:41 +08:00
|
|
|
# Get the session data now, before we start messing
|
|
|
|
# with the file it is stored within.
|
2008-08-15 03:43:08 +08:00
|
|
|
session_data = self._get_session(no_load=must_create)
|
2008-08-31 04:50:41 +08:00
|
|
|
|
|
|
|
session_file_name = self._key_to_file()
|
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
try:
|
2008-08-31 04:50:41 +08:00
|
|
|
# Make sure the file exists. If it does not already exist, an
|
|
|
|
# empty placeholder file is created.
|
|
|
|
flags = os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0)
|
|
|
|
if must_create:
|
|
|
|
flags |= os.O_EXCL
|
|
|
|
fd = os.open(session_file_name, flags)
|
|
|
|
os.close(fd)
|
|
|
|
|
2012-04-29 00:09:37 +08:00
|
|
|
except OSError as e:
|
2008-08-14 11:57:18 +08:00
|
|
|
if must_create and e.errno == errno.EEXIST:
|
|
|
|
raise CreateError
|
|
|
|
raise
|
2008-08-31 04:50:41 +08:00
|
|
|
|
|
|
|
# Write the session file without interfering with other threads
|
|
|
|
# or processes. By writing to an atomically generated temporary
|
|
|
|
# file and then using the atomic os.rename() to make the complete
|
|
|
|
# file visible, we avoid having to lock the session file, while
|
|
|
|
# still maintaining its integrity.
|
|
|
|
#
|
|
|
|
# Note: Locking the session file was explored, but rejected in part
|
|
|
|
# because in order to be atomic and cross-platform, it required a
|
|
|
|
# long-lived lock file for each session, doubling the number of
|
|
|
|
# files in the session storage directory at any given time. This
|
|
|
|
# rename solution is cleaner and avoids any additional overhead
|
|
|
|
# when reading the session data, which is the more common case
|
|
|
|
# unless SESSION_SAVE_EVERY_REQUEST = True.
|
|
|
|
#
|
|
|
|
# See ticket #8616.
|
|
|
|
dir, prefix = os.path.split(session_file_name)
|
|
|
|
|
|
|
|
try:
|
|
|
|
output_file_fd, output_file_name = tempfile.mkstemp(dir=dir,
|
|
|
|
prefix=prefix + '_out_')
|
2008-09-02 04:25:16 +08:00
|
|
|
renamed = False
|
2008-08-31 04:50:41 +08:00
|
|
|
try:
|
|
|
|
try:
|
2012-08-15 20:19:53 +08:00
|
|
|
os.write(output_file_fd, self.encode(session_data).encode())
|
2008-08-31 04:50:41 +08:00
|
|
|
finally:
|
|
|
|
os.close(output_file_fd)
|
|
|
|
os.rename(output_file_name, session_file_name)
|
|
|
|
renamed = True
|
|
|
|
finally:
|
|
|
|
if not renamed:
|
|
|
|
os.unlink(output_file_name)
|
|
|
|
|
|
|
|
except (OSError, IOError, EOFError):
|
2007-09-16 05:29:14 +08:00
|
|
|
pass
|
|
|
|
|
|
|
|
def exists(self, session_key):
|
2011-09-10 03:33:40 +08:00
|
|
|
return os.path.exists(self._key_to_file(session_key))
|
2008-01-06 20:53:09 +08:00
|
|
|
|
2008-08-14 11:57:46 +08:00
|
|
|
def delete(self, session_key=None):
|
|
|
|
if session_key is None:
|
2011-11-28 01:52:24 +08:00
|
|
|
if self.session_key is None:
|
2008-08-15 22:59:11 +08:00
|
|
|
return
|
2011-11-28 01:52:24 +08:00
|
|
|
session_key = self.session_key
|
2007-09-16 05:29:14 +08:00
|
|
|
try:
|
|
|
|
os.unlink(self._key_to_file(session_key))
|
|
|
|
except OSError:
|
|
|
|
pass
|
2008-01-06 20:53:09 +08:00
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
def clean(self):
|
2007-09-16 10:03:46 +08:00
|
|
|
pass
|
2012-10-28 05:12:08 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def clear_expired(cls):
|
|
|
|
storage_path = getattr(settings, "SESSION_FILE_PATH", tempfile.gettempdir())
|
|
|
|
file_prefix = settings.SESSION_COOKIE_NAME
|
|
|
|
|
|
|
|
for session_file in os.listdir(storage_path):
|
|
|
|
if not session_file.startswith(file_prefix):
|
|
|
|
continue
|
|
|
|
session_key = session_file[len(file_prefix):]
|
|
|
|
session = cls(session_key)
|
|
|
|
# When an expired session is loaded, its file is removed, and a
|
|
|
|
# new file is immediately created. Prevent this by disabling
|
|
|
|
# the create() method.
|
|
|
|
session.create = lambda: None
|
|
|
|
session.load()
|