| 1 |
import datetime |
| 2 |
import logging |
| 3 |
import os |
| 4 |
import shutil |
| 5 |
import tempfile |
| 6 |
|
| 7 |
from django.conf import settings |
| 8 |
from django.contrib.sessions.backends.base import ( |
| 9 |
VALID_KEY_CHARS, |
| 10 |
CreateError, |
| 11 |
SessionBase, |
| 12 |
UpdateError, |
| 13 |
) |
| 14 |
from django.contrib.sessions.exceptions import InvalidSessionKey |
| 15 |
from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation |
| 16 |
|
| 17 |
|
| 18 |
class SessionStore(SessionBase): |
| 19 |
""" |
| 20 |
Implement a file based session store. |
| 21 |
""" |
| 22 |
|
| 23 |
def __init__(self, session_key=None): |
| 24 |
self.storage_path = self._get_storage_path() |
| 25 |
self.file_prefix = settings.SESSION_COOKIE_NAME |
| 26 |
super().__init__(session_key) |
| 27 |
|
| 28 |
@classmethod |
| 29 |
def _get_storage_path(cls): |
| 30 |
try: |
| 31 |
return cls._storage_path |
| 32 |
except AttributeError: |
| 33 |
storage_path = ( |
| 34 |
getattr(settings, "SESSION_FILE_PATH", None) or tempfile.gettempdir() |
| 35 |
) |
| 36 |
# Make sure the storage path is valid. |
| 37 |
if not os.path.isdir(storage_path): |
| 38 |
raise ImproperlyConfigured( |
| 39 |
"The session storage path %r doesn't exist. Please set your" |
| 40 |
" SESSION_FILE_PATH setting to an existing directory in which" |
| 41 |
" Django can store session data." % storage_path |
| 42 |
) |
| 43 |
|
| 44 |
cls._storage_path = storage_path |
| 45 |
return storage_path |
| 46 |
|
| 47 |
def _key_to_file(self, session_key=None): |
| 48 |
""" |
| 49 |
Get the file associated with this session key. |
| 50 |
""" |
| 51 |
if session_key is None: |
| 52 |
session_key = self._get_or_create_session_key() |
| 53 |
|
| 54 |
# Make sure we're not vulnerable to directory traversal. Session keys |
| 55 |
# should always be md5s, so they should never contain directory |
| 56 |
# components. |
| 57 |
if not set(session_key).issubset(VALID_KEY_CHARS): |
| 58 |
raise InvalidSessionKey("Invalid characters in session key") |
| 59 |
|
| 60 |
return os.path.join(self.storage_path, self.file_prefix + session_key) |
| 61 |
|
| 62 |
def _last_modification(self): |
| 63 |
""" |
| 64 |
Return the modification time of the file storing the session's content. |
| 65 |
""" |
| 66 |
modification = os.stat(self._key_to_file()).st_mtime |
| 67 |
tz = datetime.timezone.utc if settings.USE_TZ else None |
| 68 |
return datetime.datetime.fromtimestamp(modification, tz=tz) |
| 69 |
|
| 70 |
def _expiry_date(self, session_data): |
| 71 |
""" |
| 72 |
Return the expiry time of the file storing the session's content. |
| 73 |
""" |
| 74 |
return session_data.get("_session_expiry") or ( |
| 75 |
self._last_modification() |
| 76 |
+ datetime.timedelta(seconds=self.get_session_cookie_age()) |
| 77 |
) |
| 78 |
|
| 79 |
def load(self): |
| 80 |
session_data = {} |
| 81 |
try: |
| 82 |
with open(self._key_to_file(), encoding="ascii") as session_file: |
| 83 |
file_data = session_file.read() |
| 84 |
# Don't fail if there is no data in the session file. |
| 85 |
# We may have opened the empty placeholder file. |
| 86 |
if file_data: |
| 87 |
try: |
| 88 |
session_data = self.decode(file_data) |
| 89 |
except (EOFError, SuspiciousOperation) as e: |
| 90 |
if isinstance(e, SuspiciousOperation): |
| 91 |
logger = logging.getLogger( |
| 92 |
"django.security.%s" % e.__class__.__name__ |
| 93 |
) |
| 94 |
logger.warning(str(e)) |
| 95 |
self.create() |
| 96 |
|
| 97 |
# Remove expired sessions. |
| 98 |
expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data)) |
| 99 |
if expiry_age <= 0: |
| 100 |
session_data = {} |
| 101 |
self.delete() |
| 102 |
self.create() |
| 103 |
except (OSError, SuspiciousOperation): |
| 104 |
self._session_key = None |
| 105 |
return session_data |
| 106 |
|
| 107 |
async def aload(self): |
| 108 |
return self.load() |
| 109 |
|
| 110 |
def create(self): |
| 111 |
while True: |
| 112 |
self._session_key = self._get_new_session_key() |
| 113 |
try: |
| 114 |
self.save(must_create=True) |
| 115 |
except CreateError: |
| 116 |
continue |
| 117 |
self.modified = True |
| 118 |
return |
| 119 |
|
| 120 |
async def acreate(self): |
| 121 |
return self.create() |
| 122 |
|
| 123 |
def save(self, must_create=False): |
| 124 |
if self.session_key is None: |
| 125 |
return self.create() |
| 126 |
# Get the session data now, before we start messing |
| 127 |
# with the file it is stored within. |
| 128 |
session_data = self._get_session(no_load=must_create) |
| 129 |
|
| 130 |
session_file_name = self._key_to_file() |
| 131 |
|
| 132 |
try: |
| 133 |
# Make sure the file exists. If it does not already exist, an |
| 134 |
# empty placeholder file is created. |
| 135 |
flags = os.O_WRONLY | getattr(os, "O_BINARY", 0) |
| 136 |
if must_create: |
| 137 |
flags |= os.O_EXCL | os.O_CREAT |
| 138 |
fd = os.open(session_file_name, flags) |
| 139 |
os.close(fd) |
| 140 |
except FileNotFoundError: |
| 141 |
if not must_create: |
| 142 |
raise UpdateError |
| 143 |
except FileExistsError: |
| 144 |
if must_create: |
| 145 |
raise CreateError |
| 146 |
|
| 147 |
# Write the session file without interfering with other threads |
| 148 |
# or processes. By writing to an atomically generated temporary |
| 149 |
# file and then using the atomic os.rename() to make the complete |
| 150 |
# file visible, we avoid having to lock the session file, while |
| 151 |
# still maintaining its integrity. |
| 152 |
# |
| 153 |
# Note: Locking the session file was explored, but rejected in part |
| 154 |
# because in order to be atomic and cross-platform, it required a |
| 155 |
# long-lived lock file for each session, doubling the number of |
| 156 |
# files in the session storage directory at any given time. This |
| 157 |
# rename solution is cleaner and avoids any additional overhead |
| 158 |
# when reading the session data, which is the more common case |
| 159 |
# unless SESSION_SAVE_EVERY_REQUEST = True. |
| 160 |
# |
| 161 |
# See ticket #8616. |
| 162 |
dir, prefix = os.path.split(session_file_name) |
| 163 |
|
| 164 |
try: |
| 165 |
output_file_fd, output_file_name = tempfile.mkstemp( |
| 166 |
dir=dir, prefix=prefix + "_out_" |
| 167 |
) |
| 168 |
renamed = False |
| 169 |
try: |
| 170 |
try: |
| 171 |
os.write(output_file_fd, self.encode(session_data).encode()) |
| 172 |
finally: |
| 173 |
os.close(output_file_fd) |
| 174 |
|
| 175 |
# This will atomically rename the file (os.rename) if the OS |
| 176 |
# supports it. Otherwise this will result in a shutil.copy2 |
| 177 |
# and os.unlink (for example on Windows). See #9084. |
| 178 |
shutil.move(output_file_name, session_file_name) |
| 179 |
renamed = True |
| 180 |
finally: |
| 181 |
if not renamed: |
| 182 |
os.unlink(output_file_name) |
| 183 |
except (EOFError, OSError): |
| 184 |
pass |
| 185 |
|
| 186 |
async def asave(self, must_create=False): |
| 187 |
return self.save(must_create=must_create) |
| 188 |
|
| 189 |
def exists(self, session_key): |
| 190 |
return os.path.exists(self._key_to_file(session_key)) |
| 191 |
|
| 192 |
async def aexists(self, session_key): |
| 193 |
return self.exists(session_key) |
| 194 |
|
| 195 |
def delete(self, session_key=None): |
| 196 |
if session_key is None: |
| 197 |
if self.session_key is None: |
| 198 |
return |
| 199 |
session_key = self.session_key |
| 200 |
try: |
| 201 |
os.unlink(self._key_to_file(session_key)) |
| 202 |
except OSError: |
| 203 |
pass |
| 204 |
|
| 205 |
async def adelete(self, session_key=None): |
| 206 |
return self.delete(session_key=session_key) |
| 207 |
|
| 208 |
@classmethod |
| 209 |
def clear_expired(cls): |
| 210 |
storage_path = cls._get_storage_path() |
| 211 |
file_prefix = settings.SESSION_COOKIE_NAME |
| 212 |
|
| 213 |
for session_file in os.listdir(storage_path): |
| 214 |
if not session_file.startswith(file_prefix): |
| 215 |
continue |
| 216 |
session_key = session_file.removeprefix(file_prefix) |
| 217 |
session = cls(session_key) |
| 218 |
# When an expired session is loaded, its file is removed, and a |
| 219 |
# new file is immediately created. Prevent this by disabling |
| 220 |
# the create() method. |
| 221 |
session.create = lambda: None |
| 222 |
session.load() |
| 223 |
|
| 224 |
@classmethod |
| 225 |
async def aclear_expired(cls): |
| 226 |
cls.clear_expired() |