xattr.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. """A basic extended attributes (xattr) implementation for Linux, FreeBSD and MacOS X."""
  2. import errno
  3. import os
  4. import re
  5. import subprocess
  6. import sys
  7. import tempfile
  8. from ctypes import CDLL, create_string_buffer, c_ssize_t, c_size_t, c_char_p, c_int, c_uint32, get_errno
  9. from ctypes.util import find_library
  10. from distutils.version import LooseVersion
  11. from .helpers import Buffer
  12. try:
  13. ENOATTR = errno.ENOATTR
  14. except AttributeError:
  15. # on some platforms, ENOATTR is missing, use ENODATA there
  16. ENOATTR = errno.ENODATA
  17. buffer = Buffer(create_string_buffer, limit=2**24)
  18. def is_enabled(path=None):
  19. """Determine if xattr is enabled on the filesystem
  20. """
  21. with tempfile.NamedTemporaryFile(dir=path, prefix='borg-tmp') as fd:
  22. try:
  23. setxattr(fd.fileno(), 'user.name', b'value')
  24. except OSError:
  25. return False
  26. return getxattr(fd.fileno(), 'user.name') == b'value'
  27. def get_all(path, follow_symlinks=True):
  28. try:
  29. result = {}
  30. names = listxattr(path, follow_symlinks=follow_symlinks)
  31. for name in names:
  32. try:
  33. result[name] = getxattr(path, name, follow_symlinks=follow_symlinks)
  34. except OSError as e:
  35. # if we get ENOATTR, a race has happened: xattr names were deleted after list.
  36. # we just ignore the now missing ones. if you want consistency, do snapshots.
  37. if e.errno != ENOATTR:
  38. raise
  39. return result
  40. except OSError as e:
  41. if e.errno in (errno.ENOTSUP, errno.EPERM):
  42. return {}
  43. libc_name = find_library('c')
  44. if libc_name is None:
  45. # find_library didn't work, maybe we are on some minimal system that misses essential
  46. # tools used by find_library, like ldconfig, gcc/cc, objdump.
  47. # so we can only try some "usual" names for the C library:
  48. if sys.platform.startswith('linux'):
  49. libc_name = 'libc.so.6'
  50. elif sys.platform.startswith(('freebsd', 'netbsd')):
  51. libc_name = 'libc.so'
  52. elif sys.platform == 'darwin':
  53. libc_name = 'libc.dylib'
  54. else:
  55. msg = "Can't find C library. No fallback known. Try installing ldconfig, gcc/cc or objdump."
  56. print(msg, file=sys.stderr) # logger isn't initialized at this stage
  57. raise Exception(msg)
  58. # If we are running with fakeroot on Linux, then use the xattr functions of fakeroot. This is needed by
  59. # the 'test_extract_capabilities' test, but also allows xattrs to work with fakeroot on Linux in normal use.
  60. # TODO: Check whether fakeroot supports xattrs on all platforms supported below.
  61. # TODO: If that's the case then we can make Borg fakeroot-xattr-compatible on these as well.
  62. try:
  63. XATTR_FAKEROOT = False
  64. if sys.platform.startswith('linux'):
  65. LD_PRELOAD = os.environ.get('LD_PRELOAD', '')
  66. preloads = re.split("[ :]", LD_PRELOAD)
  67. for preload in preloads:
  68. if preload.startswith("libfakeroot"):
  69. fakeroot_version = LooseVersion(subprocess.check_output(['fakeroot', '-v']).decode('ascii').split()[-1])
  70. if fakeroot_version >= LooseVersion("1.20.2"):
  71. # 1.20.2 has been confirmed to have xattr support
  72. # 1.18.2 has been confirmed not to have xattr support
  73. # Versions in-between are unknown
  74. libc_name = preload
  75. XATTR_FAKEROOT = True
  76. break
  77. except:
  78. pass
  79. try:
  80. libc = CDLL(libc_name, use_errno=True)
  81. except OSError as e:
  82. msg = "Can't find C library [%s]. Try installing ldconfig, gcc/cc or objdump." % e
  83. raise Exception(msg)
  84. def split_string0(buf):
  85. """split a list of zero-terminated strings into python not-zero-terminated bytes"""
  86. return buf.split(b'\0')[:-1]
  87. def split_lstring(buf):
  88. """split a list of length-prefixed strings into python not-length-prefixed bytes"""
  89. result = []
  90. mv = memoryview(buf)
  91. while mv:
  92. length = mv[0]
  93. result.append(bytes(mv[1:1 + length]))
  94. mv = mv[1 + length:]
  95. return result
  96. class BufferTooSmallError(Exception):
  97. """the buffer given to an xattr function was too small for the result"""
  98. def _check(rv, path=None, detect_buffer_too_small=False):
  99. if rv < 0:
  100. e = get_errno()
  101. if detect_buffer_too_small and e == errno.ERANGE:
  102. # listxattr and getxattr signal with ERANGE that they need a bigger result buffer.
  103. # setxattr signals this way that e.g. a xattr key name is too long / inacceptable.
  104. raise BufferTooSmallError
  105. else:
  106. try:
  107. msg = os.strerror(e)
  108. except ValueError:
  109. msg = ''
  110. if isinstance(path, int):
  111. path = '<FD %d>' % path
  112. raise OSError(e, msg, path)
  113. if detect_buffer_too_small and rv >= len(buffer):
  114. # freebsd does not error with ERANGE if the buffer is too small,
  115. # it just fills the buffer, truncates and returns.
  116. # so, we play sure and just assume that result is truncated if
  117. # it happens to be a full buffer.
  118. raise BufferTooSmallError
  119. return rv
  120. def _listxattr_inner(func, path):
  121. if isinstance(path, str):
  122. path = os.fsencode(path)
  123. size = len(buffer)
  124. while True:
  125. buf = buffer.get(size)
  126. try:
  127. n = _check(func(path, buf, size), path, detect_buffer_too_small=True)
  128. except BufferTooSmallError:
  129. size *= 2
  130. else:
  131. return n, buf.raw
  132. def _getxattr_inner(func, path, name):
  133. if isinstance(path, str):
  134. path = os.fsencode(path)
  135. name = os.fsencode(name)
  136. size = len(buffer)
  137. while True:
  138. buf = buffer.get(size)
  139. try:
  140. n = _check(func(path, name, buf, size), path, detect_buffer_too_small=True)
  141. except BufferTooSmallError:
  142. size *= 2
  143. else:
  144. return n, buf.raw
  145. def _setxattr_inner(func, path, name, value):
  146. if isinstance(path, str):
  147. path = os.fsencode(path)
  148. name = os.fsencode(name)
  149. value = value and os.fsencode(value)
  150. size = len(value) if value else 0
  151. _check(func(path, name, value, size), path, detect_buffer_too_small=False)
  152. if sys.platform.startswith('linux'): # pragma: linux only
  153. libc.llistxattr.argtypes = (c_char_p, c_char_p, c_size_t)
  154. libc.llistxattr.restype = c_ssize_t
  155. libc.flistxattr.argtypes = (c_int, c_char_p, c_size_t)
  156. libc.flistxattr.restype = c_ssize_t
  157. libc.lsetxattr.argtypes = (c_char_p, c_char_p, c_char_p, c_size_t, c_int)
  158. libc.lsetxattr.restype = c_int
  159. libc.fsetxattr.argtypes = (c_int, c_char_p, c_char_p, c_size_t, c_int)
  160. libc.fsetxattr.restype = c_int
  161. libc.lgetxattr.argtypes = (c_char_p, c_char_p, c_char_p, c_size_t)
  162. libc.lgetxattr.restype = c_ssize_t
  163. libc.fgetxattr.argtypes = (c_int, c_char_p, c_char_p, c_size_t)
  164. libc.fgetxattr.restype = c_ssize_t
  165. def listxattr(path, *, follow_symlinks=True):
  166. def func(path, buf, size):
  167. if isinstance(path, int):
  168. return libc.flistxattr(path, buf, size)
  169. else:
  170. if follow_symlinks:
  171. return libc.listxattr(path, buf, size)
  172. else:
  173. return libc.llistxattr(path, buf, size)
  174. n, buf = _listxattr_inner(func, path)
  175. return [os.fsdecode(name) for name in split_string0(buf[:n])
  176. if not name.startswith(b'system.posix_acl_')]
  177. def getxattr(path, name, *, follow_symlinks=True):
  178. def func(path, name, buf, size):
  179. if isinstance(path, int):
  180. return libc.fgetxattr(path, name, buf, size)
  181. else:
  182. if follow_symlinks:
  183. return libc.getxattr(path, name, buf, size)
  184. else:
  185. return libc.lgetxattr(path, name, buf, size)
  186. n, buf = _getxattr_inner(func, path, name)
  187. return buf[:n] or None
  188. def setxattr(path, name, value, *, follow_symlinks=True):
  189. def func(path, name, value, size):
  190. flags = 0
  191. if isinstance(path, int):
  192. return libc.fsetxattr(path, name, value, size, flags)
  193. else:
  194. if follow_symlinks:
  195. return libc.setxattr(path, name, value, size, flags)
  196. else:
  197. return libc.lsetxattr(path, name, value, size, flags)
  198. _setxattr_inner(func, path, name, value)
  199. elif sys.platform == 'darwin': # pragma: darwin only
  200. libc.listxattr.argtypes = (c_char_p, c_char_p, c_size_t, c_int)
  201. libc.listxattr.restype = c_ssize_t
  202. libc.flistxattr.argtypes = (c_int, c_char_p, c_size_t)
  203. libc.flistxattr.restype = c_ssize_t
  204. libc.setxattr.argtypes = (c_char_p, c_char_p, c_char_p, c_size_t, c_uint32, c_int)
  205. libc.setxattr.restype = c_int
  206. libc.fsetxattr.argtypes = (c_int, c_char_p, c_char_p, c_size_t, c_uint32, c_int)
  207. libc.fsetxattr.restype = c_int
  208. libc.getxattr.argtypes = (c_char_p, c_char_p, c_char_p, c_size_t, c_uint32, c_int)
  209. libc.getxattr.restype = c_ssize_t
  210. libc.fgetxattr.argtypes = (c_int, c_char_p, c_char_p, c_size_t, c_uint32, c_int)
  211. libc.fgetxattr.restype = c_ssize_t
  212. XATTR_NOFLAGS = 0x0000
  213. XATTR_NOFOLLOW = 0x0001
  214. def listxattr(path, *, follow_symlinks=True):
  215. def func(path, buf, size):
  216. if isinstance(path, int):
  217. return libc.flistxattr(path, buf, size, XATTR_NOFLAGS)
  218. else:
  219. if follow_symlinks:
  220. return libc.listxattr(path, buf, size, XATTR_NOFLAGS)
  221. else:
  222. return libc.listxattr(path, buf, size, XATTR_NOFOLLOW)
  223. n, buf = _listxattr_inner(func, path)
  224. return [os.fsdecode(name) for name in split_string0(buf[:n])]
  225. def getxattr(path, name, *, follow_symlinks=True):
  226. def func(path, name, buf, size):
  227. if isinstance(path, int):
  228. return libc.fgetxattr(path, name, buf, size, 0, XATTR_NOFLAGS)
  229. else:
  230. if follow_symlinks:
  231. return libc.getxattr(path, name, buf, size, 0, XATTR_NOFLAGS)
  232. else:
  233. return libc.getxattr(path, name, buf, size, 0, XATTR_NOFOLLOW)
  234. n, buf = _getxattr_inner(func, path, name)
  235. return buf[:n] or None
  236. def setxattr(path, name, value, *, follow_symlinks=True):
  237. def func(path, name, value, size):
  238. if isinstance(path, int):
  239. return libc.fsetxattr(path, name, value, size, 0, XATTR_NOFLAGS)
  240. else:
  241. if follow_symlinks:
  242. return libc.setxattr(path, name, value, size, 0, XATTR_NOFLAGS)
  243. else:
  244. return libc.setxattr(path, name, value, size, 0, XATTR_NOFOLLOW)
  245. _setxattr_inner(func, path, name, value)
  246. elif sys.platform.startswith('freebsd'): # pragma: freebsd only
  247. libc.extattr_list_fd.argtypes = (c_int, c_int, c_char_p, c_size_t)
  248. libc.extattr_list_fd.restype = c_ssize_t
  249. libc.extattr_list_link.argtypes = (c_char_p, c_int, c_char_p, c_size_t)
  250. libc.extattr_list_link.restype = c_ssize_t
  251. libc.extattr_list_file.argtypes = (c_char_p, c_int, c_char_p, c_size_t)
  252. libc.extattr_list_file.restype = c_ssize_t
  253. libc.extattr_get_fd.argtypes = (c_int, c_int, c_char_p, c_char_p, c_size_t)
  254. libc.extattr_get_fd.restype = c_ssize_t
  255. libc.extattr_get_link.argtypes = (c_char_p, c_int, c_char_p, c_char_p, c_size_t)
  256. libc.extattr_get_link.restype = c_ssize_t
  257. libc.extattr_get_file.argtypes = (c_char_p, c_int, c_char_p, c_char_p, c_size_t)
  258. libc.extattr_get_file.restype = c_ssize_t
  259. libc.extattr_set_fd.argtypes = (c_int, c_int, c_char_p, c_char_p, c_size_t)
  260. libc.extattr_set_fd.restype = c_int
  261. libc.extattr_set_link.argtypes = (c_char_p, c_int, c_char_p, c_char_p, c_size_t)
  262. libc.extattr_set_link.restype = c_int
  263. libc.extattr_set_file.argtypes = (c_char_p, c_int, c_char_p, c_char_p, c_size_t)
  264. libc.extattr_set_file.restype = c_int
  265. ns = EXTATTR_NAMESPACE_USER = 0x0001
  266. def listxattr(path, *, follow_symlinks=True):
  267. def func(path, buf, size):
  268. if isinstance(path, int):
  269. return libc.extattr_list_fd(path, ns, buf, size)
  270. else:
  271. if follow_symlinks:
  272. return libc.extattr_list_file(path, ns, buf, size)
  273. else:
  274. return libc.extattr_list_link(path, ns, buf, size)
  275. n, buf = _listxattr_inner(func, path)
  276. return [os.fsdecode(name) for name in split_lstring(buf[:n])]
  277. def getxattr(path, name, *, follow_symlinks=True):
  278. def func(path, name, buf, size):
  279. if isinstance(path, int):
  280. return libc.extattr_get_fd(path, ns, name, buf, size)
  281. else:
  282. if follow_symlinks:
  283. return libc.extattr_get_file(path, ns, name, buf, size)
  284. else:
  285. return libc.extattr_get_link(path, ns, name, buf, size)
  286. n, buf = _getxattr_inner(func, path, name)
  287. return buf[:n] or None
  288. def setxattr(path, name, value, *, follow_symlinks=True):
  289. def func(path, name, value, size):
  290. if isinstance(path, int):
  291. return libc.extattr_set_fd(path, ns, name, value, size)
  292. else:
  293. if follow_symlinks:
  294. return libc.extattr_set_file(path, ns, name, value, size)
  295. else:
  296. return libc.extattr_set_link(path, ns, name, value, size)
  297. _setxattr_inner(func, path, name, value)
  298. else: # pragma: unknown platform only
  299. def listxattr(path, *, follow_symlinks=True):
  300. return []
  301. def getxattr(path, name, *, follow_symlinks=True):
  302. pass
  303. def setxattr(path, name, value, *, follow_symlinks=True):
  304. pass