You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
6.5 KiB

  1. # Copyright 2017 Virgil Dupras
  2. # This software is licensed under the "BSD" License as described in the "LICENSE" file,
  3. # which should be included with this package. The terms are also available at
  4. # http://www.hardcoded.net/licenses/bsd_license
  5. # This is a reimplementation of plat_other.py with reference to the
  6. # freedesktop.org trash specification:
  7. # [1] http://www.freedesktop.org/wiki/Specifications/trash-spec
  8. # [2] http://www.ramendik.ru/docs/trashspec.html
  9. # See also:
  10. # [3] http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  11. #
  12. # For external volumes this implementation will raise an exception if it can't
  13. # find or create the user's trash directory.
  14. from __future__ import unicode_literals
  15. import errno
  16. import sys
  17. import os
  18. import os.path as op
  19. from datetime import datetime
  20. import stat
  21. try:
  22. from urllib.parse import quote
  23. except ImportError:
  24. # Python 2
  25. from urllib import quote
  26. from .compat import text_type, environb
  27. from .exceptions import TrashPermissionError
  28. try:
  29. fsencode = os.fsencode # Python 3
  30. fsdecode = os.fsdecode
  31. except AttributeError:
  32. def fsencode(u): # Python 2
  33. return u.encode(sys.getfilesystemencoding())
  34. def fsdecode(b):
  35. return b.decode(sys.getfilesystemencoding())
  36. # The Python 3 versions are a bit smarter, handling surrogate escapes,
  37. # but these should work in most cases.
  38. FILES_DIR = b"files"
  39. INFO_DIR = b"info"
  40. INFO_SUFFIX = b".trashinfo"
  41. # Default of ~/.local/share [3]
  42. XDG_DATA_HOME = op.expanduser(environb.get(b"XDG_DATA_HOME", b"~/.local/share"))
  43. HOMETRASH_B = op.join(XDG_DATA_HOME, b"Trash")
  44. HOMETRASH = fsdecode(HOMETRASH_B)
  45. uid = os.getuid()
  46. TOPDIR_TRASH = b".Trash"
  47. TOPDIR_FALLBACK = b".Trash-" + text_type(uid).encode("ascii")
  48. def is_parent(parent, path):
  49. path = op.realpath(path) # In case it's a symlink
  50. if isinstance(path, text_type):
  51. path = fsencode(path)
  52. parent = op.realpath(parent)
  53. if isinstance(parent, text_type):
  54. parent = fsencode(parent)
  55. return path.startswith(parent)
  56. def format_date(date):
  57. return date.strftime("%Y-%m-%dT%H:%M:%S")
  58. def info_for(src, topdir):
  59. # ...it MUST not include a ".." directory, and for files not "under" that
  60. # directory, absolute pathnames must be used. [2]
  61. if topdir is None or not is_parent(topdir, src):
  62. src = op.abspath(src)
  63. else:
  64. src = op.relpath(src, topdir)
  65. info = "[Trash Info]\n"
  66. info += "Path=" + quote(src) + "\n"
  67. info += "DeletionDate=" + format_date(datetime.now()) + "\n"
  68. return info
  69. def check_create(dir):
  70. # use 0700 for paths [3]
  71. if not op.exists(dir):
  72. os.makedirs(dir, 0o700)
  73. def trash_move(src, dst, topdir=None):
  74. filename = op.basename(src)
  75. filespath = op.join(dst, FILES_DIR)
  76. infopath = op.join(dst, INFO_DIR)
  77. base_name, ext = op.splitext(filename)
  78. counter = 0
  79. destname = filename
  80. while op.exists(op.join(filespath, destname)) or op.exists(
  81. op.join(infopath, destname + INFO_SUFFIX)
  82. ):
  83. counter += 1
  84. destname = base_name + b" " + text_type(counter).encode("ascii") + ext
  85. check_create(filespath)
  86. check_create(infopath)
  87. with open(op.join(infopath, destname + INFO_SUFFIX), "w") as f:
  88. f.write(info_for(src, topdir))
  89. os.rename(src, op.join(filespath, destname))
  90. def find_mount_point(path):
  91. # Even if something's wrong, "/" is a mount point, so the loop will exit.
  92. # Use realpath in case it's a symlink
  93. path = op.realpath(path) # Required to avoid infinite loop
  94. while not op.ismount(path):
  95. path = op.split(path)[0]
  96. return path
  97. def find_ext_volume_global_trash(volume_root):
  98. # from [2] Trash directories (1) check for a .Trash dir with the right
  99. # permissions set.
  100. trash_dir = op.join(volume_root, TOPDIR_TRASH)
  101. if not op.exists(trash_dir):
  102. return None
  103. mode = os.lstat(trash_dir).st_mode
  104. # vol/.Trash must be a directory, cannot be a symlink, and must have the
  105. # sticky bit set.
  106. if not op.isdir(trash_dir) or op.islink(trash_dir) or not (mode & stat.S_ISVTX):
  107. return None
  108. trash_dir = op.join(trash_dir, text_type(uid).encode("ascii"))
  109. try:
  110. check_create(trash_dir)
  111. except OSError:
  112. return None
  113. return trash_dir
  114. def find_ext_volume_fallback_trash(volume_root):
  115. # from [2] Trash directories (1) create a .Trash-$uid dir.
  116. trash_dir = op.join(volume_root, TOPDIR_FALLBACK)
  117. # Try to make the directory, if we lack permission, raise TrashPermissionError
  118. try:
  119. check_create(trash_dir)
  120. except OSError as e:
  121. if e.errno == errno.EACCES:
  122. raise TrashPermissionError(e.filename)
  123. raise
  124. return trash_dir
  125. def find_ext_volume_trash(volume_root):
  126. trash_dir = find_ext_volume_global_trash(volume_root)
  127. if trash_dir is None:
  128. trash_dir = find_ext_volume_fallback_trash(volume_root)
  129. return trash_dir
  130. # Pull this out so it's easy to stub (to avoid stubbing lstat itself)
  131. def get_dev(path):
  132. return os.lstat(path).st_dev
  133. def send2trash(paths):
  134. if not isinstance(paths, list):
  135. paths = [paths]
  136. for path in paths:
  137. if isinstance(path, text_type):
  138. path_b = fsencode(path)
  139. elif isinstance(path, bytes):
  140. path_b = path
  141. elif hasattr(path, "__fspath__"):
  142. # Python 3.6 PathLike protocol
  143. return send2trash(path.__fspath__())
  144. else:
  145. raise TypeError("str, bytes or PathLike expected, not %r" % type(path))
  146. if not op.exists(path_b):
  147. raise OSError("File not found: %s" % path)
  148. # ...should check whether the user has the necessary permissions to delete
  149. # it, before starting the trashing operation itself. [2]
  150. if not os.access(path_b, os.W_OK):
  151. raise OSError("Permission denied: %s" % path)
  152. # if the file to be trashed is on the same device as HOMETRASH we
  153. # want to move it there.
  154. path_dev = get_dev(path_b)
  155. # If XDG_DATA_HOME or HOMETRASH do not yet exist we need to stat the
  156. # home directory, and these paths will be created further on if needed.
  157. trash_dev = get_dev(op.expanduser(b"~"))
  158. if path_dev == trash_dev:
  159. topdir = XDG_DATA_HOME
  160. dest_trash = HOMETRASH_B
  161. else:
  162. topdir = find_mount_point(path_b)
  163. trash_dev = get_dev(topdir)
  164. if trash_dev != path_dev:
  165. raise OSError("Couldn't find mount point for %s" % path)
  166. dest_trash = find_ext_volume_trash(topdir)
  167. trash_move(path_b, dest_trash, topdir)