2 xattr - a python module for manipulating filesystem extended attributes
4 Copyright (C) 2002, 2003, 2006, 2008, 2012, 2013, 2015
5 Iustin Pop <iustin@k1024.org>
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with this library; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 #define PY_SSIZE_T_CLEAN
26 #if defined(__APPLE__) || defined(__linux__)
27 #include <sys/xattr.h>
31 /* Compatibility with python 2.4 regarding python size type (PEP 353) */
32 #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
33 typedef int Py_ssize_t;
34 #define PY_SSIZE_T_MAX INT_MAX
35 #define PY_SSIZE_T_MIN INT_MIN
38 #if PY_MAJOR_VERSION >= 3
40 #define BYTES_CHAR "y"
41 #define BYTES_TUPLE "yy#"
43 #define BYTES_CHAR "s"
44 #define BYTES_TUPLE "ss#"
45 #define PyBytes_Check PyString_Check
46 #define PyBytes_AS_STRING PyString_AS_STRING
47 #define PyBytes_FromStringAndSize PyString_FromStringAndSize
48 #define PyBytes_FromString PyString_FromString
52 ":param item: a string representing a file-name, or a file-like\n" \
53 " object, or a file descriptor; this represents the file on \n" \
56 #define NOFOLLOW_DOC \
57 ":param nofollow: if true and if\n" \
58 " the file name given is a symbolic link, the\n" \
59 " function will operate on the symbolic link itself instead\n" \
60 " of its target; defaults to false\n" \
61 ":type nofollow: boolean, optional\n" \
64 ":param namespace: if given, the attribute must not contain the\n" \
65 " namespace, but instead it will be taken from this parameter\n" \
66 ":type namespace: bytes\n"
68 #define NAME_GET_DOC \
69 ":param string name: the attribute whose value to retrieve;\n" \
70 " usually in the form of ``system.posix_acl`` or ``user.mime_type``\n"
72 #define NAME_SET_DOC \
73 ":param string name: the attribute whose value to set;\n" \
74 " usually in the form of ``system.posix_acl`` or ``user.mime_type``\n"
76 #define NAME_REMOVE_DOC \
77 ":param string name: the attribute to remove;\n" \
78 " usually in the form of ``system.posix_acl`` or \n" \
79 " ``user.mime_type``\n"
82 ":param string value: possibly with embedded NULLs; note that there\n" \
83 " are restrictions regarding the size of the value, for\n" \
84 " example, for ext2/ext3, maximum size is the block size\n" \
87 ":param flags: if 0 or omitted the attribute will be\n" \
88 " created or replaced; if :const:`XATTR_CREATE`, the attribute\n" \
89 " will be created, giving an error if it already exists;\n" \
90 " if :const:`XATTR_REPLACE`, the attribute will be replaced,\n" \
91 " giving an error if it doesn't exist;\n" \
92 ":type flags: integer\n"
94 #define NS_CHANGED_DOC \
95 ".. versionchanged:: 0.5.1\n" \
96 " The namespace argument, if passed, cannot be None anymore; to\n" \
97 " explicitly specify an empty namespace, pass an empty\n" \
98 " string (byte string under Python 3)."
101 /* The initial I/O buffer size for list and get operations; if the
102 * actual values will be smaller than this, we save a syscall out of
103 * two and allocate more memory upfront than needed, otherwise we
104 * incur three syscalls (get with ENORANGE, get with 0 to compute
105 * actual size, final get). The test suite is marginally faster (5%)
106 * with this, so it seems worth doing.
108 #define ESTIMATE_ATTR_SIZE 1024
110 typedef enum {T_FD, T_PATH, T_LINK} target_e;
121 /* Cleans up a tgt structure */
122 static void free_tgt(target_t *tgt) {
123 if (tgt->tmp != NULL) {
128 /* Used for cpychecker: */
129 /* The checker automatically defines this preprocessor name when creating
130 the custom attribute: */
131 #if defined(WITH_CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION_ATTRIBUTE)
132 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION \
133 __attribute__((cpychecker_negative_result_sets_exception))
135 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
138 static int convert_obj(PyObject *myobj, target_t *tgt, int nofollow)
139 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
141 static int merge_ns(const char *ns, const char *name,
142 const char **result, char **buf)
143 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
146 /** Converts from a string, file or int argument to what we need.
148 * Returns -1 on failure, 0 on success.
150 static int convert_obj(PyObject *myobj, target_t *tgt, int nofollow) {
153 if(PyBytes_Check(myobj)) {
154 tgt->type = nofollow ? T_LINK : T_PATH;
155 tgt->name = PyBytes_AS_STRING(myobj);
156 } else if(PyUnicode_Check(myobj)) {
157 tgt->type = nofollow ? T_LINK : T_PATH;
159 PyUnicode_AsEncodedString(myobj,
160 Py_FileSystemDefaultEncoding,
169 tgt->name = PyBytes_AS_STRING(tgt->tmp);
170 } else if((fd = PyObject_AsFileDescriptor(myobj)) != -1) {
174 PyErr_SetString(PyExc_TypeError, "argument must be string or int");
182 /* Combine a namespace string and an attribute name into a
183 fully-qualified name */
184 static int merge_ns(const char *ns, const char *name,
185 const char **result, char **buf) {
186 if(ns != NULL && *ns != '\0') {
188 /* The value of new_size is related to/must be kept in-sync
189 with the format string below */
190 size_t new_size = strlen(ns) + 1 + strlen(name) + 1;
191 if((*buf = PyMem_Malloc(new_size)) == NULL) {
195 cnt = snprintf(*buf, new_size, "%s.%s", ns, name);
196 if((size_t) cnt >= new_size || cnt < 0) {
197 PyErr_SetString(PyExc_ValueError,
198 "unexpected: can't format the attribute name");
210 #if defined(__APPLE__)
211 static inline ssize_t _listxattr(const char *path, char *namebuf, size_t size) {
212 return listxattr(path, namebuf, size, 0);
214 static inline ssize_t _llistxattr(const char *path, char *namebuf, size_t size) {
215 return listxattr(path, namebuf, size, XATTR_NOFOLLOW);
217 static inline ssize_t _flistxattr(int fd, char *namebuf, size_t size) {
218 return flistxattr(fd, namebuf, size, 0);
221 static inline ssize_t _getxattr (const char *path, const char *name, void *value, size_t size) {
222 return getxattr(path, name, value, size, 0, 0);
224 static inline ssize_t _lgetxattr (const char *path, const char *name, void *value, size_t size) {
225 return getxattr(path, name, value, size, 0, XATTR_NOFOLLOW);
227 static inline ssize_t _fgetxattr (int filedes, const char *name, void *value, size_t size) {
228 return fgetxattr(filedes, name, value, size, 0, 0);
231 // [fl]setxattr: Both OS X and Linux define XATTR_CREATE and XATTR_REPLACE for the last option.
232 static inline int _setxattr(const char *path, const char *name, const void *value, size_t size, int flags) {
233 return setxattr(path, name, value, size, 0, flags);
235 static inline int _lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags) {
236 return setxattr(path, name, value, size, 0, flags & XATTR_NOFOLLOW);
238 static inline int _fsetxattr(int filedes, const char *name, const void *value, size_t size, int flags) {
239 return fsetxattr(filedes, name, value, size, 0, flags);
242 static inline int _removexattr(const char *path, const char *name) {
243 return removexattr(path, name, 0);
245 static inline int _lremovexattr(const char *path, const char *name) {
246 return removexattr(path, name, XATTR_NOFOLLOW);
248 static inline int _fremovexattr(int filedes, const char *name) {
249 return fremovexattr(filedes, name, 0);
252 #elif defined(__linux__)
253 #define _listxattr(path, list, size) listxattr(path, list, size)
254 #define _llistxattr(path, list, size) llistxattr(path, list, size)
255 #define _flistxattr(fd, list, size) flistxattr(fd, list, size)
257 #define _getxattr(path, name, value, size) getxattr(path, name, value, size)
258 #define _lgetxattr(path, name, value, size) lgetxattr(path, name, value, size)
259 #define _fgetxattr(fd, name, value, size) fgetxattr(fd, name, value, size)
261 #define _setxattr(path, name, value, size, flags) setxattr(path, name, value, size, flags)
262 #define _lsetxattr(path, name, value, size, flags) lsetxattr(path, name, value, size, flags)
263 #define _fsetxattr(fd, name, value, size, flags) fsetxattr(fd, name, value, size, flags)
265 #define _removexattr(path, name) removexattr(path, name)
266 #define _lremovexattr(path, name) lremovexattr(path, name)
267 #define _fremovexattr(fd, name) fremovexattr(fd, name)
271 typedef ssize_t (*buf_getter)(target_t *tgt, const char *name,
272 void *output, size_t size);
274 static ssize_t _list_obj(target_t *tgt, const char *unused, void *list,
276 if(tgt->type == T_FD)
277 return _flistxattr(tgt->fd, list, size);
278 else if (tgt->type == T_LINK)
279 return _llistxattr(tgt->name, list, size);
281 return _listxattr(tgt->name, list, size);
284 static ssize_t _get_obj(target_t *tgt, const char *name, void *value,
286 if(tgt->type == T_FD)
287 return _fgetxattr(tgt->fd, name, value, size);
288 else if (tgt->type == T_LINK)
289 return _lgetxattr(tgt->name, name, value, size);
291 return _getxattr(tgt->name, name, value, size);
294 static int _set_obj(target_t *tgt, const char *name,
295 const void *value, size_t size, int flags) {
296 if(tgt->type == T_FD)
297 return _fsetxattr(tgt->fd, name, value, size, flags);
298 else if (tgt->type == T_LINK)
299 return _lsetxattr(tgt->name, name, value, size, flags);
301 return _setxattr(tgt->name, name, value, size, flags);
304 static int _remove_obj(target_t *tgt, const char *name) {
305 if(tgt->type == T_FD)
306 return _fremovexattr(tgt->fd, name);
307 else if (tgt->type == T_LINK)
308 return _lremovexattr(tgt->name, name);
310 return _removexattr(tgt->name, name);
313 /* Perform a get/list operation with appropriate buffer size,
314 * determined dynamically.
317 * - getter: the function that actually does the I/O.
318 * - tgt, name: passed to the getter.
319 * - buffer: pointer to either an already allocated memory area (in
320 * which case size contains its current size), or NULL to
321 * allocate. In all cases (success or failure), the caller should
322 * deallocate the buffer, using PyMem_Free(). Note that if size is
323 * zero but buffer already points to allocate memory, it will be
325 * - size: either size of current buffer (if non-NULL), or size for
326 * initial allocation (if non-zero), or a zero value which means
327 * auto-allocate buffer with automatically queried size. Value will
328 * be updated upon return with the current buffer size.
329 * - io_errno: if non-NULL, the actual errno will be recorded here; if
330 * zero, the call was successful and the output/size/nval are valid.
332 * Return value: if positive or zero, buffer will contain the read
333 * value. Otherwise, io_errno will contain the I/O errno, or zero
334 * to signify a Python-level error. In all cases, the Python-level
335 * error is set to the appropriate value.
337 static ssize_t _generic_get(buf_getter getter, target_t *tgt,
342 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
344 static ssize_t _generic_get(buf_getter getter, target_t *tgt,
350 /* Clear errno for now, will only set it when it fails in I/O. */
351 if (io_errno != NULL) {
355 #define EXIT_IOERROR() \
357 if (io_errno != NULL) { \
360 PyErr_SetFromErrno(PyExc_IOError); \
364 /* Initialize the buffer, if needed. */
365 if (*size == 0 || *buffer == NULL) {
368 if ((nalloc = getter(tgt, name, NULL, 0)) == -1) {
372 /* Empty, so no need to retrieve it. */
377 if((*buffer = PyMem_Malloc(*size)) == NULL) {
382 // Try to get the value, while increasing the buffer if too small.
383 while((res = getter(tgt, name, *buffer, *size)) == -1) {
384 if(errno == ERANGE) {
385 ssize_t realloc_size_s = getter(tgt, name, NULL, 0);
386 /* ERANGE + proper size _should_ not fail, but... */
387 if(realloc_size_s == -1) {
390 size_t realloc_size = (size_t) realloc_size_s;
392 if((tmp_buf = PyMem_Realloc(*buffer, realloc_size)) == NULL) {
397 *size = realloc_size;
400 /* else we're dealing with a different error, which we
401 don't know how to handle nicely, so we return */
410 Checks if an attribute name matches an optional namespace.
412 If the namespace is NULL or an empty string, it will return the
413 name itself. If the namespace is non-NULL and the name matches, it
414 will return a pointer to the offset in the name after the namespace
415 and the separator. If however the name doesn't match the namespace,
419 const char *matches_ns(const char *ns, const char *name) {
421 if (ns == NULL || *ns == '\0')
423 ns_size = strlen(ns);
425 if (strlen(name) > (ns_size+1) && !strncmp(name, ns, ns_size) &&
426 name[ns_size] == '.')
427 return name + ns_size + 1;
431 /* Wrapper for getxattr */
432 static char __pygetxattr_doc__[] =
433 "getxattr(item, attribute[, nofollow=False])\n"
434 "Get the value of a given extended attribute (deprecated).\n"
440 ".. deprecated:: 0.4\n"
441 " this function has been deprecated\n"
442 " by the :func:`get` function.\n"
446 pygetxattr(PyObject *self, PyObject *args)
451 char *attrname = NULL;
454 size_t nalloc = ESTIMATE_ATTR_SIZE;
457 /* Parse the arguments */
458 if (!PyArg_ParseTuple(args, "Oet|i", &myarg, NULL, &attrname, &nofollow))
460 if(convert_obj(myarg, &tgt, nofollow) < 0) {
465 nret = _generic_get(_get_obj, &tgt, attrname, &buf, &nalloc, NULL);
470 /* Create the string which will hold the result */
471 res = PyBytes_FromStringAndSize(buf, nret);
474 /* Free the buffer, now it is no longer needed */
478 PyMem_Free(attrname);
480 /* Return the result */
484 /* Wrapper for getxattr */
485 static char __get_doc__[] =
486 "get(item, name[, nofollow=False, namespace=None])\n"
487 "Get the value of a given extended attribute.\n"
490 " >>> xattr.get('/path/to/file', 'user.comment')\n"
492 " >>> xattr.get('/path/to/file', 'comment', namespace=xattr.NS_USER)\n"
499 ":return: the value of the extended attribute (can contain NULLs)\n"
501 ":raises EnvironmentError: caused by any system errors\n"
503 ".. versionadded:: 0.4\n"
508 xattr_get(PyObject *self, PyObject *args, PyObject *keywds)
513 char *attrname = NULL, *namebuf;
514 const char *fullname;
516 const char *ns = NULL;
518 size_t nalloc = ESTIMATE_ATTR_SIZE;
519 PyObject *res = NULL;
520 static char *kwlist[] = {"item", "name", "nofollow", "namespace", NULL};
522 /* Parse the arguments */
523 if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oet|i" BYTES_CHAR, kwlist,
524 &myarg, NULL, &attrname, &nofollow, &ns))
527 if(convert_obj(myarg, &tgt, nofollow) < 0) {
531 if(merge_ns(ns, attrname, &fullname, &namebuf) < 0) {
535 nret = _generic_get(_get_obj, &tgt, fullname, &buf, &nalloc, NULL);
540 /* Create the string which will hold the result */
541 res = PyBytes_FromStringAndSize(buf, nret);
543 /* Free the buffers, they are no longer needed */
550 PyMem_Free(attrname);
552 /* Return the result */
556 /* Wrapper for getxattr */
557 static char __get_all_doc__[] =
558 "get_all(item[, nofollow=False, namespace=None])\n"
559 "Get all the extended attributes of an item.\n"
561 "This function performs a bulk-get of all extended attribute names\n"
562 "and the corresponding value.\n"
565 " >>> xattr.get_all('/path/to/file')\n"
566 " [('user.mime-type', 'plain/text'), ('user.comment', 'test'),\n"
567 " ('system.posix_acl_access', '\\x02\\x00...')]\n"
568 " >>> xattr.get_all('/path/to/file', namespace=xattr.NS_USER)\n"
569 " [('mime-type', 'plain/text'), ('comment', 'test')]\n"
572 ":keyword namespace: an optional namespace for filtering the\n"
573 " attributes; for example, querying all user attributes can be\n"
574 " accomplished by passing namespace=:const:`NS_USER`\n"
575 ":type namespace: string\n"
577 ":return: list of tuples (name, value); note that if a namespace\n"
578 " argument was passed, it (and the separator) will be stripped from\n"
579 " the names returned\n"
581 ":raises EnvironmentError: caused by any system errors\n"
583 ".. note:: Since reading the whole attribute list is not an atomic\n"
584 " operation, it might be possible that attributes are added\n"
585 " or removed between the initial query and the actual reading\n"
586 " of the attributes; the returned list will contain only the\n"
587 " attributes that were present at the initial listing of the\n"
588 " attribute names and that were still present when the read\n"
589 " attempt for the value is made.\n"
590 ".. versionadded:: 0.4\n"
595 get_all(PyObject *self, PyObject *args, PyObject *keywds)
597 PyObject *myarg, *res;
599 const char *ns = NULL;
600 char *buf_list = NULL, *buf_val = NULL;
602 size_t nalloc = ESTIMATE_ATTR_SIZE;
606 static char *kwlist[] = {"item", "nofollow", "namespace", NULL};
609 /* Parse the arguments */
610 if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|i" BYTES_CHAR, kwlist,
611 &myarg, &nofollow, &ns))
613 if(convert_obj(myarg, &tgt, nofollow) < 0)
617 /* Compute first the list of attributes */
618 nlist = _generic_get(_list_obj, &tgt, NULL, &buf_list,
621 /* We can't handle any errors, and the Python error is already
622 set, just bail out. */
626 /* Create the list which will hold the result. */
627 mylist = PyList_New(0);
632 nalloc = ESTIMATE_ATTR_SIZE;
633 /* Create and insert the attributes as strings in the list */
634 for(s = buf_list; s - buf_list < nlist; s += strlen(s) + 1) {
638 if((name = matches_ns(ns, s)) == NULL)
640 /* Now retrieve the attribute value */
641 nval = _generic_get(_get_obj, &tgt, s, &buf_val, &nalloc, &io_errno);
643 if (io_errno == ENODATA) {
651 my_tuple = Py_BuildValue(BYTES_TUPLE, name, buf_val, nval);
652 if (my_tuple == NULL) {
656 PyList_Append(mylist, my_tuple);
660 /* Successful exit */
667 PyMem_Free(buf_list);
672 /* Return the result */
677 static char __pysetxattr_doc__[] =
678 "setxattr(item, name, value[, flags=0, nofollow=False])\n"
679 "Set the value of a given extended attribute (deprecated).\n"
681 "Be careful in case you want to set attributes on symbolic\n"
682 "links, you have to use all the 5 parameters; use 0 for the \n"
683 "flags value if you want the default behaviour (create or "
692 ".. deprecated:: 0.4\n"
693 " this function has been deprecated\n"
694 " by the :func:`set` function.\n"
697 /* Wrapper for setxattr */
699 pysetxattr(PyObject *self, PyObject *args)
701 PyObject *myarg, *res;
703 char *attrname = NULL;
705 Py_ssize_t bufsize_s;
711 /* Parse the arguments */
712 if (!PyArg_ParseTuple(args, "Oetet#|ii", &myarg, NULL, &attrname,
713 NULL, &buf, &bufsize_s, &flags, &nofollow))
717 PyErr_SetString(PyExc_ValueError,
718 "negative value size?!");
722 bufsize = (size_t) bufsize_s;
724 if(convert_obj(myarg, &tgt, nofollow) < 0) {
729 /* Set the attribute's value */
730 nret = _set_obj(&tgt, attrname, buf, bufsize, flags);
735 res = PyErr_SetFromErrno(PyExc_IOError);
743 PyMem_Free(attrname);
746 /* Return the result */
750 static char __set_doc__[] =
751 "set(item, name, value[, flags=0, namespace=None])\n"
752 "Set the value of a given extended attribute.\n"
756 " >>> xattr.set('/path/to/file', 'user.comment', 'test')\n"
757 " >>> xattr.set('/path/to/file', 'comment', 'test',"
758 " namespace=xattr.NS_USER)\n"
767 ":raises EnvironmentError: caused by any system errors\n"
769 ".. versionadded:: 0.4\n"
773 /* Wrapper for setxattr */
775 xattr_set(PyObject *self, PyObject *args, PyObject *keywds)
777 PyObject *myarg, *res;
779 char *attrname = NULL;
781 Py_ssize_t bufsize_s;
786 const char *ns = NULL;
788 const char *full_name;
789 static char *kwlist[] = {"item", "name", "value", "flags",
790 "nofollow", "namespace", NULL};
792 /* Parse the arguments */
793 if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oetet#|ii" BYTES_CHAR,
794 kwlist, &myarg, NULL, &attrname, NULL,
795 &buf, &bufsize_s, &flags, &nofollow, &ns))
799 PyErr_SetString(PyExc_ValueError,
800 "negative value size?!");
804 bufsize = (size_t) bufsize_s;
806 if(convert_obj(myarg, &tgt, nofollow) < 0) {
811 if(merge_ns(ns, attrname, &full_name, &newname) < 0) {
816 /* Set the attribute's value */
817 nret = _set_obj(&tgt, full_name, buf, bufsize, flags);
824 res = PyErr_SetFromErrno(PyExc_IOError);
832 PyMem_Free(attrname);
835 /* Return the result */
840 static char __pyremovexattr_doc__[] =
841 "removexattr(item, name[, nofollow])\n"
842 "Remove an attribute from a file (deprecated).\n"
848 ".. deprecated:: 0.4\n"
849 " this function has been deprecated by the :func:`remove` function.\n"
852 /* Wrapper for removexattr */
854 pyremovexattr(PyObject *self, PyObject *args)
856 PyObject *myarg, *res;
858 char *attrname = NULL;
862 /* Parse the arguments */
863 if (!PyArg_ParseTuple(args, "Oet|i", &myarg, NULL, &attrname, &nofollow))
866 if(convert_obj(myarg, &tgt, nofollow) < 0) {
871 /* Remove the attribute */
872 nret = _remove_obj(&tgt, attrname);
877 res = PyErr_SetFromErrno(PyExc_IOError);
885 PyMem_Free(attrname);
887 /* Return the result */
891 static char __remove_doc__[] =
892 "remove(item, name[, nofollow=False, namespace=None])\n"
893 "Remove an attribute from a file.\n"
897 " >>> xattr.remove('/path/to/file', 'user.comment')\n"
904 ":raises EnvironmentError: caused by any system errors\n"
906 ".. versionadded:: 0.4\n"
910 /* Wrapper for removexattr */
912 xattr_remove(PyObject *self, PyObject *args, PyObject *keywds)
914 PyObject *myarg, *res;
916 char *attrname = NULL, *name_buf;
917 const char *ns = NULL;
918 const char *full_name;
921 static char *kwlist[] = {"item", "name", "nofollow", "namespace", NULL};
923 /* Parse the arguments */
924 if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oet|i" BYTES_CHAR, kwlist,
925 &myarg, NULL, &attrname, &nofollow, &ns))
928 if(convert_obj(myarg, &tgt, nofollow) < 0) {
933 if(merge_ns(ns, attrname, &full_name, &name_buf) < 0) {
938 /* Remove the attribute */
939 nret = _remove_obj(&tgt, full_name);
941 PyMem_Free(name_buf);
946 res = PyErr_SetFromErrno(PyExc_IOError);
954 PyMem_Free(attrname);
956 /* Return the result */
960 static char __pylistxattr_doc__[] =
961 "listxattr(item[, nofollow=False])\n"
962 "Return the list of attribute names for a file (deprecated).\n"
967 ".. deprecated:: 0.4\n"
968 " this function has been deprecated by the :func:`list` function.\n"
971 /* Wrapper for listxattr */
973 pylistxattr(PyObject *self, PyObject *args)
978 size_t nalloc = ESTIMATE_ATTR_SIZE;
985 /* Parse the arguments */
986 if (!PyArg_ParseTuple(args, "O|i", &myarg, &nofollow))
988 if(convert_obj(myarg, &tgt, nofollow) < 0)
991 nret = _generic_get(_list_obj, &tgt, NULL, &buf, &nalloc, NULL);
997 /* Compute the number of attributes in the list */
998 for(s = buf, nattrs = 0; (s - buf) < nret; s += strlen(s) + 1) {
1002 /* Create the list which will hold the result */
1003 mylist = PyList_New(nattrs);
1004 if(mylist == NULL) {
1008 /* Create and insert the attributes as strings in the list */
1009 for(s = buf, nattrs = 0; s - buf < nret; s += strlen(s) + 1) {
1010 PyObject *item = PyBytes_FromString(s);
1016 PyList_SET_ITEM(mylist, nattrs, item);
1021 /* Free the buffer, now it is no longer needed */
1025 /* Return the result */
1029 static char __list_doc__[] =
1030 "list(item[, nofollow=False, namespace=None])\n"
1031 "Return the list of attribute names for a file.\n"
1035 " >>> xattr.list('/path/to/file')\n"
1036 " ['user.test', 'user.comment', 'system.posix_acl_access']\n"
1037 " >>> xattr.list('/path/to/file', namespace=xattr.NS_USER)\n"
1038 " ['test', 'comment']\n"
1043 ":returns: the list of attributes; note that if a namespace \n"
1044 " argument was passed, it (and the separator) will be stripped\n"
1048 ":raises EnvironmentError: caused by any system errors\n"
1050 ".. versionadded:: 0.4\n"
1054 /* Wrapper for listxattr */
1056 xattr_list(PyObject *self, PyObject *args, PyObject *keywds)
1061 size_t nalloc = ESTIMATE_ATTR_SIZE;
1064 const char *ns = NULL;
1068 static char *kwlist[] = {"item", "nofollow", "namespace", NULL};
1070 /* Parse the arguments */
1071 if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|i" BYTES_CHAR, kwlist,
1072 &myarg, &nofollow, &ns))
1075 if(convert_obj(myarg, &tgt, nofollow) < 0) {
1078 nret = _generic_get(_list_obj, &tgt, NULL, &buf, &nalloc, NULL);
1083 /* Compute the number of attributes in the list */
1084 for(s = buf, nattrs = 0; (s - buf) < nret; s += strlen(s) + 1) {
1085 if(matches_ns(ns, s) != NULL)
1089 /* Create the list which will hold the result */
1090 if((res = PyList_New(nattrs)) == NULL) {
1094 /* Create and insert the attributes as strings in the list */
1095 for(s = buf, nattrs = 0; s - buf < nret; s += strlen(s) + 1) {
1096 const char *name = matches_ns(ns, s);
1098 PyObject *item = PyBytes_FromString(name);
1104 PyList_SET_ITEM(res, nattrs, item);
1110 /* Free the buffer, now it is no longer needed */
1117 /* Return the result */
1121 static PyMethodDef xattr_methods[] = {
1122 {"getxattr", pygetxattr, METH_VARARGS, __pygetxattr_doc__ },
1123 {"get", (PyCFunction) xattr_get, METH_VARARGS | METH_KEYWORDS,
1125 {"get_all", (PyCFunction) get_all, METH_VARARGS | METH_KEYWORDS,
1127 {"setxattr", pysetxattr, METH_VARARGS, __pysetxattr_doc__ },
1128 {"set", (PyCFunction) xattr_set, METH_VARARGS | METH_KEYWORDS,
1130 {"removexattr", pyremovexattr, METH_VARARGS, __pyremovexattr_doc__ },
1131 {"remove", (PyCFunction) xattr_remove, METH_VARARGS | METH_KEYWORDS,
1133 {"listxattr", pylistxattr, METH_VARARGS, __pylistxattr_doc__ },
1134 {"list", (PyCFunction) xattr_list, METH_VARARGS | METH_KEYWORDS,
1136 {NULL, NULL, 0, NULL} /* Sentinel */
1139 static char __xattr_doc__[] = \
1140 "This module gives access to the extended attributes present\n"
1141 "in some operating systems/filesystems. You can list attributes,\n"
1142 "get, set and remove them.\n"
1144 "The module exposes two sets of functions:\n"
1145 " - the 'old' :func:`listxattr`, :func:`getxattr`, :func:`setxattr`,\n"
1146 " :func:`removexattr`\n"
1147 " functions which are deprecated since version 0.4\n"
1148 " - the new :func:`list`, :func:`get`, :func:`get_all`, :func:`set`,\n"
1149 " :func:`remove` functions\n"
1150 " which expose a namespace-aware API and simplify a bit the calling\n"
1151 " model by using keyword arguments\n"
1154 " >>> import xattr\n"
1155 " >>> xattr.listxattr(\"file.txt\")\n"
1156 " ['user.mime_type']\n"
1157 " >>> xattr.getxattr(\"file.txt\", \"user.mime_type\")\n"
1159 " >>> xattr.setxattr(\"file.txt\", \"user.comment\", "
1160 "\"Simple text file\")\n"
1161 " >>> xattr.listxattr(\"file.txt\")\n"
1162 " ['user.mime_type', 'user.comment']\n"
1163 " >>> xattr.removexattr (\"file.txt\", \"user.comment\")\n"
1165 ".. note:: Most or all errors reported by the system while using\n"
1166 " the ``xattr`` library will be reported by raising\n"
1167 " a :exc:`EnvironmentError`; under\n"
1168 " Linux, the following ``errno`` values are used:\n"
1170 " - ``ENODATA`` means that the attribute name is\n invalid\n"
1171 " - ``ENOTSUP`` and ``EOPNOTSUPP`` mean that the filesystem does not\n"
1172 " support extended attributes, or that the namespace is invalid\n"
1173 " - ``E2BIG`` mean that the attribute value is too big\n"
1174 " - ``ERANGE`` mean that the attribute name is too big (it might also\n"
1175 " mean an error in the xattr module itself)\n"
1176 " - ``ENOSPC`` and ``EDQUOT`` are documented as meaning out of disk\n"
1177 " space or out of disk space because of quota limits\n"
1178 ".. note:: Under Python 3, the namespace argument is a byte string,\n"
1179 " not a unicode string.\n"
1185 static struct PyModuleDef xattrmodule = {
1186 PyModuleDef_HEAD_INIT,
1193 #define INITERROR return NULL
1199 #define INITERROR return
1204 PyObject *ns_security = NULL;
1205 PyObject *ns_system = NULL;
1206 PyObject *ns_trusted = NULL;
1207 PyObject *ns_user = NULL;
1209 PyObject *m = PyModule_Create(&xattrmodule);
1211 PyObject *m = Py_InitModule3("xattr", xattr_methods, __xattr_doc__);
1216 PyModule_AddStringConstant(m, "__author__", _XATTR_AUTHOR);
1217 PyModule_AddStringConstant(m, "__contact__", _XATTR_EMAIL);
1218 PyModule_AddStringConstant(m, "__version__", _XATTR_VERSION);
1219 PyModule_AddStringConstant(m, "__license__",
1220 "GNU Lesser General Public License (LGPL)");
1221 PyModule_AddStringConstant(m, "__docformat__", "restructuredtext en");
1223 PyModule_AddIntConstant(m, "XATTR_CREATE", XATTR_CREATE);
1224 PyModule_AddIntConstant(m, "XATTR_REPLACE", XATTR_REPLACE);
1226 /* namespace constants */
1227 if((ns_security = PyBytes_FromString("security")) == NULL)
1229 if((ns_system = PyBytes_FromString("system")) == NULL)
1231 if((ns_trusted = PyBytes_FromString("trusted")) == NULL)
1233 if((ns_user = PyBytes_FromString("user")) == NULL)
1235 if(PyModule_AddObject(m, "NS_SECURITY", ns_security) < 0)
1238 if(PyModule_AddObject(m, "NS_SYSTEM", ns_system) < 0)
1241 if(PyModule_AddObject(m, "NS_TRUSTED", ns_trusted) < 0)
1244 if(PyModule_AddObject(m, "NS_USER", ns_user) < 0)
1255 Py_XDECREF(ns_user);
1256 Py_XDECREF(ns_trusted);
1257 Py_XDECREF(ns_system);
1258 Py_XDECREF(ns_security);