]> git.k1024.org Git - pyxattr.git/blob - xattr.c
Move to goto-style error exit
[pyxattr.git] / xattr.c
1 #include <Python.h>
2 #include <attr/xattr.h>
3
4 /** Converts from a string, file or int argument to what we need. */
5 static int convertObj(PyObject *myobj, int *ishandle, int *filehandle,
6                       char **filename) {
7     if(PyString_Check(myobj)) {
8         *ishandle = 0;
9         *filename = PyString_AS_STRING(myobj);
10     } else if((*filehandle = PyObject_AsFileDescriptor(myobj)) != -1) {
11         *ishandle = 1;
12     } else {
13         PyErr_SetString(PyExc_TypeError, "argument 1 must be string or int");
14         return 0;
15     }
16     return 1;
17 }
18
19 /* Checks if an attribute name matches an optional namespace */
20 static int matches_ns(const char *name, const char *ns) {
21     size_t ns_size;
22     if (ns == NULL)
23         return 1;
24     ns_size = strlen(ns);
25
26     if (strlen(name) > ns_size && !strncmp(name, ns, ns_size) &&
27         name[ns_size] == '.')
28         return 1;
29     return 0;
30 }
31
32 /* Wrapper for getxattr */
33 static char __pygetxattr_doc__[] =
34     "Get the value of a given extended attribute.\n"
35     "\n"
36     "Parameters:\n"
37     "  - a string representing filename, or a file-like object,\n"
38     "    or a file descriptor; this represents the file on \n"
39     "    which to act\n"
40     "  - a string, representing the attribute whose value to retrieve;\n"
41     "    usually in form of system.posix_acl or user.mime_type\n"
42     "  - (optional) a boolean value (defaults to false), which, if\n"
43     "    the file name given is a symbolic link, makes the\n"
44     "    function operate on the symbolic link itself instead\n"
45     "    of its target;\n"
46     "@deprecated: this function has been replace with the L{get_all} function"
47     " which replaces the positional parameters with keyword ones\n"
48     ;
49
50 static PyObject *
51 pygetxattr(PyObject *self, PyObject *args)
52 {
53     PyObject *myarg;
54     char *file = NULL;
55     int filedes = -1, ishandle, dolink=0;
56     char *attrname;
57     char *buf;
58     int nalloc, nret;
59     PyObject *res;
60
61     /* Parse the arguments */
62     if (!PyArg_ParseTuple(args, "Os|i", &myarg, &attrname, &dolink))
63         return NULL;
64     if(!convertObj(myarg, &ishandle, &filedes, &file))
65         return NULL;
66
67     /* Find out the needed size of the buffer */
68     nalloc = ishandle ?
69         fgetxattr(filedes, attrname, NULL, 0) :
70         dolink ?
71         lgetxattr(file, attrname, NULL, 0) :
72         getxattr(file, attrname, NULL, 0);
73     if(nalloc == -1) {
74         return PyErr_SetFromErrno(PyExc_IOError);
75     }
76
77     /* Try to allocate the memory, using Python's allocator */
78     if((buf = PyMem_Malloc(nalloc)) == NULL) {
79         PyErr_NoMemory();
80         return NULL;
81     }
82
83     /* Now retrieve the attribute value */
84     nret = ishandle ?
85         fgetxattr(filedes, attrname, buf, nalloc) :
86         dolink ?
87         lgetxattr(file, attrname, buf, nalloc) :
88         getxattr(file, attrname, buf, nalloc);
89     if(nret == -1) {
90         PyMem_Free(buf);
91         return PyErr_SetFromErrno(PyExc_IOError);
92     }
93
94     /* Create the string which will hold the result */
95     res = PyString_FromStringAndSize(buf, nret);
96
97     /* Free the buffer, now it is no longer needed */
98     PyMem_Free(buf);
99
100     /* Return the result */
101     return res;
102 }
103
104 /* Wrapper for getxattr */
105 static char __get_all_doc__[] =
106     "Get all the extended attributes of an item.\n"
107     "\n"
108     "This function performs a bulk-get of all extended attribute names\n"
109     "and the corresponding value.\n"
110     "Example:\n"
111     "  >>> xattr.get_all('/path/to/file')\n"
112     "  [('user.mime-type', 'plain/text'), ('user.comment', 'test'),"
113     " ('system.posix_acl_access', '\\x02\\x00...')]\n"
114     "  >>> xattr.get_all('/path/to/file', namespace=xattr.NS_USER)\n"
115     "  [('user.mime-type', 'plain/text'), ('user.comment', 'test')]\n"
116     "\n"
117     "@param item: the item to query; either a string representing the"
118     " filename, or a file-like object, or a file descriptor\n"
119     "@keyword namespace: an optional namespace for filtering the"
120     " attributes; for example, querying all user attributes can be"
121     " accomplished by passing namespace=L{NS_USER}\n"
122     "@type namespace: string\n"
123     "@keyword nofollow: if passed and true, if the target file is a symbolic"
124     " link,"
125     " the attributes for the link itself will be returned, instead of the"
126     " attributes of the target\n"
127     "@type nofollow: boolean\n"
128     "@return: list of tuples (name, value)\n"
129     ;
130
131 static PyObject *
132 get_all(PyObject *self, PyObject *args, PyObject *keywds)
133 {
134     PyObject *myarg;
135     char *file = NULL;
136     int filedes = -1, ishandle, dolink=0;
137     char *ns = NULL;
138     char *buf_list, *buf_val;
139     char *s;
140     size_t nalloc, nlist, nval;
141     PyObject *mylist;
142     static char *kwlist[] = {"item", "nofollow", "namespace", NULL};
143
144     /* Parse the arguments */
145     if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|iz", kwlist,
146                                      &myarg, &dolink, &ns))
147         return NULL;
148     if(!convertObj(myarg, &ishandle, &filedes, &file))
149         return NULL;
150
151     /* Compute first the list of attributes */
152
153     /* Find out the needed size of the buffer for the attribute list */
154     nalloc = ishandle ?
155         flistxattr(filedes, NULL, 0) :
156         dolink ?
157         llistxattr(file, NULL, 0) :
158         listxattr(file, NULL, 0);
159
160     if(nalloc == -1) {
161         return PyErr_SetFromErrno(PyExc_IOError);
162     }
163
164     /* Try to allocate the memory, using Python's allocator */
165     if((buf_list = PyMem_Malloc(nalloc)) == NULL) {
166         PyErr_NoMemory();
167         return NULL;
168     }
169
170     /* Now retrieve the list of attributes */
171     nlist = ishandle ?
172         flistxattr(filedes, buf_list, nalloc) :
173         dolink ?
174         llistxattr(file, buf_list, nalloc) :
175         listxattr(file, buf_list, nalloc);
176
177     if(nlist == -1) {
178         PyErr_SetFromErrno(PyExc_IOError);
179         goto free_buf_list;
180     }
181
182     /* Create the list which will hold the result */
183     mylist = PyList_New(0);
184     nalloc = 256;
185     if((buf_val = PyMem_Malloc(nalloc)) == NULL) {
186         PyErr_NoMemory();
187         goto free_list;
188     }
189
190     /* Create and insert the attributes as strings in the list */
191     for(s = buf_list; s - buf_list < nlist; s += strlen(s) + 1) {
192         PyObject *my_tuple;
193         int missing;
194
195         if(!matches_ns(s, ns))
196             continue;
197         /* Now retrieve the attribute value */
198         missing = 0;
199         while(1) {
200             nval = ishandle ?
201                 fgetxattr(filedes, s, buf_val, nalloc) :
202                 dolink ?
203                 lgetxattr(file, s, buf_val, nalloc) :
204                 getxattr(file, s, buf_val, nalloc);
205
206             if(nval == -1) {
207                 if(errno == ERANGE) {
208                     nval = ishandle ?
209                         fgetxattr(filedes, s, NULL, 0) :
210                         dolink ?
211                         lgetxattr(file, s, NULL, 0) :
212                         getxattr(file, s, NULL, 0);
213                     if((buf_val = PyMem_Realloc(buf_val, nval)) == NULL)
214                         goto free_list;
215                     nalloc = nval;
216                     continue;
217                 } else if(errno == ENODATA || errno == ENOATTR) {
218                     /* this attribute has gone away since we queried
219                        the attribute list */
220                     missing = 1;
221                     break;
222                 }
223                 goto exit_errno;
224             }
225             break;
226         }
227         if(missing)
228             continue;
229         my_tuple = Py_BuildValue("ss#", s, buf_val, nval);
230
231         PyList_Append(mylist, my_tuple);
232         Py_DECREF(my_tuple);
233     }
234
235     /* Free the buffers, now they are no longer needed */
236     PyMem_Free(buf_val);
237     PyMem_Free(buf_list);
238
239     /* Return the result */
240     return mylist;
241  exit_errno:
242     PyErr_SetFromErrno(PyExc_IOError);
243  free_buf_val:
244     PyMem_Free(buf_val);
245  free_list:
246     Py_DECREF(mylist);
247  free_buf_list:
248     PyMem_Free(buf_list);
249     return NULL;
250 }
251
252
253 static char __pysetxattr_doc__[] =
254     "Set the value of a given extended attribute.\n"
255     "Be carefull in case you want to set attributes on symbolic\n"
256     "links, you have to use all the 5 parameters; use 0 for the \n"
257     "flags value if you want the default behavior (create or "
258     "replace)\n"
259     "\n"
260     "Parameters:\n"
261     "  - a string representing filename, or a file-like object,\n"
262     "    or a file descriptor; this represents the file on \n"
263     "    which to act\n"
264     "  - a string, representing the attribute whose value to set;\n"
265     "    usually in form of system.posix_acl or user.mime_type\n"
266     "  - a string, possibly with embedded NULLs; note that there\n"
267     "    are restrictions regarding the size of the value, for\n"
268     "    example, for ext2/ext3, maximum size is the block size\n"
269     "  - (optional) flags; if 0 or ommited the attribute will be \n"
270     "    created or replaced; if XATTR_CREATE, the attribute \n"
271     "    will be created, giving an error if it already exists;\n"
272     "    of XATTR_REPLACE, the attribute will be replaced,\n"
273     "    giving an error if it doesn't exists;\n"
274     "  - (optional) a boolean value (defaults to false), which, if\n"
275     "    the file name given is a symbolic link, makes the\n"
276     "    function operate on the symbolic link itself instead\n"
277     "    of its target;"
278     ;
279
280 /* Wrapper for setxattr */
281 static PyObject *
282 pysetxattr(PyObject *self, PyObject *args)
283 {
284     PyObject *myarg;
285     char *file;
286     int ishandle, filedes, dolink=0;
287     char *attrname;
288     char *buf;
289     int bufsize, nret;
290     int flags = 0;
291
292     /* Parse the arguments */
293     if (!PyArg_ParseTuple(args, "Oss#|bi", &myarg, &attrname,
294                           &buf, &bufsize, &flags, &dolink))
295         return NULL;
296     if(!convertObj(myarg, &ishandle, &filedes, &file))
297         return NULL;
298
299     /* Set the attribute's value */
300     nret = ishandle ?
301         fsetxattr(filedes, attrname, buf, bufsize, flags) :
302         dolink ?
303         lsetxattr(file, attrname, buf, bufsize, flags) :
304         setxattr(file, attrname, buf, bufsize, flags);
305
306     if(nret == -1) {
307         return PyErr_SetFromErrno(PyExc_IOError);
308     }
309
310     /* Return the result */
311     Py_INCREF(Py_None);
312     return Py_None;
313 }
314
315 static char __pyremovexattr_doc__[] =
316     "Remove an attribute from a file\n"
317     "\n"
318     "Parameters:\n"
319     "  - a string representing filename, or a file-like object,\n"
320     "    or a file descriptor; this represents the file on \n"
321     "    which to act\n"
322     "  - a string, representing the attribute to be removed;\n"
323     "    usually in form of system.posix_acl or user.mime_type\n"
324     "  - (optional) a boolean value (defaults to false), which, if\n"
325     "    the file name given is a symbolic link, makes the\n"
326     "    function operate on the symbolic link itself instead\n"
327     "    of its target;\n"
328     ;
329
330 /* Wrapper for removexattr */
331 static PyObject *
332 pyremovexattr(PyObject *self, PyObject *args)
333 {
334     PyObject *myarg;
335     char *file;
336     int ishandle, filedes, dolink=0;
337     char *attrname;
338     int nret;
339
340     /* Parse the arguments */
341     if (!PyArg_ParseTuple(args, "Os|i", &myarg, &attrname, &dolink))
342         return NULL;
343
344     if(!convertObj(myarg, &ishandle, &filedes, &file))
345         return NULL;
346
347     /* Remove the attribute */
348     nret = ishandle ?
349         fremovexattr(filedes, attrname) :
350         dolink ?
351         lremovexattr(file, attrname) :
352         removexattr(file, attrname);
353
354     if(nret == -1)
355         return PyErr_SetFromErrno(PyExc_IOError);
356
357     /* Return the result */
358     Py_INCREF(Py_None);
359     return Py_None;
360 }
361
362 static char __pylistxattr_doc__[] =
363     "Return the list of attribute names for a file\n"
364     "\n"
365     "Parameters:\n"
366     "  - a string representing filename, or a file-like object,\n"
367     "    or a file descriptor; this represents the file to \n"
368     "    be queried\n"
369     "  - (optional) a boolean value (defaults to false), which, if\n"
370     "    the file name given is a symbolic link, makes the\n"
371     "    function operate on the symbolic link itself instead\n"
372     "    of its target;\n"
373     ;
374
375 /* Wrapper for listxattr */
376 static PyObject *
377 pylistxattr(PyObject *self, PyObject *args)
378 {
379     char *file = NULL;
380     int filedes = -1;
381     char *buf;
382     int ishandle, dolink=0;
383     int nalloc, nret;
384     PyObject *myarg;
385     PyObject *mylist;
386     int nattrs;
387     char *s;
388
389     /* Parse the arguments */
390     if (!PyArg_ParseTuple(args, "O|i", &myarg, &dolink))
391         return NULL;
392     if(!convertObj(myarg, &ishandle, &filedes, &file))
393         return NULL;
394
395     /* Find out the needed size of the buffer */
396     nalloc = ishandle ?
397         flistxattr(filedes, NULL, 0) :
398         dolink ?
399         llistxattr(file, NULL, 0) :
400         listxattr(file, NULL, 0);
401
402     if(nalloc == -1) {
403         return PyErr_SetFromErrno(PyExc_IOError);
404     }
405
406     /* Try to allocate the memory, using Python's allocator */
407     if((buf = PyMem_Malloc(nalloc)) == NULL) {
408         PyErr_NoMemory();
409         return NULL;
410     }
411
412     /* Now retrieve the list of attributes */
413     nret = ishandle ?
414         flistxattr(filedes, buf, nalloc) :
415         dolink ?
416         llistxattr(file, buf, nalloc) :
417         listxattr(file, buf, nalloc);
418
419     if(nret == -1) {
420         return PyErr_SetFromErrno(PyExc_IOError);
421     }
422
423     /* Compute the number of attributes in the list */
424     for(s = buf, nattrs = 0; (s - buf) < nret; s += strlen(s) + 1) {
425         nattrs++;
426     }
427
428     /* Create the list which will hold the result */
429     mylist = PyList_New(nattrs);
430
431     /* Create and insert the attributes as strings in the list */
432     for(s = buf, nattrs = 0; s - buf < nret; s += strlen(s) + 1) {
433         PyList_SET_ITEM(mylist, nattrs, PyString_FromString(s));
434         nattrs++;
435     }
436
437     /* Free the buffer, now it is no longer needed */
438     PyMem_Free(buf);
439
440     /* Return the result */
441     return mylist;
442 }
443
444 static PyMethodDef xattr_methods[] = {
445     {"getxattr",  pygetxattr, METH_VARARGS, __pygetxattr_doc__ },
446     {"get_all", (PyCFunction) get_all, METH_VARARGS | METH_KEYWORDS,
447      __get_all_doc__ },
448     {"setxattr",  pysetxattr, METH_VARARGS, __pysetxattr_doc__ },
449     {"removexattr",  pyremovexattr, METH_VARARGS, __pyremovexattr_doc__ },
450     {"listxattr",  pylistxattr, METH_VARARGS, __pylistxattr_doc__ },
451     {NULL, NULL, 0, NULL}        /* Sentinel */
452 };
453
454 static char __xattr_doc__[] = \
455     "Access extended filesystem attributes\n"
456     "\n"
457     "This module gives access to the extended attributes present\n"
458     "in some operating systems/filesystems. You can list attributes,\n"
459     "get, set and remove them.\n"
460     "The last and optional parameter for all functions is a boolean \n"
461     "value which enables the 'l-' version of the functions - acting\n"
462     "on symbolic links and not their destination.\n"
463     "\n"
464     "Example: \n\n"
465     "  >>> import xattr\n"
466     "  >>> xattr.listxattr(\"file.txt\")\n"
467     "  ['user.mime_type']\n"
468     "  >>> xattr.getxattr(\"file.txt\", \"user.mime_type\")\n"
469     "  'text/plain'\n"
470     "  >>> xattr.setxattr(\"file.txt\", \"user.comment\", "
471     "\"Simple text file\")\n"
472     "  >>> xattr.listxattr(\"file.txt\")\n"
473     "  ['user.mime_type', 'user.comment']\n"
474     "  >>> xattr.removexattr (\"file.txt\", \"user.comment\")\n"
475     ""
476     ;
477
478 void
479 initxattr(void)
480 {
481     PyObject *m = Py_InitModule3("xattr", xattr_methods, __xattr_doc__);
482
483     PyModule_AddIntConstant(m, "XATTR_CREATE", XATTR_CREATE);
484     PyModule_AddIntConstant(m, "XATTR_REPLACE", XATTR_REPLACE);
485
486     /* namespace constants */
487     PyModule_AddStringConstant(m, "NS_SECURITY", "security");
488     PyModule_AddStringConstant(m, "NS_SYSTEM", "system");
489     PyModule_AddStringConstant(m, "NS_TRUSTED", "trusted");
490     PyModule_AddStringConstant(m, "NS_USER", "user");
491
492 }