file.py 7.5 KB

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