plat_other.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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(op.join(infopath, destname + INFO_SUFFIX)):
  81. counter += 1
  82. destname = base_name + b' ' + text_type(counter).encode('ascii') + ext
  83. check_create(filespath)
  84. check_create(infopath)
  85. os.rename(src, op.join(filespath, destname))
  86. f = open(op.join(infopath, destname + INFO_SUFFIX), 'w')
  87. f.write(info_for(src, topdir))
  88. f.close()
  89. def find_mount_point(path):
  90. # Even if something's wrong, "/" is a mount point, so the loop will exit.
  91. # Use realpath in case it's a symlink
  92. path = op.realpath(path) # Required to avoid infinite loop
  93. while not op.ismount(path):
  94. path = op.split(path)[0]
  95. return path
  96. def find_ext_volume_global_trash(volume_root):
  97. # from [2] Trash directories (1) check for a .Trash dir with the right
  98. # permissions set.
  99. trash_dir = op.join(volume_root, TOPDIR_TRASH)
  100. if not op.exists(trash_dir):
  101. return None
  102. mode = os.lstat(trash_dir).st_mode
  103. # vol/.Trash must be a directory, cannot be a symlink, and must have the
  104. # sticky bit set.
  105. if not op.isdir(trash_dir) or op.islink(trash_dir) or not (mode & stat.S_ISVTX):
  106. return None
  107. trash_dir = op.join(trash_dir, text_type(uid).encode('ascii'))
  108. try:
  109. check_create(trash_dir)
  110. except OSError:
  111. return None
  112. return trash_dir
  113. def find_ext_volume_fallback_trash(volume_root):
  114. # from [2] Trash directories (1) create a .Trash-$uid dir.
  115. trash_dir = op.join(volume_root, TOPDIR_FALLBACK)
  116. # Try to make the directory, if we lack permission, raise TrashPermissionError
  117. try:
  118. check_create(trash_dir)
  119. except OSError as e:
  120. if e.errno == errno.EACCES:
  121. raise TrashPermissionError(e.filename)
  122. raise
  123. return trash_dir
  124. def find_ext_volume_trash(volume_root):
  125. trash_dir = find_ext_volume_global_trash(volume_root)
  126. if trash_dir is None:
  127. trash_dir = find_ext_volume_fallback_trash(volume_root)
  128. return trash_dir
  129. # Pull this out so it's easy to stub (to avoid stubbing lstat itself)
  130. def get_dev(path):
  131. return os.lstat(path).st_dev
  132. def send2trash(path):
  133. if isinstance(path, text_type):
  134. path_b = fsencode(path)
  135. elif isinstance(path, bytes):
  136. path_b = path
  137. elif hasattr(path, '__fspath__'):
  138. # Python 3.6 PathLike protocol
  139. return send2trash(path.__fspath__())
  140. else:
  141. raise TypeError('str, bytes or PathLike expected, not %r' % type(path))
  142. if not op.exists(path_b):
  143. raise OSError("File not found: %s" % path)
  144. # ...should check whether the user has the necessary permissions to delete
  145. # it, before starting the trashing operation itself. [2]
  146. if not os.access(path_b, os.W_OK):
  147. raise OSError("Permission denied: %s" % path)
  148. # if the file to be trashed is on the same device as HOMETRASH we
  149. # want to move it there.
  150. path_dev = get_dev(path_b)
  151. # If XDG_DATA_HOME or HOMETRASH do not yet exist we need to stat the
  152. # home directory, and these paths will be created further on if needed.
  153. trash_dev = get_dev(op.expanduser(b'~'))
  154. if path_dev == trash_dev:
  155. topdir = XDG_DATA_HOME
  156. dest_trash = HOMETRASH_B
  157. else:
  158. topdir = find_mount_point(path_b)
  159. trash_dev = get_dev(topdir)
  160. if trash_dev != path_dev:
  161. raise OSError("Couldn't find mount point for %s" % path)
  162. dest_trash = find_ext_volume_trash(topdir)
  163. trash_move(path_b, dest_trash, topdir)