]> git.k1024.org Git - pyxattr.git/blob - xattr.c
Some more docstring updates
[pyxattr.git] / xattr.c
1 #define PY_SSIZE_T_CLEAN
2 #include <Python.h>
3 #include <attr/xattr.h>
4 #include <stdio.h>
5
6 /* Compatibility with python 2.4 regarding python size type (PEP 353) */
7 #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
8 typedef int Py_ssize_t;
9 #define PY_SSIZE_T_MAX INT_MAX
10 #define PY_SSIZE_T_MIN INT_MIN
11 #endif
12
13 /* the estimated (startup) attribute buffer size in
14    multi-operations */
15 #define ESTIMATE_ATTR_SIZE 256
16
17 typedef enum {T_FD, T_PATH, T_LINK} target_e;
18
19 typedef struct {
20     target_e type;
21     union {
22         const char *name;
23         int fd;
24     };
25 } target_t;
26
27 /** Converts from a string, file or int argument to what we need. */
28 static int convertObj(PyObject *myobj, target_t *tgt, int nofollow) {
29     int fd;
30     if(PyString_Check(myobj)) {
31         tgt->type = nofollow ? T_LINK : T_PATH;
32         tgt->name = PyString_AS_STRING(myobj);
33     } else if((fd = PyObject_AsFileDescriptor(myobj)) != -1) {
34         tgt->type = T_FD;
35         tgt->fd = fd;
36     } else {
37         PyErr_SetString(PyExc_TypeError, "argument must be string or int");
38         return 0;
39     }
40     return 1;
41 }
42
43 /* Combine a namespace string and an attribute name into a
44    fully-qualified name */
45 static const char* merge_ns(const char *ns, const char *name, char **buf) {
46     if(ns != NULL) {
47         int cnt;
48         size_t new_size = strlen(ns) + 1 + strlen(name) + 1;
49         if((*buf = PyMem_Malloc(new_size)) == NULL) {
50             PyErr_NoMemory();
51             return NULL;
52         }
53         cnt = snprintf(*buf, new_size, "%s.%s", ns, name);
54         if(cnt > new_size || cnt < 0) {
55             PyErr_SetString(PyExc_ValueError,
56                             "can't format the attribute name");
57             PyMem_Free(*buf);
58             return NULL;
59         }
60         return *buf;
61     } else {
62         *buf = NULL;
63         return name;
64     }
65 }
66
67 static ssize_t _list_obj(target_t *tgt, char *list, size_t size) {
68     if(tgt->type == T_FD)
69         return flistxattr(tgt->fd, list, size);
70     else if (tgt->type == T_LINK)
71         return llistxattr(tgt->name, list, size);
72     else
73         return listxattr(tgt->name, list, size);
74 }
75
76 static ssize_t _get_obj(target_t *tgt, const char *name, void *value,
77                         size_t size) {
78     if(tgt->type == T_FD)
79         return fgetxattr(tgt->fd, name, value, size);
80     else if (tgt->type == T_LINK)
81         return lgetxattr(tgt->name, name, value, size);
82     else
83         return getxattr(tgt->name, name, value, size);
84 }
85
86 static int _set_obj(target_t *tgt, const char *name,
87                     const void *value, size_t size, int flags) {
88     if(tgt->type == T_FD)
89         return fsetxattr(tgt->fd, name, value, size, flags);
90     else if (tgt->type == T_LINK)
91         return lsetxattr(tgt->name, name, value, size, flags);
92     else
93         return setxattr(tgt->name, name, value, size, flags);
94 }
95
96 static int _remove_obj(target_t *tgt, const char *name) {
97     if(tgt->type == T_FD)
98         return fremovexattr(tgt->fd, name);
99     else if (tgt->type == T_LINK)
100         return lremovexattr(tgt->name, name);
101     else
102         return removexattr(tgt->name, name);
103 }
104
105 /*
106    Checks if an attribute name matches an optional namespace.
107
108    If the namespace is NULL, it will return the name itself.  If the
109    namespace is non-NULL and the name matches, it will return a
110    pointer to the offset in the name after the namespace and the
111    separator. If however the name doesn't match the namespace, it will
112    return NULL.
113 */
114 const char *matches_ns(const char *ns, const char *name) {
115     size_t ns_size;
116     if (ns == NULL)
117         return name;
118     ns_size = strlen(ns);
119
120     if (strlen(name) > (ns_size+1) && !strncmp(name, ns, ns_size) &&
121         name[ns_size] == '.')
122         return name + ns_size + 1;
123     return NULL;
124 }
125
126 /* Wrapper for getxattr */
127 static char __pygetxattr_doc__[] =
128     "Get the value of a given extended attribute (deprecated).\n"
129     "\n"
130     "Parameters:\n"
131     "  - a string representing filename, or a file-like object,\n"
132     "    or a file descriptor; this represents the file on \n"
133     "    which to act\n"
134     "  - a string, representing the attribute whose value to retrieve;\n"
135     "    usually in form of system.posix_acl or user.mime_type\n"
136     "  - (optional) a boolean value (defaults to false), which, if\n"
137     "    the file name given is a symbolic link, makes the\n"
138     "    function operate on the symbolic link itself instead\n"
139     "    of its target;\n"
140     "@deprecated: since version 0.4, this function has been deprecated\n"
141     "    by the L{get} function\n"
142     ;
143
144 static PyObject *
145 pygetxattr(PyObject *self, PyObject *args)
146 {
147     PyObject *myarg;
148     target_t tgt;
149     int nofollow=0;
150     char *attrname;
151     char *buf;
152     ssize_t nalloc, nret;
153     PyObject *res;
154
155     /* Parse the arguments */
156     if (!PyArg_ParseTuple(args, "Os|i", &myarg, &attrname, &nofollow))
157         return NULL;
158     if(!convertObj(myarg, &tgt, nofollow))
159         return NULL;
160
161     /* Find out the needed size of the buffer */
162     if((nalloc = _get_obj(&tgt, attrname, NULL, 0)) == -1) {
163         return PyErr_SetFromErrno(PyExc_IOError);
164     }
165
166     /* Try to allocate the memory, using Python's allocator */
167     if((buf = PyMem_Malloc(nalloc)) == NULL) {
168         PyErr_NoMemory();
169         return NULL;
170     }
171
172     /* Now retrieve the attribute value */
173     if((nret = _get_obj(&tgt, attrname, buf, nalloc)) == -1) {
174         PyMem_Free(buf);
175         return PyErr_SetFromErrno(PyExc_IOError);
176     }
177
178     /* Create the string which will hold the result */
179     res = PyString_FromStringAndSize(buf, nret);
180
181     /* Free the buffer, now it is no longer needed */
182     PyMem_Free(buf);
183
184     /* Return the result */
185     return res;
186 }
187
188 /* Wrapper for getxattr */
189 static char __get_doc__[] =
190     "Get the value of a given extended attribute.\n"
191     "\n"
192     "Example\n"
193     "    >>> xattr.get('/path/to/file', 'user.comment')\n"
194     "    'test'\n"
195     "    >>> xattr.get('/path/to/file', 'comment', namespace=xattr.NS_USER)\n"
196     "    'test'\n"
197     "\n"
198     "@param item: the item to query; either a string representing the\n"
199     "    filename, or a file-like object, or a file descriptor\n"
200     "@param name: the attribute whose value to set; usually in form of\n"
201     "    system.posix_acl or user.mime_type\n"
202     "@type name: string\n"
203     "@param nofollow: if given and True, and the function is passed a\n"
204     "    filename that points to a symlink, the function will act on the\n"
205     "    symlink itself instead of its target\n"
206     "@type nofollow: boolean\n"
207     "@param namespace: if given, the attribute must not contain the\n"
208     "    namespace itself, but instead the namespace will be taken from\n"
209     "    this parameter\n"
210     "@type namespace: string\n"
211     "@return: the value of the extended attribute (can contain NULLs)\n"
212     "@rtype: string\n"
213     "@raise EnvironmentError: caused by any system errors\n"
214     "@since: 0.4\n"
215     ;
216
217 static PyObject *
218 xattr_get(PyObject *self, PyObject *args, PyObject *keywds)
219 {
220     PyObject *myarg;
221     target_t tgt;
222     int nofollow=0;
223     char *attrname, *namebuf;
224     const char *fullname;
225     char *buf;
226     char *ns = NULL;
227     ssize_t nalloc, nret;
228     PyObject *res;
229     static char *kwlist[] = {"item", "name", "nofollow", "namespace", NULL};
230
231     /* Parse the arguments */
232     if (!PyArg_ParseTupleAndKeywords(args, keywds, "Os|iz", kwlist,
233                                      &myarg, &attrname, &nofollow, &ns))
234         return NULL;
235     if(!convertObj(myarg, &tgt, nofollow))
236         return NULL;
237
238     fullname = merge_ns(ns, attrname, &namebuf);
239
240     /* Find out the needed size of the buffer */
241     if((nalloc = _get_obj(&tgt, fullname, NULL, 0)) == -1) {
242         return PyErr_SetFromErrno(PyExc_IOError);
243     }
244
245     /* Try to allocate the memory, using Python's allocator */
246     if((buf = PyMem_Malloc(nalloc)) == NULL) {
247         PyMem_Free(namebuf);
248         PyErr_NoMemory();
249         return NULL;
250     }
251
252     /* Now retrieve the attribute value */
253     if((nret = _get_obj(&tgt, fullname, buf, nalloc)) == -1) {
254         PyMem_Free(buf);
255         PyMem_Free(namebuf);
256         return PyErr_SetFromErrno(PyExc_IOError);
257     }
258
259     /* Create the string which will hold the result */
260     res = PyString_FromStringAndSize(buf, nret);
261
262     /* Free the buffers, they are no longer needed */
263     PyMem_Free(namebuf);
264     PyMem_Free(buf);
265
266     /* Return the result */
267     return res;
268 }
269
270 /* Wrapper for getxattr */
271 static char __get_all_doc__[] =
272     "Get all the extended attributes of an item.\n"
273     "\n"
274     "This function performs a bulk-get of all extended attribute names\n"
275     "and the corresponding value.\n"
276     "Example:\n"
277     "    >>> xattr.get_all('/path/to/file')\n"
278     "    [('user.mime-type', 'plain/text'), ('user.comment', 'test'),\n"
279     "     ('system.posix_acl_access', '\\x02\\x00...')]\n"
280     "    >>> xattr.get_all('/path/to/file', namespace=xattr.NS_USER)\n"
281     "    [('mime-type', 'plain/text'), ('comment', 'test')]\n"
282     "\n"
283     "@param item: the item to query; either a string representing the\n"
284     "    filename, or a file-like object, or a file descriptor\n"
285     "@keyword namespace: an optional namespace for filtering the\n"
286     "    attributes; for example, querying all user attributes can be\n"
287     "    accomplished by passing namespace=L{NS_USER}\n"
288     "@type namespace: string\n"
289     "@keyword nofollow: if passed and true, if the target file is a\n"
290     "    symbolic link, the attributes for the link itself will be\n"
291     "    returned, instead of the attributes of the target\n"
292     "@type nofollow: boolean\n"
293     "@return: list of tuples (name, value); note that if a namespace\n"
294     "    argument was passed, it (and the separator) will be stripped from\n"
295     "    the names returned\n"
296     "@rtype: list\n"
297     "@raise EnvironmentError: caused by any system errors\n"
298     "@note: Since reading the whole attribute list is not an atomic\n"
299     "    operation, it might be possible that attributes are added\n"
300     "    or removed between the initial query and the actual reading\n"
301     "    of the attributes; the returned list will contain only the\n"
302     "    attributes that were present at the initial listing of the\n"
303     "    attribute names and that were still present when the read\n"
304     "    attempt for the value is made.\n"
305     "@since: 0.4\n"
306     ;
307
308 static PyObject *
309 get_all(PyObject *self, PyObject *args, PyObject *keywds)
310 {
311     PyObject *myarg;
312     int dolink=0;
313     char *ns = NULL;
314     char *buf_list, *buf_val;
315     char *s;
316     size_t nalloc, nlist, nval;
317     PyObject *mylist;
318     target_t tgt;
319     static char *kwlist[] = {"item", "nofollow", "namespace", NULL};
320
321     /* Parse the arguments */
322     if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|iz", kwlist,
323                                      &myarg, &dolink, &ns))
324         return NULL;
325     if(!convertObj(myarg, &tgt, dolink))
326         return NULL;
327
328     /* Compute first the list of attributes */
329
330     /* Find out the needed size of the buffer for the attribute list */
331     nalloc = _list_obj(&tgt, NULL, 0);
332
333     if(nalloc == -1) {
334         return PyErr_SetFromErrno(PyExc_IOError);
335     }
336
337     /* Try to allocate the memory, using Python's allocator */
338     if((buf_list = PyMem_Malloc(nalloc)) == NULL) {
339         PyErr_NoMemory();
340         return NULL;
341     }
342
343     /* Now retrieve the list of attributes */
344     nlist = _list_obj(&tgt, buf_list, nalloc);
345
346     if(nlist == -1) {
347         PyErr_SetFromErrno(PyExc_IOError);
348         goto free_buf_list;
349     }
350
351     /* Create the list which will hold the result */
352     mylist = PyList_New(0);
353     nalloc = ESTIMATE_ATTR_SIZE;
354     if((buf_val = PyMem_Malloc(nalloc)) == NULL) {
355         PyErr_NoMemory();
356         goto free_list;
357     }
358
359     /* Create and insert the attributes as strings in the list */
360     for(s = buf_list; s - buf_list < nlist; s += strlen(s) + 1) {
361         PyObject *my_tuple;
362         int missing;
363         const char *name;
364
365         if((name=matches_ns(ns, s))==NULL)
366             continue;
367         /* Now retrieve the attribute value */
368         missing = 0;
369         while(1) {
370             nval = _get_obj(&tgt, s, buf_val, nalloc);
371
372             if(nval == -1) {
373                 if(errno == ERANGE) {
374                     nval = _get_obj(&tgt, s, NULL, 0);
375                     if((buf_val = PyMem_Realloc(buf_val, nval)) == NULL)
376                         goto free_list;
377                     nalloc = nval;
378                     continue;
379                 } else if(errno == ENODATA || errno == ENOATTR) {
380                     /* this attribute has gone away since we queried
381                        the attribute list */
382                     missing = 1;
383                     break;
384                 }
385                 goto exit_errno;
386             }
387             break;
388         }
389         if(missing)
390             continue;
391         my_tuple = Py_BuildValue("ss#", name, buf_val, nval);
392
393         PyList_Append(mylist, my_tuple);
394         Py_DECREF(my_tuple);
395     }
396
397     /* Free the buffers, now they are no longer needed */
398     PyMem_Free(buf_val);
399     PyMem_Free(buf_list);
400
401     /* Return the result */
402     return mylist;
403  exit_errno:
404     PyErr_SetFromErrno(PyExc_IOError);
405     PyMem_Free(buf_val);
406  free_list:
407     Py_DECREF(mylist);
408  free_buf_list:
409     PyMem_Free(buf_list);
410     return NULL;
411 }
412
413
414 static char __pysetxattr_doc__[] =
415     "Set the value of a given extended attribute (deprecated).\n"
416     "Be carefull in case you want to set attributes on symbolic\n"
417     "links, you have to use all the 5 parameters; use 0 for the \n"
418     "flags value if you want the default behavior (create or "
419     "replace)\n"
420     "\n"
421     "Parameters:\n"
422     "  - a string representing filename, or a file-like object,\n"
423     "    or a file descriptor; this represents the file on \n"
424     "    which to act\n"
425     "  - a string, representing the attribute whose value to set;\n"
426     "    usually in form of system.posix_acl or user.mime_type\n"
427     "  - a string, possibly with embedded NULLs; note that there\n"
428     "    are restrictions regarding the size of the value, for\n"
429     "    example, for ext2/ext3, maximum size is the block size\n"
430     "  - (optional) flags; if 0 or ommited the attribute will be \n"
431     "    created or replaced; if XATTR_CREATE, the attribute \n"
432     "    will be created, giving an error if it already exists;\n"
433     "    of XATTR_REPLACE, the attribute will be replaced,\n"
434     "    giving an error if it doesn't exists;\n"
435     "  - (optional) a boolean value (defaults to false), which, if\n"
436     "    the file name given is a symbolic link, makes the\n"
437     "    function operate on the symbolic link itself instead\n"
438     "    of its target;\n"
439     "@deprecated: since version 0.4, this function has been deprecated\n"
440     "    by the L{set} function\n"
441     ;
442
443 /* Wrapper for setxattr */
444 static PyObject *
445 pysetxattr(PyObject *self, PyObject *args)
446 {
447     PyObject *myarg;
448     int nofollow=0;
449     char *attrname;
450     char *buf;
451     Py_ssize_t bufsize;
452     int nret;
453     int flags = 0;
454     target_t tgt;
455
456     /* Parse the arguments */
457     if (!PyArg_ParseTuple(args, "Oss#|bi", &myarg, &attrname,
458                           &buf, &bufsize, &flags, &nofollow))
459         return NULL;
460     if(!convertObj(myarg, &tgt, nofollow))
461         return NULL;
462
463     /* Set the attribute's value */
464     if((nret = _set_obj(&tgt, attrname, buf, bufsize, flags)) == -1) {
465         return PyErr_SetFromErrno(PyExc_IOError);
466     }
467
468     /* Return the result */
469     Py_RETURN_NONE;
470 }
471
472 static char __set_doc__[] =
473     "Set the value of a given extended attribute.\n"
474     "\n"
475     "Example:\n"
476     "    >>> xattr.set('/path/to/file', 'user.comment', 'test')\n"
477     "    >>> xattr.set('/path/to/file', 'comment', 'test',"
478     " namespace=xattr.NS_USER)\n"
479     "\n"
480     "@param item: the item to query; either a string representing the\n"
481     "    filename, or a file-like object, or a file descriptor\n"
482     "@param name: the attribute whose value to set; usually in form of\n"
483     "    system.posix_acl or user.mime_type\n"
484     "@type name: string\n"
485     "@param value: a string, possibly with embedded NULLs; note that there\n"
486     "    are restrictions regarding the size of the value, for\n"
487     "    example, for ext2/ext3, maximum size is the block size\n"
488     "@type value: string\n"
489     "@param flags: if 0 or ommited the attribute will be\n"
490     "    created or replaced; if L{XATTR_CREATE}, the attribute\n"
491     "    will be created, giving an error if it already exists;\n"
492     "    if L{XATTR_REPLACE}, the attribute will be replaced,\n"
493     "    giving an error if it doesn't exists;\n"
494     "@type flags: integer\n"
495     "@param nofollow: if given and True, and the function is passed a\n"
496     "    filename that points to a symlink, the function will act on the\n"
497     "    symlink itself instead of its target\n"
498     "@type nofollow: boolean\n"
499     "@param namespace: if given, the attribute must not contain the\n"
500     "    namespace itself, but instead the namespace will be taken from\n"
501     "    this parameter\n"
502     "@type namespace: string\n"
503     "@rtype: None\n"
504     "@raise EnvironmentError: caused by any system errors\n"
505     "@since: 0.4\n"
506     ;
507
508 /* Wrapper for setxattr */
509 static PyObject *
510 xattr_set(PyObject *self, PyObject *args, PyObject *keywds)
511 {
512     PyObject *myarg;
513     int nofollow=0;
514     char *attrname;
515     char *buf;
516     Py_ssize_t bufsize;
517     int nret;
518     int flags = 0;
519     target_t tgt;
520     char *ns = NULL;
521     char *newname;
522     const char *full_name;
523     static char *kwlist[] = {"item", "name", "value", "flags",
524                              "nofollow", "namespace", NULL};
525
526     /* Parse the arguments */
527     if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oss#|iiz", kwlist,
528                                      &myarg, &attrname,
529                                      &buf, &bufsize, &flags, &nofollow, &ns))
530         return NULL;
531     if(!convertObj(myarg, &tgt, nofollow))
532         return NULL;
533
534     full_name = merge_ns(ns, attrname, &newname);
535     /* Set the attribute's value */
536     nret = _set_obj(&tgt, full_name, buf, bufsize, flags);
537     if(newname != NULL)
538         PyMem_Free(newname);
539     if(nret == -1) {
540         return PyErr_SetFromErrno(PyExc_IOError);
541     }
542
543     /* Return the result */
544     Py_RETURN_NONE;
545 }
546
547
548 static char __pyremovexattr_doc__[] =
549     "Remove an attribute from a file (deprecated)\n"
550     "\n"
551     "Parameters:\n"
552     "  - a string representing filename, or a file-like object,\n"
553     "    or a file descriptor; this represents the file on \n"
554     "    which to act\n"
555     "  - a string, representing the attribute to be removed;\n"
556     "    usually in form of system.posix_acl or user.mime_type\n"
557     "  - (optional) a boolean value (defaults to false), which, if\n"
558     "    the file name given is a symbolic link, makes the\n"
559     "    function operate on the symbolic link itself instead\n"
560     "    of its target;\n"
561     "@deprecated: since version 0.4, this function has been deprecated\n"
562     "    by the L{remove}"
563     " function\n"
564     ;
565
566 /* Wrapper for removexattr */
567 static PyObject *
568 pyremovexattr(PyObject *self, PyObject *args)
569 {
570     PyObject *myarg;
571     int nofollow=0;
572     char *attrname;
573     int nret;
574     target_t tgt;
575
576     /* Parse the arguments */
577     if (!PyArg_ParseTuple(args, "Os|i", &myarg, &attrname, &nofollow))
578         return NULL;
579
580     if(!convertObj(myarg, &tgt, nofollow))
581         return NULL;
582
583     /* Remove the attribute */
584     if((nret = _remove_obj(&tgt, attrname)) == -1) {
585         return PyErr_SetFromErrno(PyExc_IOError);
586     }
587
588     /* Return the result */
589     Py_RETURN_NONE;
590 }
591
592 static char __remove_doc__[] =
593     "Remove an attribute from a file\n"
594     "\n"
595     "Example:\n"
596     "    >>> xattr.remove('/path/to/file', 'user.comment')\n"
597     "\n"
598     "@param item: the item to query; either a string representing the\n"
599     "    filename, or a file-like object, or a file descriptor\n"
600     "@param name: the attribute whose value to set; usually in form of\n"
601     "    system.posix_acl or user.mime_type\n"
602     "@type name: string\n"
603     "@param nofollow: if given and True, and the function is passed a\n"
604     "    filename that points to a symlink, the function will act on the\n"
605     "    symlink itself instead of its target\n"
606     "@type nofollow: boolean\n"
607     "@param namespace: if given, the attribute must not contain the\n"
608     "    namespace itself, but instead the namespace will be taken from\n"
609     "    this parameter\n"
610     "@type namespace: string\n"
611     "@since: 0.4\n"
612     "@rtype: None\n"
613     "@raise EnvironmentError: caused by any system errors\n"
614     ;
615
616 /* Wrapper for removexattr */
617 static PyObject *
618 xattr_remove(PyObject *self, PyObject *args, PyObject *keywds)
619 {
620     PyObject *myarg;
621     int nofollow=0;
622     char *attrname, *name_buf;
623     char *ns = NULL;
624     const char *full_name;
625     int nret;
626     target_t tgt;
627     static char *kwlist[] = {"item", "name", "nofollow", "namespace", NULL};
628
629     /* Parse the arguments */
630     if (!PyArg_ParseTupleAndKeywords(args, keywds, "Os|iz", kwlist,
631                                      &myarg, &attrname, &nofollow, &ns))
632         return NULL;
633
634     if(!convertObj(myarg, &tgt, nofollow))
635         return NULL;
636     full_name = merge_ns(ns, attrname, &name_buf);
637     if(full_name == NULL)
638         return NULL;
639
640     /* Remove the attribute */
641     nret = _remove_obj(&tgt, full_name);
642     PyMem_Free(name_buf);
643     if(nret == -1) {
644         return PyErr_SetFromErrno(PyExc_IOError);
645     }
646
647     /* Return the result */
648     Py_RETURN_NONE;
649 }
650
651 static char __pylistxattr_doc__[] =
652     "Return the list of attribute names for a file (deprecated)\n"
653     "\n"
654     "Parameters:\n"
655     "  - a string representing filename, or a file-like object,\n"
656     "    or a file descriptor; this represents the file to \n"
657     "    be queried\n"
658     "  - (optional) a boolean value (defaults to false), which, if\n"
659     "    the file name given is a symbolic link, makes the\n"
660     "    function operate on the symbolic link itself instead\n"
661     "    of its target;\n"
662     "@deprecated: since version 0.4, this function has been deprecated\n"
663     "    by the L{list}"
664     " function\n"
665     ;
666
667 /* Wrapper for listxattr */
668 static PyObject *
669 pylistxattr(PyObject *self, PyObject *args)
670 {
671     char *buf;
672     int nofollow=0;
673     ssize_t nalloc, nret;
674     PyObject *myarg;
675     PyObject *mylist;
676     Py_ssize_t nattrs;
677     char *s;
678     target_t tgt;
679
680     /* Parse the arguments */
681     if (!PyArg_ParseTuple(args, "O|i", &myarg, &nofollow))
682         return NULL;
683     if(!convertObj(myarg, &tgt, nofollow))
684         return NULL;
685
686     /* Find out the needed size of the buffer */
687     if((nalloc = _list_obj(&tgt, NULL, 0)) == -1) {
688         return PyErr_SetFromErrno(PyExc_IOError);
689     }
690
691     /* Try to allocate the memory, using Python's allocator */
692     if((buf = PyMem_Malloc(nalloc)) == NULL) {
693         PyErr_NoMemory();
694         return NULL;
695     }
696
697     /* Now retrieve the list of attributes */
698     if((nret = _list_obj(&tgt, buf, nalloc)) == -1) {
699         PyMem_Free(buf);
700         return PyErr_SetFromErrno(PyExc_IOError);
701     }
702
703     /* Compute the number of attributes in the list */
704     for(s = buf, nattrs = 0; (s - buf) < nret; s += strlen(s) + 1) {
705         nattrs++;
706     }
707
708     /* Create the list which will hold the result */
709     mylist = PyList_New(nattrs);
710
711     /* Create and insert the attributes as strings in the list */
712     for(s = buf, nattrs = 0; s - buf < nret; s += strlen(s) + 1) {
713         PyList_SET_ITEM(mylist, nattrs, PyString_FromString(s));
714         nattrs++;
715     }
716
717     /* Free the buffer, now it is no longer needed */
718     PyMem_Free(buf);
719
720     /* Return the result */
721     return mylist;
722 }
723
724 static char __list_doc__[] =
725     "Return the list of attribute names for a file\n"
726     "\n"
727     "Example:\n"
728     "    >>> xattr.list('/path/to/file')\n"
729     "    ['user.test', 'user.comment', 'system.posix_acl_access']\n"
730     "    >>> xattr.list('/path/to/file', namespace=xattr.NS_USER)\n"
731     "    ['test', 'comment']\n"
732     "\n"
733     "@param item: the item to query; either a string representing the\n"
734     "    filename, or a file-like object, or a file descriptor\n"
735     "@param nofollow: if given and True, and the function is passed a\n"
736     "    filename that points to a symlink, the function will act on the\n"
737     "    symlink itself instead of its target\n"
738     "@type nofollow: boolean\n"
739     "@param namespace: if given, the attribute must not contain the\n"
740     "    namespace itself, but instead the namespace will be taken from\n"
741     "    this parameter\n"
742     "@type namespace: string\n"
743     "@return: list of strings; note that if a namespace argument was\n"
744     "    passed, it (and the separator) will be stripped from the names\n"
745     "    returned\n"
746     "@rtype: list\n"
747     "@raise EnvironmentError: caused by any system errors\n"
748     "@since: 0.4\n"
749     ;
750
751 /* Wrapper for listxattr */
752 static PyObject *
753 xattr_list(PyObject *self, PyObject *args, PyObject *keywds)
754 {
755     char *buf;
756     int nofollow=0;
757     ssize_t nalloc, nret;
758     PyObject *myarg;
759     PyObject *mylist;
760     char *ns = NULL;
761     Py_ssize_t nattrs;
762     char *s;
763     target_t tgt;
764     static char *kwlist[] = {"item", "nofollow", "namespace", NULL};
765
766     /* Parse the arguments */
767     if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|iz", kwlist,
768                           &myarg, &nofollow, &ns))
769         return NULL;
770     if(!convertObj(myarg, &tgt, nofollow))
771         return NULL;
772
773     /* Find out the needed size of the buffer */
774     if((nalloc = _list_obj(&tgt, NULL, 0)) == -1) {
775         return PyErr_SetFromErrno(PyExc_IOError);
776     }
777
778     /* Try to allocate the memory, using Python's allocator */
779     if((buf = PyMem_Malloc(nalloc)) == NULL) {
780         PyErr_NoMemory();
781         return NULL;
782     }
783
784     /* Now retrieve the list of attributes */
785     if((nret = _list_obj(&tgt, buf, nalloc)) == -1) {
786         PyMem_Free(buf);
787         return PyErr_SetFromErrno(PyExc_IOError);
788     }
789
790     /* Compute the number of attributes in the list */
791     for(s = buf, nattrs = 0; (s - buf) < nret; s += strlen(s) + 1) {
792         if(matches_ns(ns, s)!=NULL)
793             nattrs++;
794     }
795     /* Create the list which will hold the result */
796     mylist = PyList_New(nattrs);
797
798     /* Create and insert the attributes as strings in the list */
799     for(s = buf, nattrs = 0; s - buf < nret; s += strlen(s) + 1) {
800         const char *name = matches_ns(ns, s);
801         if(name!=NULL) {
802             PyList_SET_ITEM(mylist, nattrs, PyString_FromString(name));
803             nattrs++;
804         }
805     }
806
807     /* Free the buffer, now it is no longer needed */
808     PyMem_Free(buf);
809
810     /* Return the result */
811     return mylist;
812 }
813
814 static PyMethodDef xattr_methods[] = {
815     {"getxattr",  pygetxattr, METH_VARARGS, __pygetxattr_doc__ },
816     {"get",  (PyCFunction) xattr_get, METH_VARARGS | METH_KEYWORDS,
817      __get_doc__ },
818     {"get_all", (PyCFunction) get_all, METH_VARARGS | METH_KEYWORDS,
819      __get_all_doc__ },
820     {"setxattr",  pysetxattr, METH_VARARGS, __pysetxattr_doc__ },
821     {"set",  (PyCFunction) xattr_set, METH_VARARGS | METH_KEYWORDS,
822      __set_doc__ },
823     {"removexattr",  pyremovexattr, METH_VARARGS, __pyremovexattr_doc__ },
824     {"remove",  (PyCFunction) xattr_remove, METH_VARARGS | METH_KEYWORDS,
825      __remove_doc__ },
826     {"listxattr",  pylistxattr, METH_VARARGS, __pylistxattr_doc__ },
827     {"list",  (PyCFunction) xattr_list, METH_VARARGS | METH_KEYWORDS,
828      __list_doc__ },
829     {NULL, NULL, 0, NULL}        /* Sentinel */
830 };
831
832 static char __xattr_doc__[] = \
833     "Access extended filesystem attributes\n"
834     "\n"
835     "This module gives access to the extended attributes present\n"
836     "in some operating systems/filesystems. You can list attributes,\n"
837     "get, set and remove them.\n"
838     "\n"
839     "The module exposes two sets of functions:\n"
840     "  - the 'old' L{listxattr}, L{getxattr}, L{setxattr}, L{removexattr}\n"
841     "    functions which are deprecated since version 0.4\n"
842     "  - the new L{list}, L{get}, L{get_all}, L{set}, L{remove} functions\n"
843     "    which expose a namespace-aware API and simplify a bit the calling\n"
844     "    model by using keyword arguments\n"
845     "\n"
846     "Example: \n\n"
847     "  >>> import xattr\n"
848     "  >>> xattr.listxattr(\"file.txt\")\n"
849     "  ['user.mime_type']\n"
850     "  >>> xattr.getxattr(\"file.txt\", \"user.mime_type\")\n"
851     "  'text/plain'\n"
852     "  >>> xattr.setxattr(\"file.txt\", \"user.comment\", "
853     "\"Simple text file\")\n"
854     "  >>> xattr.listxattr(\"file.txt\")\n"
855     "  ['user.mime_type', 'user.comment']\n"
856     "  >>> xattr.removexattr (\"file.txt\", \"user.comment\")\n"
857     "\n"
858     "@note: Most or all errors reported by the system while using the xattr\n"
859     "library will be reported by raising a L{EnvironmentError}; under Linux,\n"
860     "the following C{errno} values are used:\n"
861     "  - C{ENOATTR} and C{ENODATA} mean that the attribute name is invalid\n"
862     "  - C{ENOTSUP} and C{EOPNOTSUPP} mean that the filesystem does not\n"
863     "    support extended attributes, or that the namespace is invalid\n"
864     "  - C{E2BIG} mean that the attribute value is too big\n"
865     "  - C{ERANGE} mean that the attribute name is too big (it might also\n"
866     "    mean an error in the xattr module itself)\n"
867     "  - C{ENOSPC} and C{EDQUOT} are documented as meaning out of disk space\n"
868     "    or out of disk space because of quota limits\n"
869     "\n"
870     "@group Deprecated API: *xattr\n"
871     "@group Namespace constants: NS_*\n"
872     "@group set function flags: XATTR_CREATE, XATTR_REPLACE\n"
873     "@sort: list, get, get_all, set, remove, listxattr, getxattr, setxattr\n"
874     "    removexattr\n"
875     ;
876
877 void
878 initxattr(void)
879 {
880     PyObject *m = Py_InitModule3("xattr", xattr_methods, __xattr_doc__);
881
882     PyModule_AddStringConstant(m, "__author__", _XATTR_AUTHOR);
883     PyModule_AddStringConstant(m, "__contact__", _XATTR_EMAIL);
884     PyModule_AddStringConstant(m, "__version__", _XATTR_VERSION);
885     PyModule_AddStringConstant(m, "__docformat__", "epytext en");
886
887     PyModule_AddIntConstant(m, "XATTR_CREATE", XATTR_CREATE);
888     PyModule_AddIntConstant(m, "XATTR_REPLACE", XATTR_REPLACE);
889
890     /* namespace constants */
891     PyModule_AddStringConstant(m, "NS_SECURITY", "security");
892     PyModule_AddStringConstant(m, "NS_SYSTEM", "system");
893     PyModule_AddStringConstant(m, "NS_TRUSTED", "trusted");
894     PyModule_AddStringConstant(m, "NS_USER", "user");
895
896 }