2 #include <attr/xattr.h>
5 /* the estimated (startup) attribute buffer size in
7 #define ESTIMATE_ATTR_SIZE 256
9 typedef enum {T_FD, T_PATH, T_LINK} target_e;
19 /** Converts from a string, file or int argument to what we need. */
20 static int convertObj(PyObject *myobj, target_t *tgt, int nofollow) {
22 if(PyString_Check(myobj)) {
23 tgt->type = nofollow ? T_LINK : T_PATH;
24 tgt->name = PyString_AS_STRING(myobj);
25 } else if((fd = PyObject_AsFileDescriptor(myobj)) != -1) {
29 PyErr_SetString(PyExc_TypeError, "argument must be string or int");
35 /* Combine a namespace string and an attribute name into a
36 fully-qualified name */
37 static const char* merge_ns(const char *ns, const char *name, char **buf) {
40 size_t new_size = strlen(ns) + 1 + strlen(name) + 1;
41 if((*buf = PyMem_Malloc(new_size)) == NULL) {
45 cnt = snprintf(*buf, new_size, "%s.%s", ns, name);
46 if(cnt > new_size || cnt < 0) {
47 PyErr_SetString(PyExc_ValueError,
48 "can't format the attribute name");
59 static ssize_t _list_obj(target_t *tgt, char *list, size_t size) {
61 return flistxattr(tgt->fd, list, size);
62 else if (tgt->type == T_LINK)
63 return llistxattr(tgt->name, list, size);
65 return listxattr(tgt->name, list, size);
68 static ssize_t _get_obj(target_t *tgt, const char *name, void *value,
71 return fgetxattr(tgt->fd, name, value, size);
72 else if (tgt->type == T_LINK)
73 return lgetxattr(tgt->name, name, value, size);
75 return getxattr(tgt->name, name, value, size);
78 static ssize_t _set_obj(target_t *tgt, const char *name,
79 const void *value, size_t size,
82 return fsetxattr(tgt->fd, name, value, size, flags);
83 else if (tgt->type == T_LINK)
84 return lsetxattr(tgt->name, name, value, size, flags);
86 return setxattr(tgt->name, name, value, size, flags);
89 static ssize_t _remove_obj(target_t *tgt, const char *name) {
91 return fremovexattr(tgt->fd, name);
92 else if (tgt->type == T_LINK)
93 return lremovexattr(tgt->name, name);
95 return removexattr(tgt->name, name);
98 /* Checks if an attribute name matches an optional namespace */
99 static int matches_ns(const char *name, const char *ns) {
103 ns_size = strlen(ns);
105 if (strlen(name) > ns_size && !strncmp(name, ns, ns_size) &&
106 name[ns_size] == '.')
111 /* Wrapper for getxattr */
112 static char __pygetxattr_doc__[] =
113 "Get the value of a given extended attribute.\n"
116 " - a string representing filename, or a file-like object,\n"
117 " or a file descriptor; this represents the file on \n"
119 " - a string, representing the attribute whose value to retrieve;\n"
120 " usually in form of system.posix_acl or user.mime_type\n"
121 " - (optional) a boolean value (defaults to false), which, if\n"
122 " the file name given is a symbolic link, makes the\n"
123 " function operate on the symbolic link itself instead\n"
125 "@deprecated: this function has been replace with the L{get_all} function"
126 " which replaces the positional parameters with keyword ones\n"
130 pygetxattr(PyObject *self, PyObject *args)
140 /* Parse the arguments */
141 if (!PyArg_ParseTuple(args, "Os|i", &myarg, &attrname, &nofollow))
143 if(!convertObj(myarg, &tgt, nofollow))
146 /* Find out the needed size of the buffer */
147 if((nalloc = _get_obj(&tgt, attrname, NULL, 0)) == -1) {
148 return PyErr_SetFromErrno(PyExc_IOError);
151 /* Try to allocate the memory, using Python's allocator */
152 if((buf = PyMem_Malloc(nalloc)) == NULL) {
157 /* Now retrieve the attribute value */
158 if((nret = _get_obj(&tgt, attrname, buf, nalloc)) == -1) {
160 return PyErr_SetFromErrno(PyExc_IOError);
163 /* Create the string which will hold the result */
164 res = PyString_FromStringAndSize(buf, nret);
166 /* Free the buffer, now it is no longer needed */
169 /* Return the result */
173 /* Wrapper for getxattr */
174 static char __get_all_doc__[] =
175 "Get all the extended attributes of an item.\n"
177 "This function performs a bulk-get of all extended attribute names\n"
178 "and the corresponding value.\n"
180 " >>> xattr.get_all('/path/to/file')\n"
181 " [('user.mime-type', 'plain/text'), ('user.comment', 'test'),"
182 " ('system.posix_acl_access', '\\x02\\x00...')]\n"
183 " >>> xattr.get_all('/path/to/file', namespace=xattr.NS_USER)\n"
184 " [('user.mime-type', 'plain/text'), ('user.comment', 'test')]\n"
186 "@param item: the item to query; either a string representing the"
187 " filename, or a file-like object, or a file descriptor\n"
188 "@keyword namespace: an optional namespace for filtering the"
189 " attributes; for example, querying all user attributes can be"
190 " accomplished by passing namespace=L{NS_USER}\n"
191 "@type namespace: string\n"
192 "@keyword nofollow: if passed and true, if the target file is a symbolic"
194 " the attributes for the link itself will be returned, instead of the"
195 " attributes of the target\n"
196 "@type nofollow: boolean\n"
197 "@return: list of tuples (name, value)\n"
201 get_all(PyObject *self, PyObject *args, PyObject *keywds)
206 char *buf_list, *buf_val;
208 size_t nalloc, nlist, nval;
211 static char *kwlist[] = {"item", "nofollow", "namespace", NULL};
213 /* Parse the arguments */
214 if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|iz", kwlist,
215 &myarg, &dolink, &ns))
217 if(!convertObj(myarg, &tgt, dolink))
220 /* Compute first the list of attributes */
222 /* Find out the needed size of the buffer for the attribute list */
223 nalloc = _list_obj(&tgt, NULL, 0);
226 return PyErr_SetFromErrno(PyExc_IOError);
229 /* Try to allocate the memory, using Python's allocator */
230 if((buf_list = PyMem_Malloc(nalloc)) == NULL) {
235 /* Now retrieve the list of attributes */
236 nlist = _list_obj(&tgt, buf_list, nalloc);
239 PyErr_SetFromErrno(PyExc_IOError);
243 /* Create the list which will hold the result */
244 mylist = PyList_New(0);
245 nalloc = ESTIMATE_ATTR_SIZE;
246 if((buf_val = PyMem_Malloc(nalloc)) == NULL) {
251 /* Create and insert the attributes as strings in the list */
252 for(s = buf_list; s - buf_list < nlist; s += strlen(s) + 1) {
256 if(!matches_ns(s, ns))
258 /* Now retrieve the attribute value */
261 nval = _get_obj(&tgt, s, buf_val, nalloc);
264 if(errno == ERANGE) {
265 nval = _get_obj(&tgt, s, NULL, 0);
266 if((buf_val = PyMem_Realloc(buf_val, nval)) == NULL)
270 } else if(errno == ENODATA || errno == ENOATTR) {
271 /* this attribute has gone away since we queried
272 the attribute list */
282 my_tuple = Py_BuildValue("ss#", s, buf_val, nval);
284 PyList_Append(mylist, my_tuple);
288 /* Free the buffers, now they are no longer needed */
290 PyMem_Free(buf_list);
292 /* Return the result */
295 PyErr_SetFromErrno(PyExc_IOError);
300 PyMem_Free(buf_list);
305 static char __pysetxattr_doc__[] =
306 "Set the value of a given extended attribute.\n"
307 "Be carefull in case you want to set attributes on symbolic\n"
308 "links, you have to use all the 5 parameters; use 0 for the \n"
309 "flags value if you want the default behavior (create or "
313 " - a string representing filename, or a file-like object,\n"
314 " or a file descriptor; this represents the file on \n"
316 " - a string, representing the attribute whose value to set;\n"
317 " usually in form of system.posix_acl or user.mime_type\n"
318 " - a string, possibly with embedded NULLs; note that there\n"
319 " are restrictions regarding the size of the value, for\n"
320 " example, for ext2/ext3, maximum size is the block size\n"
321 " - (optional) flags; if 0 or ommited the attribute will be \n"
322 " created or replaced; if XATTR_CREATE, the attribute \n"
323 " will be created, giving an error if it already exists;\n"
324 " of XATTR_REPLACE, the attribute will be replaced,\n"
325 " giving an error if it doesn't exists;\n"
326 " - (optional) a boolean value (defaults to false), which, if\n"
327 " the file name given is a symbolic link, makes the\n"
328 " function operate on the symbolic link itself instead\n"
330 "@deprecated: this function has been deprecated by the new L{set}"
334 /* Wrapper for setxattr */
336 pysetxattr(PyObject *self, PyObject *args)
346 /* Parse the arguments */
347 if (!PyArg_ParseTuple(args, "Oss#|bi", &myarg, &attrname,
348 &buf, &bufsize, &flags, &nofollow))
350 if(!convertObj(myarg, &tgt, nofollow))
353 /* Set the attribute's value */
354 if((nret = _set_obj(&tgt, attrname, buf, bufsize, flags)) == -1) {
355 return PyErr_SetFromErrno(PyExc_IOError);
358 /* Return the result */
362 static char __set_doc__[] =
363 "Set the value of a given extended attribute.\n"
365 "@param item: the item to query; either a string representing the"
366 " filename, or a file-like object, or a file descriptor\n"
367 "@param name: the attribute whose value to set; usually in form of"
368 " system.posix_acl or user.mime_type\n"
369 "@type name: string\n"
370 "@param value: a string, possibly with embedded NULLs; note that there"
371 " are restrictions regarding the size of the value, for"
372 " example, for ext2/ext3, maximum size is the block size\n"
373 "@type value: string\n"
374 "@param flags: if 0 or ommited the attribute will be"
375 " created or replaced; if L{XATTR_CREATE}, the attribute"
376 " will be created, giving an error if it already exists;"
377 " if L{XATTR_REPLACE}, the attribute will be replaced,"
378 " giving an error if it doesn't exists;\n"
379 "@type flags: integer\n"
380 "@param nofollow: if given and True, and the function is passed a"
381 " filename that points to a symlink, the function will act on the symlink"
382 " itself instead of its target\n"
383 "@type nofollow: boolean\n"
384 "@param namespace: if given, the attribute must not contain the namespace"
385 " itself, but instead the namespace will be taken from this parameter\n"
386 "@type namespace: string\n"
389 /* Wrapper for setxattr */
391 xattr_set(PyObject *self, PyObject *args, PyObject *keywds)
402 const char *full_name;
403 static char *kwlist[] = {"item", "name", "value", "flags",
404 "nofollow", "namespace", NULL};
406 /* Parse the arguments */
407 if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oss#|iiz", kwlist,
409 &buf, &bufsize, &flags, &nofollow, &ns))
411 if(!convertObj(myarg, &tgt, nofollow))
414 full_name = merge_ns(ns, attrname, &newname);
415 /* Set the attribute's value */
416 nret = _set_obj(&tgt, full_name, buf, bufsize, flags);
420 return PyErr_SetFromErrno(PyExc_IOError);
423 /* Return the result */
428 static char __pyremovexattr_doc__[] =
429 "Remove an attribute from a file\n"
432 " - a string representing filename, or a file-like object,\n"
433 " or a file descriptor; this represents the file on \n"
435 " - a string, representing the attribute to be removed;\n"
436 " usually in form of system.posix_acl or user.mime_type\n"
437 " - (optional) a boolean value (defaults to false), which, if\n"
438 " the file name given is a symbolic link, makes the\n"
439 " function operate on the symbolic link itself instead\n"
443 /* Wrapper for removexattr */
445 pyremovexattr(PyObject *self, PyObject *args)
453 /* Parse the arguments */
454 if (!PyArg_ParseTuple(args, "Os|i", &myarg, &attrname, &nofollow))
457 if(!convertObj(myarg, &tgt, nofollow))
460 /* Remove the attribute */
461 if((nret = _remove_obj(&tgt, attrname)) == -1) {
462 return PyErr_SetFromErrno(PyExc_IOError);
465 /* Return the result */
469 static char __pylistxattr_doc__[] =
470 "Return the list of attribute names for a file\n"
473 " - a string representing filename, or a file-like object,\n"
474 " or a file descriptor; this represents the file to \n"
476 " - (optional) a boolean value (defaults to false), which, if\n"
477 " the file name given is a symbolic link, makes the\n"
478 " function operate on the symbolic link itself instead\n"
482 /* Wrapper for listxattr */
484 pylistxattr(PyObject *self, PyObject *args)
495 /* Parse the arguments */
496 if (!PyArg_ParseTuple(args, "O|i", &myarg, &nofollow))
498 if(!convertObj(myarg, &tgt, nofollow))
501 /* Find out the needed size of the buffer */
502 if((nalloc = _list_obj(&tgt, NULL, 0)) == -1) {
503 return PyErr_SetFromErrno(PyExc_IOError);
506 /* Try to allocate the memory, using Python's allocator */
507 if((buf = PyMem_Malloc(nalloc)) == NULL) {
512 /* Now retrieve the list of attributes */
513 if((nret = _list_obj(&tgt, buf, nalloc)) == -1) {
515 return PyErr_SetFromErrno(PyExc_IOError);
518 /* Compute the number of attributes in the list */
519 for(s = buf, nattrs = 0; (s - buf) < nret; s += strlen(s) + 1) {
523 /* Create the list which will hold the result */
524 mylist = PyList_New(nattrs);
526 /* Create and insert the attributes as strings in the list */
527 for(s = buf, nattrs = 0; s - buf < nret; s += strlen(s) + 1) {
528 PyList_SET_ITEM(mylist, nattrs, PyString_FromString(s));
532 /* Free the buffer, now it is no longer needed */
535 /* Return the result */
539 static PyMethodDef xattr_methods[] = {
540 {"getxattr", pygetxattr, METH_VARARGS, __pygetxattr_doc__ },
541 {"get_all", (PyCFunction) get_all, METH_VARARGS | METH_KEYWORDS,
543 {"setxattr", pysetxattr, METH_VARARGS, __pysetxattr_doc__ },
544 {"set", (PyCFunction) xattr_set, METH_VARARGS | METH_KEYWORDS,
546 {"removexattr", pyremovexattr, METH_VARARGS, __pyremovexattr_doc__ },
547 {"listxattr", pylistxattr, METH_VARARGS, __pylistxattr_doc__ },
548 {NULL, NULL, 0, NULL} /* Sentinel */
551 static char __xattr_doc__[] = \
552 "Access extended filesystem attributes\n"
554 "This module gives access to the extended attributes present\n"
555 "in some operating systems/filesystems. You can list attributes,\n"
556 "get, set and remove them.\n"
557 "The last and optional parameter for all functions is a boolean \n"
558 "value which enables the 'l-' version of the functions - acting\n"
559 "on symbolic links and not their destination.\n"
562 " >>> import xattr\n"
563 " >>> xattr.listxattr(\"file.txt\")\n"
564 " ['user.mime_type']\n"
565 " >>> xattr.getxattr(\"file.txt\", \"user.mime_type\")\n"
567 " >>> xattr.setxattr(\"file.txt\", \"user.comment\", "
568 "\"Simple text file\")\n"
569 " >>> xattr.listxattr(\"file.txt\")\n"
570 " ['user.mime_type', 'user.comment']\n"
571 " >>> xattr.removexattr (\"file.txt\", \"user.comment\")\n"
578 PyObject *m = Py_InitModule3("xattr", xattr_methods, __xattr_doc__);
580 PyModule_AddIntConstant(m, "XATTR_CREATE", XATTR_CREATE);
581 PyModule_AddIntConstant(m, "XATTR_REPLACE", XATTR_REPLACE);
583 /* namespace constants */
584 PyModule_AddStringConstant(m, "NS_SECURITY", "security");
585 PyModule_AddStringConstant(m, "NS_SYSTEM", "system");
586 PyModule_AddStringConstant(m, "NS_TRUSTED", "trusted");
587 PyModule_AddStringConstant(m, "NS_USER", "user");