]> git.k1024.org Git - pylibacl.git/blob - acl.c
Switch from epydoc to sphinx
[pylibacl.git] / acl.c
1 /*
2     posix1e - a python module exposing the posix acl functions
3
4     Copyright (C) 2002-2009, 2012 Iustin Pop <iusty@k1024.org>
5
6     This library is free software; you can redistribute it and/or
7     modify it under the terms of the GNU Lesser General Public
8     License as published by the Free Software Foundation; either
9     version 2.1 of the License, or (at your option) any later version.
10
11     This library is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14     Lesser General Public License for more details.
15
16     You should have received a copy of the GNU Lesser General Public
17     License along with this library; if not, write to the Free Software
18     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19     02110-1301  USA
20
21 */
22
23 #include <Python.h>
24
25 #include <sys/types.h>
26 #include <sys/acl.h>
27
28 #ifdef HAVE_LINUX
29 #include <acl/libacl.h>
30 #define get_perm acl_get_perm
31 #elif HAVE_FREEBSD
32 #define get_perm acl_get_perm_np
33 #endif
34
35 #if PY_MAJOR_VERSION >= 3
36 #define IS_PY3K
37 #define PyInt_Check(op) PyLong_Check(op)
38 #define PyInt_FromString PyLong_FromString
39 #define PyInt_FromUnicode PyLong_FromUnicode
40 #define PyInt_FromLong PyLong_FromLong
41 #define PyInt_FromSize_t PyLong_FromSize_t
42 #define PyInt_FromSsize_t PyLong_FromSsize_t
43 #define PyInt_AsLong PyLong_AsLong
44 #define PyInt_AsSsize_t PyLong_AsSsize_t
45 #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
46 #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
47 #define PyInt_AS_LONG PyLong_AS_LONG
48 #else
49 #define PyBytes_Check PyString_Check
50 #define PyBytes_AS_STRING PyString_AS_STRING
51 #define PyBytes_FromStringAndSize PyString_FromStringAndSize
52 #define PyBytes_FromString PyString_FromString
53 #define PyBytes_FromFormat PyString_FromFormat
54 #define PyBytes_ConcatAndDel PyString_ConcatAndDel
55
56 /* Python 2.6 already defines Py_TYPE */
57 #ifndef Py_TYPE
58 #define Py_TYPE(o)    (((PyObject*)(o))->ob_type)
59 #endif
60 #endif
61
62 static PyTypeObject ACL_Type;
63 static PyObject* ACL_applyto(PyObject* obj, PyObject* args);
64 static PyObject* ACL_valid(PyObject* obj, PyObject* args);
65
66 #ifdef HAVE_ACL_COPY_EXT
67 static PyObject* ACL_get_state(PyObject *obj, PyObject* args);
68 static PyObject* ACL_set_state(PyObject *obj, PyObject* args);
69 #endif
70
71 #ifdef HAVE_LEVEL2
72 static PyTypeObject Entry_Type;
73 static PyTypeObject Permset_Type;
74 static PyObject* Permset_new(PyTypeObject* type, PyObject* args,
75                              PyObject *keywds);
76 #endif
77
78 static acl_perm_t holder_ACL_EXECUTE = ACL_EXECUTE;
79 static acl_perm_t holder_ACL_READ = ACL_READ;
80 static acl_perm_t holder_ACL_WRITE = ACL_WRITE;
81
82 typedef struct {
83     PyObject_HEAD
84     acl_t acl;
85 #ifdef HAVE_LEVEL2
86     int entry_id;
87 #endif
88 } ACL_Object;
89
90 #ifdef HAVE_LEVEL2
91
92 typedef struct {
93     PyObject_HEAD
94     PyObject *parent_acl; /* The parent acl, so it won't run out on us */
95     acl_entry_t entry;
96 } Entry_Object;
97
98 typedef struct {
99     PyObject_HEAD
100     PyObject *parent_entry; /* The parent entry, so it won't run out on us */
101     acl_permset_t permset;
102 } Permset_Object;
103
104 #endif
105
106 /* Creation of a new ACL instance */
107 static PyObject* ACL_new(PyTypeObject* type, PyObject* args,
108                          PyObject *keywds) {
109     PyObject* newacl;
110
111     newacl = type->tp_alloc(type, 0);
112
113     if(newacl != NULL) {
114         ((ACL_Object*)newacl)->acl = NULL;
115 #ifdef HAVEL_LEVEL2
116         ((ACL_Object*)newacl)->entry_id = ACL_FIRST_ENTRY;
117 #endif
118     }
119
120     return newacl;
121 }
122
123 /* Initialization of a new ACL instance */
124 static int ACL_init(PyObject* obj, PyObject* args, PyObject *keywds) {
125     ACL_Object* self = (ACL_Object*) obj;
126 #ifdef HAVE_LINUX
127     static char *kwlist[] = { "file", "fd", "text", "acl", "filedef",
128                               "mode", NULL };
129     char *format = "|etisO!sH";
130     mode_t mode = 0;
131 #else
132     static char *kwlist[] = { "file", "fd", "text", "acl", "filedef", NULL };
133     char *format = "|etisO!s";
134 #endif
135     char *file = NULL;
136     char *filedef = NULL;
137     char *text = NULL;
138     int fd = -1;
139     ACL_Object* thesrc = NULL;
140
141     if(!PyTuple_Check(args) || PyTuple_Size(args) != 0 ||
142        (keywds != NULL && PyDict_Check(keywds) && PyDict_Size(keywds) > 1)) {
143         PyErr_SetString(PyExc_ValueError, "a max of one keyword argument"
144                         " must be passed");
145         return -1;
146     }
147     if(!PyArg_ParseTupleAndKeywords(args, keywds, format, kwlist,
148                                     NULL, &file, &fd, &text, &ACL_Type,
149                                     &thesrc, &filedef
150 #ifdef HAVE_LINUX
151                                     , &mode
152 #endif
153                                     ))
154         return -1;
155
156     /* Free the old acl_t without checking for error, we don't
157      * care right now */
158     if(self->acl != NULL)
159         acl_free(self->acl);
160
161     if(file != NULL)
162         self->acl = acl_get_file(file, ACL_TYPE_ACCESS);
163     else if(text != NULL)
164         self->acl = acl_from_text(text);
165     else if(fd != -1)
166         self->acl = acl_get_fd(fd);
167     else if(thesrc != NULL)
168         self->acl = acl_dup(thesrc->acl);
169     else if(filedef != NULL)
170         self->acl = acl_get_file(filedef, ACL_TYPE_DEFAULT);
171 #ifdef HAVE_LINUX
172     else if(PyMapping_HasKeyString(keywds, kwlist[5]))
173         self->acl = acl_from_mode(mode);
174 #endif
175     else
176         self->acl = acl_init(0);
177
178     if(self->acl == NULL) {
179         PyErr_SetFromErrno(PyExc_IOError);
180         return -1;
181     }
182
183     return 0;
184 }
185
186 /* Standard type functions */
187 static void ACL_dealloc(PyObject* obj) {
188     ACL_Object *self = (ACL_Object*) obj;
189     PyObject *err_type, *err_value, *err_traceback;
190     int have_error = PyErr_Occurred() ? 1 : 0;
191
192     if (have_error)
193         PyErr_Fetch(&err_type, &err_value, &err_traceback);
194     if(self->acl != NULL && acl_free(self->acl) != 0)
195         PyErr_WriteUnraisable(obj);
196     if (have_error)
197         PyErr_Restore(err_type, err_value, err_traceback);
198     PyObject_DEL(self);
199 }
200
201 /* Converts the acl to a text format */
202 static PyObject* ACL_str(PyObject *obj) {
203     char *text;
204     ACL_Object *self = (ACL_Object*) obj;
205     PyObject *ret;
206
207     text = acl_to_text(self->acl, NULL);
208     if(text == NULL) {
209         return PyErr_SetFromErrno(PyExc_IOError);
210     }
211     ret = PyBytes_FromString(text);
212     if(acl_free(text) != 0) {
213         Py_XDECREF(ret);
214         return PyErr_SetFromErrno(PyExc_IOError);
215     }
216     return ret;
217 }
218
219 #ifdef HAVE_LINUX
220 static char __to_any_text_doc__[] =
221   "Convert the ACL to a custom text format.\n"
222   "\n"
223   "This method encapsulates the acl_to_any_text function. It allows a \n"
224   "customized text format to be generated for the ACL. See\n"
225   "acl_to_any_text(3) for more details.\n"
226   "\n"
227   "Parameters:\n"
228   "  - prefix: if given, this string will be prepended to all lines\n"
229   "  - separator: a single character (defaults to '\\n'); this will be\n"
230   "               user to separate the entries in the ACL\n"
231   "  - options: a bitwise combination of:\n"
232   "    -  TEXT_ABBREVIATE: use 'u' instead of 'user', 'g' instead of \n"
233   "                       'group', etc.\n"
234   "    -  TEXT_NUMERIC_IDS: User and group IDs are included as decimal\n"
235   "                         numbers instead of names\n"
236   "    -  TEXT_SOME_EFFECTIVE: Include comments denoting the effective\n"
237   "                            permissions when some are masked\n"
238   "    -  TEXT_ALL_EFFECTIVE: Include comments after all ACL entries\n"
239   "                           affected by an ACL_MASK entry\n"
240   "    -  TEXT_SMART_INDENT: Used in combination with the _EFFECTIVE\n"
241   "                          options, this will ensure that comments \n"
242   "                          are alligned to the fourth tab position\n"
243   "                          (assuming one tab equals eight spaces)\n"
244   ;
245
246 /* Converts the acl to a custom text format */
247 static PyObject* ACL_to_any_text(PyObject *obj, PyObject *args,
248                                  PyObject *kwds) {
249     char *text;
250     ACL_Object *self = (ACL_Object*) obj;
251     PyObject *ret;
252     const char *arg_prefix = NULL;
253     char arg_separator = '\n';
254     int arg_options = 0;
255     static char *kwlist[] = {"prefix", "separator", "options", NULL};
256
257     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|sci", kwlist, &arg_prefix,
258                                      &arg_separator, &arg_options))
259       return NULL;
260
261     text = acl_to_any_text(self->acl, arg_prefix, arg_separator, arg_options);
262     if(text == NULL) {
263         return PyErr_SetFromErrno(PyExc_IOError);
264     }
265     ret = PyBytes_FromString(text);
266     if(acl_free(text) != 0) {
267         Py_XDECREF(ret);
268         return PyErr_SetFromErrno(PyExc_IOError);
269     }
270     return ret;
271 }
272
273 static char __check_doc__[] =
274     "Check the ACL validity.\n"
275     "\n"
276     "This is a non-portable, Linux specific extension that allow more\n"
277     "information to be retrieved in case an ACL is not valid than the\n"
278     "validate() method.\n"
279     "\n"
280     "This method will return either False (the ACL is valid), or a tuple\n"
281     "with two elements. The first element is one of the following\n"
282     "constants:\n"
283     "  - ACL_MULTI_ERROR: The ACL contains multiple entries that have a\n"
284     "                     tag type that may occur at most once\n"
285     "  - ACL_DUPLICATE_ERROR: The ACL contains multiple ACL_USER or \n"
286     "                         ACL_GROUP entries  with the same ID\n"
287     "  - ACL_MISS_ERROR: A required entry is missing\n"
288     "  - ACL_ENTRY_ERROR: The ACL contains an invalid entry tag type\n"
289     "\n"
290     "The second element of the tuple is the index of the entry that is\n"
291     "invalid (in the same order as by iterating over the ACL entry)\n"
292     ;
293
294 /* The acl_check method */
295 static PyObject* ACL_check(PyObject* obj, PyObject* args) {
296     ACL_Object *self = (ACL_Object*) obj;
297     int result;
298     int eindex;
299
300     if((result = acl_check(self->acl, &eindex)) == -1)
301         return PyErr_SetFromErrno(PyExc_IOError);
302     if(result == 0) {
303         Py_RETURN_FALSE;
304     }
305     return Py_BuildValue("(ii)", result, eindex);
306 }
307
308 /* Implementation of the rich compare for ACLs */
309 static PyObject* ACL_richcompare(PyObject* o1, PyObject* o2, int op) {
310     ACL_Object *acl1, *acl2;
311     int n;
312     PyObject *ret;
313
314     if(!PyObject_IsInstance(o2, (PyObject*)&ACL_Type)) {
315         if(op == Py_EQ)
316             Py_RETURN_FALSE;
317         if(op == Py_NE)
318             Py_RETURN_TRUE;
319         PyErr_SetString(PyExc_TypeError, "can only compare to an ACL");
320         return NULL;
321     }
322
323     acl1 = (ACL_Object*)o1;
324     acl2 = (ACL_Object*)o2;
325     if((n=acl_cmp(acl1->acl, acl2->acl))==-1)
326         return PyErr_SetFromErrno(PyExc_IOError);
327     switch(op) {
328     case Py_EQ:
329         ret = n == 0 ? Py_True : Py_False;
330         break;
331     case Py_NE:
332         ret = n == 1 ? Py_True : Py_False;
333         break;
334     default:
335         ret = Py_NotImplemented;
336     }
337     Py_INCREF(ret);
338     return ret;
339 }
340
341 static char __equiv_mode_doc__[] =
342     "Return the octal mode the ACL is equivalent to.\n"
343     "\n"
344     "This is a non-portable, Linux specific extension that checks\n"
345     "if the ACL is a basic ACL and returns the corresponding mode.\n"
346     "\n"
347     "An IOerror exception will be raised if the ACL is an extended ACL\n"
348     ;
349
350 /* The acl_equiv_mode method */
351 static PyObject* ACL_equiv_mode(PyObject* obj, PyObject* args) {
352     ACL_Object *self = (ACL_Object*) obj;
353     mode_t mode;
354
355     if(acl_equiv_mode(self->acl, &mode) == -1)
356         return PyErr_SetFromErrno(PyExc_IOError);
357     return PyInt_FromLong(mode);
358 }
359 #endif
360
361 /* Implementation of the compare for ACLs */
362 static int ACL_nocmp(PyObject* o1, PyObject* o2) {
363
364     PyErr_SetString(PyExc_TypeError, "cannot compare ACLs using cmp()");
365     return -1;
366 }
367
368 /* Custom methods */
369 static char __applyto_doc__[] =
370     "Apply the ACL to a file or filehandle.\n"
371     "\n"
372     "Parameters:\n"
373     "  - either a filename or a file-like object or an integer; this\n"
374     "    represents the filesystem object on which to act\n"
375     "  - optional flag representing the type of ACL to set, either\n"
376     "    ACL_TYPE_ACCESS (default) or ACL_TYPE_DEFAULT\n"
377     ;
378
379 /* Applyes the ACL to a file */
380 static PyObject* ACL_applyto(PyObject* obj, PyObject* args) {
381     ACL_Object *self = (ACL_Object*) obj;
382     PyObject *myarg;
383     acl_type_t type = ACL_TYPE_ACCESS;
384     int nret;
385     int fd;
386
387     if (!PyArg_ParseTuple(args, "O|I", &myarg, &type))
388         return NULL;
389
390     if(PyBytes_Check(myarg)) {
391         char *filename = PyBytes_AS_STRING(myarg);
392         nret = acl_set_file(filename, type, self->acl);
393     } else if (PyUnicode_Check(myarg)) {
394         PyObject *o =
395             PyUnicode_AsEncodedString(myarg,
396                                       Py_FileSystemDefaultEncoding, "strict");
397         if (o == NULL)
398             return NULL;
399         const char *filename = PyBytes_AS_STRING(o);
400         nret = acl_set_file(filename, type, self->acl);
401         Py_DECREF(o);
402     } else if((fd = PyObject_AsFileDescriptor(myarg)) != -1) {
403         nret = acl_set_fd(fd, self->acl);
404     } else {
405         PyErr_SetString(PyExc_TypeError, "argument 1 must be string, int,"
406                         " or file-like object");
407         return 0;
408     }
409     if(nret == -1) {
410         return PyErr_SetFromErrno(PyExc_IOError);
411     }
412
413     /* Return the result */
414     Py_INCREF(Py_None);
415     return Py_None;
416 }
417
418 static char __valid_doc__[] =
419     "Test the ACL for validity.\n"
420     "\n"
421     "This method tests the ACL to see if it is a valid ACL\n"
422     "in terms of the filesystem. More precisely, it checks that:\n"
423     "\n"
424     "The ACL contains exactly one entry with each of the\n"
425     "ACL_USER_OBJ, ACL_GROUP_OBJ, and ACL_OTHER tag types. Entries\n"
426     "with ACL_USER and ACL_GROUP tag types may appear zero or more\n"
427     "times in an ACL. An ACL that contains entries of ACL_USER or\n"
428     "ACL_GROUP tag types must contain exactly one entry of the \n"
429     "ACL_MASK tag type. If an ACL contains no entries of\n"
430     "ACL_USER or ACL_GROUP tag types, the ACL_MASK entry is optional.\n"
431     "\n"
432     "All user ID qualifiers must be unique among all entries of\n"
433     "the ACL_USER tag type, and all group IDs must be unique among all\n"
434     "entries of ACL_GROUP tag type.\n"
435     "\n"
436     "The method will return 1 for a valid ACL and 0 for an invalid one.\n"
437     "This has been chosen because the specification for acl_valid in\n"
438     "the POSIX.1e standard documents only one possible value for errno\n"
439     "in case of an invalid ACL, so we can't differentiate between\n"
440     "classes of errors. Other suggestions are welcome.\n"
441     ;
442
443 /* Checks the ACL for validity */
444 static PyObject* ACL_valid(PyObject* obj, PyObject* args) {
445     ACL_Object *self = (ACL_Object*) obj;
446
447     if(acl_valid(self->acl) == -1) {
448         Py_RETURN_FALSE;
449     } else {
450         Py_RETURN_TRUE;
451     }
452 }
453
454 #ifdef HAVE_ACL_COPY_EXT
455 static PyObject* ACL_get_state(PyObject *obj, PyObject* args) {
456     ACL_Object *self = (ACL_Object*) obj;
457     PyObject *ret;
458     ssize_t size, nsize;
459     char *buf;
460
461     size = acl_size(self->acl);
462     if(size == -1)
463         return PyErr_SetFromErrno(PyExc_IOError);
464
465     if((ret = PyBytes_FromStringAndSize(NULL, size)) == NULL)
466         return NULL;
467     buf = PyBytes_AsString(ret);
468
469     if((nsize = acl_copy_ext(buf, self->acl, size)) == -1) {
470         Py_DECREF(ret);
471         return PyErr_SetFromErrno(PyExc_IOError);
472     }
473
474     return ret;
475 }
476
477 static PyObject* ACL_set_state(PyObject *obj, PyObject* args) {
478     ACL_Object *self = (ACL_Object*) obj;
479     const void *buf;
480     int bufsize;
481     acl_t ptr;
482
483     /* Parse the argument */
484     if (!PyArg_ParseTuple(args, "s#", &buf, &bufsize))
485         return NULL;
486
487     /* Try to import the external representation */
488     if((ptr = acl_copy_int(buf)) == NULL)
489         return PyErr_SetFromErrno(PyExc_IOError);
490
491     /* Free the old acl. Should we ignore errors here? */
492     if(self->acl != NULL) {
493         if(acl_free(self->acl) == -1)
494             return PyErr_SetFromErrno(PyExc_IOError);
495     }
496
497     self->acl = ptr;
498
499     /* Return the result */
500     Py_INCREF(Py_None);
501     return Py_None;
502 }
503 #endif
504
505 #ifdef HAVE_LEVEL2
506
507 /* tp_iter for the ACL type; since it can be iterated only
508  * destructively, the type is its iterator
509  */
510 static PyObject* ACL_iter(PyObject *obj) {
511     ACL_Object *self = (ACL_Object*)obj;
512     self->entry_id = ACL_FIRST_ENTRY;
513     Py_INCREF(obj);
514     return obj;
515 }
516
517 /* the tp_iternext function for the ACL type */
518 static PyObject* ACL_iternext(PyObject *obj) {
519     ACL_Object *self = (ACL_Object*)obj;
520     acl_entry_t the_entry_t;
521     Entry_Object *the_entry_obj;
522     int nerr;
523
524     nerr = acl_get_entry(self->acl, self->entry_id, &the_entry_t);
525     self->entry_id = ACL_NEXT_ENTRY;
526     if(nerr == -1)
527         return PyErr_SetFromErrno(PyExc_IOError);
528     else if(nerr == 0) {
529         /* Docs says this is not needed */
530         /*PyErr_SetObject(PyExc_StopIteration, Py_None);*/
531         return NULL;
532     }
533
534     the_entry_obj = (Entry_Object*) PyType_GenericNew(&Entry_Type, NULL, NULL);
535     if(the_entry_obj == NULL)
536         return NULL;
537
538     the_entry_obj->entry = the_entry_t;
539
540     the_entry_obj->parent_acl = obj;
541     Py_INCREF(obj); /* For the reference we have in entry->parent */
542
543     return (PyObject*)the_entry_obj;
544 }
545
546 static char __ACL_delete_entry_doc__[] =
547     "Deletes an entry from the ACL.\n"
548     "\n"
549     "Note: Only with level 2\n"
550     "Parameters:\n"
551     "  - the Entry object which should be deleted; note that after\n"
552     "    this function is called, that object is unusable any longer\n"
553     "    and should be deleted\n"
554     ;
555
556 /* Deletes an entry from the ACL */
557 static PyObject* ACL_delete_entry(PyObject *obj, PyObject *args) {
558     ACL_Object *self = (ACL_Object*)obj;
559     Entry_Object *e;
560
561     if (!PyArg_ParseTuple(args, "O!", &Entry_Type, &e))
562         return NULL;
563
564     if(acl_delete_entry(self->acl, e->entry) == -1)
565         return PyErr_SetFromErrno(PyExc_IOError);
566
567     /* Return the result */
568     Py_INCREF(Py_None);
569     return Py_None;
570 }
571
572 static char __ACL_calc_mask_doc__[] =
573     "Compute the file group class mask.\n"
574     "\n"
575     "The calc_mask() method calculates and sets the permissions \n"
576     "associated with the ACL_MASK Entry of the ACL.\n"
577     "The value of the new permissions is the union of the permissions \n"
578     "granted by all entries of tag type ACL_GROUP, ACL_GROUP_OBJ, or \n"
579     "ACL_USER.  If the ACL already contains an ACL_MASK entry, its \n"
580     "permissions are overwritten; if it does not contain an ACL_MASK \n"
581     "Entry, one is added.\n"
582     "\n"
583     "The order of existing entries in the ACL is undefined after this \n"
584     "function.\n"
585     ;
586
587 /* Updates the mask entry in the ACL */
588 static PyObject* ACL_calc_mask(PyObject *obj, PyObject *args) {
589     ACL_Object *self = (ACL_Object*)obj;
590
591     if(acl_calc_mask(&self->acl) == -1)
592         return PyErr_SetFromErrno(PyExc_IOError);
593
594     /* Return the result */
595     Py_INCREF(Py_None);
596     return Py_None;
597 }
598
599 static char __ACL_append_doc__[] =
600     "Append a new Entry to the ACL and return it.\n"
601     "\n"
602     "This is a convenience function to create a new Entry \n"
603     "and append it to the ACL.\n"
604     "If a parameter of type Entry instance is given, the \n"
605     "entry will be a copy of that one (as if copied with \n"
606     "Entry.copy()), otherwise, the new entry will be empty.\n"
607     ;
608
609 /* Convenience method to create a new Entry */
610 static PyObject* ACL_append(PyObject *obj, PyObject *args) {
611     ACL_Object* self = (ACL_Object*) obj;
612     Entry_Object* newentry;
613     Entry_Object* oldentry = NULL;
614     int nret;
615
616     newentry = (Entry_Object*)PyType_GenericNew(&Entry_Type, NULL, NULL);
617     if(newentry == NULL) {
618         return NULL;
619     }
620
621     if (!PyArg_ParseTuple(args, "|O!", &Entry_Type, &oldentry)) {
622         Py_DECREF(newentry);
623         return NULL;
624     }
625
626     nret = acl_create_entry(&self->acl, &newentry->entry);
627     if(nret == -1) {
628         Py_DECREF(newentry);
629         return PyErr_SetFromErrno(PyExc_IOError);
630     }
631
632     if(oldentry != NULL) {
633         nret = acl_copy_entry(newentry->entry, oldentry->entry);
634         if(nret == -1) {
635             Py_DECREF(newentry);
636             return PyErr_SetFromErrno(PyExc_IOError);
637         }
638     }
639
640     newentry->parent_acl = obj;
641     Py_INCREF(obj);
642
643     return (PyObject*)newentry;
644 }
645
646 /***** Entry type *****/
647
648 /* Creation of a new Entry instance */
649 static PyObject* Entry_new(PyTypeObject* type, PyObject* args,
650                            PyObject *keywds) {
651     PyObject* newentry;
652
653     newentry = PyType_GenericNew(type, args, keywds);
654
655     if(newentry != NULL) {
656         ((Entry_Object*)newentry)->entry = NULL;
657         ((Entry_Object*)newentry)->parent_acl = NULL;
658     }
659
660     return newentry;
661 }
662
663 /* Initialization of a new Entry instance */
664 static int Entry_init(PyObject* obj, PyObject* args, PyObject *keywds) {
665     Entry_Object* self = (Entry_Object*) obj;
666     ACL_Object* parent = NULL;
667
668     if (!PyArg_ParseTuple(args, "O!", &ACL_Type, &parent))
669         return -1;
670
671     if(acl_create_entry(&parent->acl, &self->entry) == -1) {
672         PyErr_SetFromErrno(PyExc_IOError);
673         return -1;
674     }
675
676     self->parent_acl = (PyObject*)parent;
677     Py_INCREF(parent);
678
679     return 0;
680 }
681
682 /* Free the Entry instance */
683 static void Entry_dealloc(PyObject* obj) {
684     Entry_Object *self = (Entry_Object*) obj;
685     PyObject *err_type, *err_value, *err_traceback;
686     int have_error = PyErr_Occurred() ? 1 : 0;
687
688     if (have_error)
689         PyErr_Fetch(&err_type, &err_value, &err_traceback);
690     if(self->parent_acl != NULL) {
691         Py_DECREF(self->parent_acl);
692         self->parent_acl = NULL;
693     }
694     if (have_error)
695         PyErr_Restore(err_type, err_value, err_traceback);
696     PyObject_DEL(self);
697 }
698
699 /* Converts the entry to a text format */
700 static PyObject* Entry_str(PyObject *obj) {
701     acl_tag_t tag;
702     uid_t qualifier;
703     void *p;
704     PyObject *format, *kind;
705     Entry_Object *self = (Entry_Object*) obj;
706
707     if(acl_get_tag_type(self->entry, &tag) == -1) {
708         PyErr_SetFromErrno(PyExc_IOError);
709         return NULL;
710     }
711     if(tag == ACL_USER || tag == ACL_GROUP) {
712         if((p = acl_get_qualifier(self->entry)) == NULL) {
713             PyErr_SetFromErrno(PyExc_IOError);
714             return NULL;
715         }
716         qualifier = *(uid_t*)p;
717         acl_free(p);
718     } else {
719         qualifier = 0;
720     }
721
722     format = PyBytes_FromString("ACL entry for ");
723     if(format == NULL)
724         return NULL;
725     switch(tag) {
726     case ACL_UNDEFINED_TAG:
727         kind = PyBytes_FromString("undefined type");
728         break;
729     case ACL_USER_OBJ:
730         kind = PyBytes_FromString("the owner");
731         break;
732     case ACL_GROUP_OBJ:
733         kind = PyBytes_FromString("the group");
734         break;
735     case ACL_OTHER:
736         kind = PyBytes_FromString("the others");
737         break;
738     case ACL_USER:
739         kind = PyBytes_FromFormat("user with uid %d", qualifier);
740         break;
741     case ACL_GROUP:
742         kind = PyBytes_FromFormat("group with gid %d", qualifier);
743         break;
744     case ACL_MASK:
745         kind = PyBytes_FromString("the mask");
746         break;
747     default:
748         kind = PyBytes_FromString("UNKNOWN_TAG_TYPE!");
749         break;
750     }
751     if (kind == NULL) {
752         Py_DECREF(format);
753         return NULL;
754     }
755     PyBytes_ConcatAndDel(&format, kind);
756     return format;
757 }
758
759 /* Sets the tag type of the entry */
760 static int Entry_set_tag_type(PyObject* obj, PyObject* value, void* arg) {
761     Entry_Object *self = (Entry_Object*) obj;
762
763     if(value == NULL) {
764         PyErr_SetString(PyExc_TypeError,
765                         "tag type deletion is not supported");
766         return -1;
767     }
768
769     if(!PyInt_Check(value)) {
770         PyErr_SetString(PyExc_TypeError,
771                         "tag type must be integer");
772         return -1;
773     }
774     if(acl_set_tag_type(self->entry, (acl_tag_t)PyInt_AsLong(value)) == -1) {
775         PyErr_SetFromErrno(PyExc_IOError);
776         return -1;
777     }
778
779     return 0;
780 }
781
782 /* Returns the tag type of the entry */
783 static PyObject* Entry_get_tag_type(PyObject *obj, void* arg) {
784     Entry_Object *self = (Entry_Object*) obj;
785     acl_tag_t value;
786
787     if (self->entry == NULL) {
788         PyErr_SetString(PyExc_AttributeError, "entry attribute");
789         return NULL;
790     }
791     if(acl_get_tag_type(self->entry, &value) == -1) {
792         PyErr_SetFromErrno(PyExc_IOError);
793         return NULL;
794     }
795
796     return PyInt_FromLong(value);
797 }
798
799 /* Sets the qualifier (either uid_t or gid_t) for the entry,
800  * usable only if the tag type if ACL_USER or ACL_GROUP
801  */
802 static int Entry_set_qualifier(PyObject* obj, PyObject* value, void* arg) {
803     Entry_Object *self = (Entry_Object*) obj;
804     int uidgid;
805
806     if(value == NULL) {
807         PyErr_SetString(PyExc_TypeError,
808                         "qualifier deletion is not supported");
809         return -1;
810     }
811
812     if(!PyInt_Check(value)) {
813         PyErr_SetString(PyExc_TypeError,
814                         "tag type must be integer");
815         return -1;
816     }
817     uidgid = PyInt_AsLong(value);
818     if(acl_set_qualifier(self->entry, (void*)&uidgid) == -1) {
819         PyErr_SetFromErrno(PyExc_IOError);
820         return -1;
821     }
822
823     return 0;
824 }
825
826 /* Returns the qualifier of the entry */
827 static PyObject* Entry_get_qualifier(PyObject *obj, void* arg) {
828     Entry_Object *self = (Entry_Object*) obj;
829     void *p;
830     int value;
831
832     if (self->entry == NULL) {
833         PyErr_SetString(PyExc_AttributeError, "entry attribute");
834         return NULL;
835     }
836     if((p = acl_get_qualifier(self->entry)) == NULL) {
837         PyErr_SetFromErrno(PyExc_IOError);
838         return NULL;
839     }
840     value = *(uid_t*)p;
841     acl_free(p);
842
843     return PyInt_FromLong(value);
844 }
845
846 /* Returns the parent ACL of the entry */
847 static PyObject* Entry_get_parent(PyObject *obj, void* arg) {
848     Entry_Object *self = (Entry_Object*) obj;
849
850     Py_INCREF(self->parent_acl);
851     return self->parent_acl;
852 }
853
854 /* Returns the a new Permset representing the permset of the entry
855  * FIXME: Should return a new reference to the same object, which
856  * should be created at init time!
857  */
858 static PyObject* Entry_get_permset(PyObject *obj, void* arg) {
859     Entry_Object *self = (Entry_Object*)obj;
860     PyObject *p;
861     Permset_Object *ps;
862
863     p = Permset_new(&Permset_Type, NULL, NULL);
864     if(p == NULL)
865         return NULL;
866     ps = (Permset_Object*)p;
867     if(acl_get_permset(self->entry, &ps->permset) == -1) {
868         PyErr_SetFromErrno(PyExc_IOError);
869         Py_DECREF(p);
870         return NULL;
871     }
872     ps->parent_entry = obj;
873     Py_INCREF(obj);
874
875     return (PyObject*)p;
876 }
877
878 /* Sets the permset of the entry to the passed Permset */
879 static int Entry_set_permset(PyObject* obj, PyObject* value, void* arg) {
880     Entry_Object *self = (Entry_Object*)obj;
881     Permset_Object *p;
882
883     if(!PyObject_IsInstance(value, (PyObject*)&Permset_Type)) {
884         PyErr_SetString(PyExc_TypeError, "argument 1 must be posix1e.Permset");
885         return -1;
886     }
887     p = (Permset_Object*)value;
888     if(acl_set_permset(self->entry, p->permset) == -1) {
889         PyErr_SetFromErrno(PyExc_IOError);
890         return -1;
891     }
892     return 0;
893 }
894
895 static char __Entry_copy_doc__[] =
896     "Copy an ACL entry.\n"
897     "\n"
898     "This method sets all the parameters to those of another\n"
899     "entry, even one of another's ACL\n"
900     "Parameters:\n"
901     " - src, instance of type Entry\n"
902     ;
903
904 /* Sets all the entry parameters to another's entry */
905 static PyObject* Entry_copy(PyObject *obj, PyObject *args) {
906     Entry_Object *self = (Entry_Object*)obj;
907     Entry_Object *other;
908
909     if(!PyArg_ParseTuple(args, "O!", &Entry_Type, &other))
910         return NULL;
911
912     if(acl_copy_entry(self->entry, other->entry) == -1)
913         return PyErr_SetFromErrno(PyExc_IOError);
914
915     Py_INCREF(Py_None);
916     return Py_None;
917 }
918
919 /**** Permset type *****/
920
921 /* Creation of a new Permset instance */
922 static PyObject* Permset_new(PyTypeObject* type, PyObject* args,
923                              PyObject *keywds) {
924     PyObject* newpermset;
925
926     newpermset = PyType_GenericNew(type, args, keywds);
927
928     if(newpermset != NULL) {
929         ((Permset_Object*)newpermset)->permset = NULL;
930         ((Permset_Object*)newpermset)->parent_entry = NULL;
931     }
932
933     return newpermset;
934 }
935
936 /* Initialization of a new Permset instance */
937 static int Permset_init(PyObject* obj, PyObject* args, PyObject *keywds) {
938     Permset_Object* self = (Permset_Object*) obj;
939     Entry_Object* parent = NULL;
940
941     if (!PyArg_ParseTuple(args, "O!", &Entry_Type, &parent))
942         return -1;
943
944     if(acl_get_permset(parent->entry, &self->permset) == -1) {
945         PyErr_SetFromErrno(PyExc_IOError);
946         return -1;
947     }
948
949     self->parent_entry = (PyObject*)parent;
950     Py_INCREF(parent);
951
952     return 0;
953 }
954
955 /* Free the Permset instance */
956 static void Permset_dealloc(PyObject* obj) {
957     Permset_Object *self = (Permset_Object*) obj;
958     PyObject *err_type, *err_value, *err_traceback;
959     int have_error = PyErr_Occurred() ? 1 : 0;
960
961     if (have_error)
962         PyErr_Fetch(&err_type, &err_value, &err_traceback);
963     if(self->parent_entry != NULL) {
964         Py_DECREF(self->parent_entry);
965         self->parent_entry = NULL;
966     }
967     if (have_error)
968         PyErr_Restore(err_type, err_value, err_traceback);
969     PyObject_DEL(self);
970 }
971
972 /* Permset string representation */
973 static PyObject* Permset_str(PyObject *obj) {
974     Permset_Object *self = (Permset_Object*) obj;
975     char pstr[3];
976
977     pstr[0] = get_perm(self->permset, ACL_READ) ? 'r' : '-';
978     pstr[1] = get_perm(self->permset, ACL_WRITE) ? 'w' : '-';
979     pstr[2] = get_perm(self->permset, ACL_EXECUTE) ? 'x' : '-';
980     return PyBytes_FromStringAndSize(pstr, 3);
981 }
982
983 static char __Permset_clear_doc__[] =
984     "Clear all permissions from the permission set.\n"
985     ;
986
987 /* Clears all permissions from the permset */
988 static PyObject* Permset_clear(PyObject* obj, PyObject* args) {
989     Permset_Object *self = (Permset_Object*) obj;
990
991     if(acl_clear_perms(self->permset) == -1)
992         return PyErr_SetFromErrno(PyExc_IOError);
993
994     /* Return the result */
995     Py_INCREF(Py_None);
996     return Py_None;
997 }
998
999 static PyObject* Permset_get_right(PyObject *obj, void* arg) {
1000     Permset_Object *self = (Permset_Object*) obj;
1001
1002     if(get_perm(self->permset, *(acl_perm_t*)arg)) {
1003         Py_RETURN_TRUE;
1004     } else {
1005         Py_RETURN_FALSE;
1006     }
1007 }
1008
1009 static int Permset_set_right(PyObject* obj, PyObject* value, void* arg) {
1010     Permset_Object *self = (Permset_Object*) obj;
1011     int on;
1012     int nerr;
1013
1014     if(!PyInt_Check(value)) {
1015         PyErr_SetString(PyExc_ValueError, "a maximum of one argument must"
1016                         " be passed");
1017         return -1;
1018     }
1019     on = PyInt_AsLong(value);
1020     if(on)
1021         nerr = acl_add_perm(self->permset, *(acl_perm_t*)arg);
1022     else
1023         nerr = acl_delete_perm(self->permset, *(acl_perm_t*)arg);
1024     if(nerr == -1) {
1025         PyErr_SetFromErrno(PyExc_IOError);
1026         return -1;
1027     }
1028     return 0;
1029 }
1030
1031 static char __Permset_add_doc__[] =
1032     "Add a permission to the permission set.\n"
1033     "\n"
1034     "The add() function adds the permission contained in \n"
1035     "the argument perm to the permission set.  An attempt \n"
1036     "to add a permission that is already contained in the \n"
1037     "permission set is not considered an error.\n"
1038     "\n"
1039     "Parameters:\n\n"
1040     "  - perm: a permission (ACL_WRITE, ACL_READ, ACL_EXECUTE, ...)\n"
1041     "\n"
1042     "Return value: None\n"
1043     "\n"
1044     "Can raise: IOError\n"
1045     ;
1046
1047 static PyObject* Permset_add(PyObject* obj, PyObject* args) {
1048     Permset_Object *self = (Permset_Object*) obj;
1049     int right;
1050
1051     if (!PyArg_ParseTuple(args, "i", &right))
1052         return NULL;
1053
1054     if(acl_add_perm(self->permset, (acl_perm_t) right) == -1)
1055         return PyErr_SetFromErrno(PyExc_IOError);
1056
1057     /* Return the result */
1058     Py_INCREF(Py_None);
1059     return Py_None;
1060 }
1061
1062 static char __Permset_delete_doc__[] =
1063     "Delete a permission from the permission set.\n"
1064     "\n"
1065     "The delete() function deletes the permission contained in \n"
1066     "the argument perm from the permission set.  An attempt \n"
1067     "to delete a permission that is not contained in the \n"
1068     "permission set is not considered an error.\n"
1069     "Parameters:\n\n"
1070     "  - perm a permission (ACL_WRITE, ACL_READ, ACL_EXECUTE, ...)\n"
1071     "Return value: None\n"
1072     "\n"
1073     "Can raise: IOError\n"
1074     ;
1075
1076 static PyObject* Permset_delete(PyObject* obj, PyObject* args) {
1077     Permset_Object *self = (Permset_Object*) obj;
1078     int right;
1079
1080     if (!PyArg_ParseTuple(args, "i", &right))
1081         return NULL;
1082
1083     if(acl_delete_perm(self->permset, (acl_perm_t) right) == -1)
1084         return PyErr_SetFromErrno(PyExc_IOError);
1085
1086     /* Return the result */
1087     Py_INCREF(Py_None);
1088     return Py_None;
1089 }
1090
1091 static char __Permset_test_doc__[] =
1092     "Test if a permission exists in the permission set.\n"
1093     "\n"
1094     "The test() function tests if the permission contained in \n"
1095     "the argument perm exits the permission set.\n"
1096     "Parameters:\n\n"
1097     "  - perm a permission (ACL_WRITE, ACL_READ, ACL_EXECUTE, ...)\n"
1098     "Return value: Boolean\n"
1099     "\n"
1100     "Can raise: IOError\n"
1101     ;
1102
1103 static PyObject* Permset_test(PyObject* obj, PyObject* args) {
1104     Permset_Object *self = (Permset_Object*) obj;
1105     int right;
1106     int ret;
1107
1108     if (!PyArg_ParseTuple(args, "i", &right))
1109         return NULL;
1110
1111     ret = get_perm(self->permset, (acl_perm_t) right);
1112     if(ret == -1)
1113         return PyErr_SetFromErrno(PyExc_IOError);
1114
1115     if(ret) {
1116         Py_RETURN_TRUE;
1117     } else {
1118         Py_RETURN_FALSE;
1119     }
1120 }
1121
1122 #endif
1123
1124 static char __ACL_Type_doc__[] =
1125     "Type which represents a POSIX ACL\n"
1126     "\n"
1127     "Parameters (only one keword parameter should be provided):\n"
1128     "  - file=\"...\", meaning create ACL representing\n"
1129     "    the access ACL of that file\n"
1130     "  - filedef=\"...\", meaning create ACL representing\n"
1131     "    the default ACL of that directory\n"
1132     "  - fd=<int>, meaning create ACL representing\n"
1133     "    the access ACL of that file descriptor\n"
1134     "  - text=\"...\", meaning create ACL from a \n"
1135     "    textual description\n"
1136     "  - acl=<ACL instance>, meaning create a copy\n"
1137     "    of an existing ACL instance\n"
1138     "  - mode=<int>, meaning create an ACL from a numeric mode\n"
1139     "    (e.g. mode=0644) (this is valid only when the C library\n"
1140     "    provides the acl_from_mode call)\n"
1141     "\n"
1142     "If no parameters are passed, create an empty ACL; this\n"
1143     "makes sense only when your OS supports ACL modification\n"
1144     "(i.e. it implements full POSIX.1e support)\n"
1145     ;
1146
1147 /* ACL type methods */
1148 static PyMethodDef ACL_methods[] = {
1149     {"applyto", ACL_applyto, METH_VARARGS, __applyto_doc__},
1150     {"valid", ACL_valid, METH_NOARGS, __valid_doc__},
1151 #ifdef HAVE_LINUX
1152     {"to_any_text", (PyCFunction)ACL_to_any_text, METH_VARARGS | METH_KEYWORDS,
1153      __to_any_text_doc__},
1154     {"check", ACL_check, METH_NOARGS, __check_doc__},
1155     {"equiv_mode", ACL_equiv_mode, METH_NOARGS, __equiv_mode_doc__},
1156 #endif
1157 #ifdef HAVE_ACL_COPYEXT
1158     {"__getstate__", ACL_get_state, METH_NOARGS,
1159      "Dumps the ACL to an external format."},
1160     {"__setstate__", ACL_set_state, METH_VARARGS,
1161      "Loads the ACL from an external format."},
1162 #endif
1163 #ifdef HAVE_LEVEL2
1164     {"delete_entry", ACL_delete_entry, METH_VARARGS, __ACL_delete_entry_doc__},
1165     {"calc_mask", ACL_calc_mask, METH_NOARGS, __ACL_calc_mask_doc__},
1166     {"append", ACL_append, METH_VARARGS, __ACL_append_doc__},
1167 #endif
1168     {NULL, NULL, 0, NULL}
1169 };
1170
1171
1172 /* The definition of the ACL Type */
1173 static PyTypeObject ACL_Type = {
1174 #ifdef IS_PY3K
1175     PyVarObject_HEAD_INIT(NULL, 0)
1176 #else
1177     PyObject_HEAD_INIT(NULL)
1178     0,
1179 #endif
1180     "posix1e.ACL",
1181     sizeof(ACL_Object),
1182     0,
1183     ACL_dealloc,        /* tp_dealloc */
1184     0,                  /* tp_print */
1185     0,                  /* tp_getattr */
1186     0,                  /* tp_setattr */
1187     ACL_nocmp,          /* tp_compare */
1188     0,                  /* tp_repr */
1189     0,                  /* tp_as_number */
1190     0,                  /* tp_as_sequence */
1191     0,                  /* tp_as_mapping */
1192     0,                  /* tp_hash */
1193     0,                  /* tp_call */
1194     ACL_str,            /* tp_str */
1195     0,                  /* tp_getattro */
1196     0,                  /* tp_setattro */
1197     0,                  /* tp_as_buffer */
1198     Py_TPFLAGS_DEFAULT, /* tp_flags */
1199     __ACL_Type_doc__,   /* tp_doc */
1200     0,                  /* tp_traverse */
1201     0,                  /* tp_clear */
1202 #ifdef HAVE_LINUX
1203     ACL_richcompare,    /* tp_richcompare */
1204 #else
1205     0,                  /* tp_richcompare */
1206 #endif
1207     0,                  /* tp_weaklistoffset */
1208 #ifdef HAVE_LEVEL2
1209     ACL_iter,
1210     ACL_iternext,
1211 #else
1212     0,                  /* tp_iter */
1213     0,                  /* tp_iternext */
1214 #endif
1215     ACL_methods,        /* tp_methods */
1216     0,                  /* tp_members */
1217     0,                  /* tp_getset */
1218     0,                  /* tp_base */
1219     0,                  /* tp_dict */
1220     0,                  /* tp_descr_get */
1221     0,                  /* tp_descr_set */
1222     0,                  /* tp_dictoffset */
1223     ACL_init,           /* tp_init */
1224     0,                  /* tp_alloc */
1225     ACL_new,            /* tp_new */
1226 };
1227
1228 #ifdef HAVE_LEVEL2
1229
1230 /* Entry type methods */
1231 static PyMethodDef Entry_methods[] = {
1232     {"copy", Entry_copy, METH_VARARGS, __Entry_copy_doc__},
1233     {NULL, NULL, 0, NULL}
1234 };
1235
1236 static char __Entry_tagtype_doc__[] =
1237     "The tag type of the current entry\n"
1238     "\n"
1239     "This is one of:\n"
1240     " - ACL_UNDEFINED_TAG\n"
1241     " - ACL_USER_OBJ\n"
1242     " - ACL_USER\n"
1243     " - ACL_GROUP_OBJ\n"
1244     " - ACL_GROUP\n"
1245     " - ACL_MASK\n"
1246     " - ACL_OTHER\n"
1247     ;
1248
1249 static char __Entry_qualifier_doc__[] =
1250     "The qualifier of the current entry\n"
1251     "\n"
1252     "If the tag type is ACL_USER, this should be a user id.\n"
1253     "If the tag type if ACL_GROUP, this should be a group id.\n"
1254     "Else, it doesn't matter.\n"
1255     ;
1256
1257 static char __Entry_parent_doc__[] =
1258     "The parent ACL of this entry\n"
1259     ;
1260
1261 static char __Entry_permset_doc__[] =
1262     "The permission set of this ACL entry\n"
1263     ;
1264
1265 /* Entry getset */
1266 static PyGetSetDef Entry_getsets[] = {
1267     {"tag_type", Entry_get_tag_type, Entry_set_tag_type,
1268      __Entry_tagtype_doc__},
1269     {"qualifier", Entry_get_qualifier, Entry_set_qualifier,
1270      __Entry_qualifier_doc__},
1271     {"parent", Entry_get_parent, NULL, __Entry_parent_doc__},
1272     {"permset", Entry_get_permset, Entry_set_permset, __Entry_permset_doc__},
1273     {NULL}
1274 };
1275
1276 static char __Entry_Type_doc__[] =
1277     "Type which represents an entry in an ACL.\n"
1278     "\n"
1279     "The type exists only if the OS has full support for POSIX.1e\n"
1280     "Can be created either by:\n"
1281     "\n"
1282     "  >>> e = posix1e.Entry(myACL) # this creates a new entry in the ACL\n"
1283     "  >>> e = myACL.append() # another way for doing the same thing\n"
1284     "\n"
1285     "or by:\n"
1286     "  >>> for entry in myACL:\n"
1287     "  ...     print entry\n"
1288     "\n"
1289     "Note that the Entry keeps a reference to its ACL, so even if \n"
1290     "you delete the ACL, it won't be cleaned up and will continue to \n"
1291     "exist until its Entry(ies) will be deleted.\n"
1292     ;
1293 /* The definition of the Entry Type */
1294 static PyTypeObject Entry_Type = {
1295 #ifdef IS_PY3K
1296     PyVarObject_HEAD_INIT(NULL, 0)
1297 #else
1298     PyObject_HEAD_INIT(NULL)
1299     0,
1300 #endif
1301     "posix1e.Entry",
1302     sizeof(Entry_Object),
1303     0,
1304     Entry_dealloc,      /* tp_dealloc */
1305     0,                  /* tp_print */
1306     0,                  /* tp_getattr */
1307     0,                  /* tp_setattr */
1308     0,                  /* tp_compare */
1309     0,                  /* tp_repr */
1310     0,                  /* tp_as_number */
1311     0,                  /* tp_as_sequence */
1312     0,                  /* tp_as_mapping */
1313     0,                  /* tp_hash */
1314     0,                  /* tp_call */
1315     Entry_str,          /* tp_str */
1316     0,                  /* tp_getattro */
1317     0,                  /* tp_setattro */
1318     0,                  /* tp_as_buffer */
1319     Py_TPFLAGS_DEFAULT, /* tp_flags */
1320     __Entry_Type_doc__, /* tp_doc */
1321     0,                  /* tp_traverse */
1322     0,                  /* tp_clear */
1323     0,                  /* tp_richcompare */
1324     0,                  /* tp_weaklistoffset */
1325     0,                  /* tp_iter */
1326     0,                  /* tp_iternext */
1327     Entry_methods,      /* tp_methods */
1328     0,                  /* tp_members */
1329     Entry_getsets,      /* tp_getset */
1330     0,                  /* tp_base */
1331     0,                  /* tp_dict */
1332     0,                  /* tp_descr_get */
1333     0,                  /* tp_descr_set */
1334     0,                  /* tp_dictoffset */
1335     Entry_init,         /* tp_init */
1336     0,                  /* tp_alloc */
1337     Entry_new,          /* tp_new */
1338 };
1339
1340 /* Permset type methods */
1341 static PyMethodDef Permset_methods[] = {
1342     {"clear", Permset_clear, METH_NOARGS, __Permset_clear_doc__, },
1343     {"add", Permset_add, METH_VARARGS, __Permset_add_doc__, },
1344     {"delete", Permset_delete, METH_VARARGS, __Permset_delete_doc__, },
1345     {"test", Permset_test, METH_VARARGS, __Permset_test_doc__, },
1346     {NULL, NULL, 0, NULL}
1347 };
1348
1349 static char __Permset_execute_doc__[] =
1350     "Execute permsission\n"
1351     "\n"
1352     "This is a convenience method of access; the \n"
1353     "same effect can be achieved using the functions\n"
1354     "add(), test(), delete(), and those can take any \n"
1355     "permission defined by your platform.\n"
1356     ;
1357
1358 static char __Permset_read_doc__[] =
1359     "Read permsission\n"
1360     "\n"
1361     "This is a convenience method of access; the \n"
1362     "same effect can be achieved using the functions\n"
1363     "add(), test(), delete(), and those can take any \n"
1364     "permission defined by your platform.\n"
1365     ;
1366
1367 static char __Permset_write_doc__[] =
1368     "Write permsission\n"
1369     "\n"
1370     "This is a convenience method of access; the \n"
1371     "same effect can be achieved using the functions\n"
1372     "add(), test(), delete(), and those can take any \n"
1373     "permission defined by your platform.\n"
1374     ;
1375
1376 /* Permset getset */
1377 static PyGetSetDef Permset_getsets[] = {
1378     {"execute", Permset_get_right, Permset_set_right,
1379      __Permset_execute_doc__, &holder_ACL_EXECUTE},
1380     {"read", Permset_get_right, Permset_set_right,
1381      __Permset_read_doc__, &holder_ACL_READ},
1382     {"write", Permset_get_right, Permset_set_right,
1383      __Permset_write_doc__, &holder_ACL_WRITE},
1384     {NULL}
1385 };
1386
1387 static char __Permset_Type_doc__[] =
1388     "Type which represents the permission set in an ACL entry\n"
1389     "\n"
1390     "The type exists only if the OS has full support for POSIX.1e\n"
1391     "Can be retrieved either by:\n\n"
1392     ">>> perms = myEntry.permset\n"
1393     "\n"
1394     "or by:\n\n"
1395     ">>> perms = posix1e.Permset(myEntry)\n"
1396     "\n"
1397     "Note that the Permset keeps a reference to its Entry, so even if \n"
1398     "you delete the entry, it won't be cleaned up and will continue to \n"
1399     "exist until its Permset will be deleted.\n"
1400     ;
1401
1402 /* The definition of the Permset Type */
1403 static PyTypeObject Permset_Type = {
1404 #ifdef IS_PY3K
1405     PyVarObject_HEAD_INIT(NULL, 0)
1406 #else
1407     PyObject_HEAD_INIT(NULL)
1408     0,
1409 #endif
1410     "posix1e.Permset",
1411     sizeof(Permset_Object),
1412     0,
1413     Permset_dealloc,    /* tp_dealloc */
1414     0,                  /* tp_print */
1415     0,                  /* tp_getattr */
1416     0,                  /* tp_setattr */
1417     0,                  /* tp_compare */
1418     0,                  /* tp_repr */
1419     0,                  /* tp_as_number */
1420     0,                  /* tp_as_sequence */
1421     0,                  /* tp_as_mapping */
1422     0,                  /* tp_hash */
1423     0,                  /* tp_call */
1424     Permset_str,        /* tp_str */
1425     0,                  /* tp_getattro */
1426     0,                  /* tp_setattro */
1427     0,                  /* tp_as_buffer */
1428     Py_TPFLAGS_DEFAULT, /* tp_flags */
1429     __Permset_Type_doc__,/* tp_doc */
1430     0,                  /* tp_traverse */
1431     0,                  /* tp_clear */
1432     0,                  /* tp_richcompare */
1433     0,                  /* tp_weaklistoffset */
1434     0,                  /* tp_iter */
1435     0,                  /* tp_iternext */
1436     Permset_methods,    /* tp_methods */
1437     0,                  /* tp_members */
1438     Permset_getsets,    /* tp_getset */
1439     0,                  /* tp_base */
1440     0,                  /* tp_dict */
1441     0,                  /* tp_descr_get */
1442     0,                  /* tp_descr_set */
1443     0,                  /* tp_dictoffset */
1444     Permset_init,       /* tp_init */
1445     0,                  /* tp_alloc */
1446     Permset_new,        /* tp_new */
1447 };
1448
1449 #endif
1450
1451 /* Module methods */
1452
1453 static char __deletedef_doc__[] =
1454     "Delete the default ACL from a directory.\n"
1455     "\n"
1456     "This function deletes the default ACL associated with \n"
1457     "a directory (the ACL which will be ANDed with the mode\n"
1458     "parameter to the open, creat functions).\n"
1459     "Parameters:\n"
1460     "  - a string representing the directory whose default ACL\n"
1461     "    should be deleted\n"
1462     ;
1463
1464 /* Deletes the default ACL from a directory */
1465 static PyObject* aclmodule_delete_default(PyObject* obj, PyObject* args) {
1466     char *filename;
1467
1468     /* Parse the arguments */
1469     if (!PyArg_ParseTuple(args, "et", NULL, &filename))
1470         return NULL;
1471
1472     if(acl_delete_def_file(filename) == -1) {
1473         return PyErr_SetFromErrno(PyExc_IOError);
1474     }
1475
1476     /* Return the result */
1477     Py_INCREF(Py_None);
1478     return Py_None;
1479 }
1480
1481 #ifdef HAVE_LINUX
1482 static char __has_extended_doc__[] =
1483     "Check if a file or filehandle has an extended ACL.\n"
1484     "\n"
1485     "Parameter:\n"
1486     "  - either a filename or a file-like object or an integer; this\n"
1487     "    represents the filesystem object on which to act\n"
1488     ;
1489
1490 /* Check for extended ACL a file or fd */
1491 static PyObject* aclmodule_has_extended(PyObject* obj, PyObject* args) {
1492     PyObject *myarg;
1493     int nret;
1494     int fd;
1495
1496     if (!PyArg_ParseTuple(args, "O", &myarg))
1497         return NULL;
1498
1499     if(PyBytes_Check(myarg)) {
1500         const char *filename = PyBytes_AS_STRING(myarg);
1501         nret = acl_extended_file(filename);
1502     } else if (PyUnicode_Check(myarg)) {
1503         PyObject *o =
1504             PyUnicode_AsEncodedString(myarg,
1505                                       Py_FileSystemDefaultEncoding, "strict");
1506         if (o == NULL)
1507             return NULL;
1508         const char *filename = PyBytes_AS_STRING(o);
1509         nret = acl_extended_file(filename);
1510         Py_DECREF(o);
1511     } else if((fd = PyObject_AsFileDescriptor(myarg)) != -1) {
1512         nret = acl_extended_fd(fd);
1513     } else {
1514         PyErr_SetString(PyExc_TypeError, "argument 1 must be string, int,"
1515                         " or file-like object");
1516         return 0;
1517     }
1518     if(nret == -1) {
1519         return PyErr_SetFromErrno(PyExc_IOError);
1520     }
1521
1522     /* Return the result */
1523     return PyBool_FromLong(nret);
1524 }
1525 #endif
1526
1527 /* The module methods */
1528 static PyMethodDef aclmodule_methods[] = {
1529     {"delete_default", aclmodule_delete_default, METH_VARARGS,
1530      __deletedef_doc__},
1531 #ifdef HAVE_LINUX
1532     {"has_extended", aclmodule_has_extended, METH_VARARGS,
1533      __has_extended_doc__},
1534 #endif
1535     {NULL, NULL, 0, NULL}
1536 };
1537
1538 static char __posix1e_doc__[] =
1539     "POSIX.1e ACLs manipulation\n"
1540     "\n"
1541     "This module provides support for manipulating POSIX.1e ACLS\n"
1542     "\n"
1543     "Depending on the operating system support for POSIX.1e, \n"
1544     "the ACL type will have more or less capabilities:\n"
1545     "  - level 1, only basic support, you can create\n"
1546     "    ACLs from files and text descriptions;\n"
1547     "    once created, the type is immutable\n"
1548     "  - level 2, complete support, you can alter\n"
1549     "    the ACL once it is created\n"
1550     "\n"
1551     "Also, in level 2, more types are available, corresponding\n"
1552     "to acl_entry_t (the Entry type), acl_permset_t (the Permset type).\n"
1553     "\n"
1554     "The existence of level 2 support and other extensions can be\n"
1555     "checked by the constants:\n"
1556     "  - HAS_ACL_ENTRY for level 2 and the Entry/Permset classes\n"
1557     "  - HAS_ACL_FROM_MODE for ACL(mode=...) usage\n"
1558     "  - HAS_ACL_CHECK for the ACL().check function\n"
1559     "  - HAS_EXTENDED_CHECK for the module-level has_extended function\n"
1560     "  - HAS_EQUIV_MODE for the ACL().equiv_mode method\n"
1561     "\n"
1562     "Example:\n"
1563     "\n"
1564     ">>> import posix1e\n"
1565     ">>> acl1 = posix1e.ACL(file=\"file.txt\") \n"
1566     ">>> print acl1\n"
1567     "user::rw-\n"
1568     "group::rw-\n"
1569     "other::r--\n"
1570     ">>>\n"
1571     ">>> b = posix1e.ACL(text=\"u::rx,g::-,o::-\")\n"
1572     ">>> print b\n"
1573     "user::r-x\n"
1574     "group::---\n"
1575     "other::---\n"
1576     ">>>\n"
1577     ">>> b.applyto(\"file.txt\")\n"
1578     ">>> print posix1e.ACL(file=\"file.txt\")\n"
1579     "user::r-x\n"
1580     "group::---\n"
1581     "other::---\n"
1582     ">>>\n"
1583     "\n"
1584     ;
1585
1586 #ifdef IS_PY3K
1587
1588 static struct PyModuleDef posix1emodule = {
1589     PyModuleDef_HEAD_INIT,
1590     "posix1e",
1591     __posix1e_doc__,
1592     0,
1593     aclmodule_methods,
1594 };
1595
1596 #define INITERROR return NULL
1597
1598 PyMODINIT_FUNC
1599 PyInit_posix1e(void)
1600
1601 #else
1602 #define INITERROR return
1603
1604 void initposix1e(void)
1605 #endif
1606 {
1607     PyObject *m, *d;
1608
1609     Py_TYPE(&ACL_Type) = &PyType_Type;
1610     if(PyType_Ready(&ACL_Type) < 0)
1611         INITERROR;
1612
1613 #ifdef HAVE_LEVEL2
1614     Py_TYPE(&Entry_Type) = &PyType_Type;
1615     if(PyType_Ready(&Entry_Type) < 0)
1616         INITERROR;
1617
1618     Py_TYPE(&Permset_Type) = &PyType_Type;
1619     if(PyType_Ready(&Permset_Type) < 0)
1620         INITERROR;
1621 #endif
1622
1623 #ifdef IS_PY3K
1624     m = PyModule_Create(&posix1emodule);
1625 #else
1626     m = Py_InitModule3("posix1e", aclmodule_methods, __posix1e_doc__);
1627 #endif
1628     if (m==NULL)
1629         INITERROR;
1630
1631     d = PyModule_GetDict(m);
1632     if (d == NULL)
1633         INITERROR;
1634
1635     Py_INCREF(&ACL_Type);
1636     if (PyDict_SetItemString(d, "ACL",
1637                              (PyObject *) &ACL_Type) < 0)
1638         INITERROR;
1639
1640     /* 23.3.6 acl_type_t values */
1641     PyModule_AddIntConstant(m, "ACL_TYPE_ACCESS", ACL_TYPE_ACCESS);
1642     PyModule_AddIntConstant(m, "ACL_TYPE_DEFAULT", ACL_TYPE_DEFAULT);
1643
1644
1645 #ifdef HAVE_LEVEL2
1646     Py_INCREF(&Entry_Type);
1647     if (PyDict_SetItemString(d, "Entry",
1648                              (PyObject *) &Entry_Type) < 0)
1649         INITERROR;
1650
1651     Py_INCREF(&Permset_Type);
1652     if (PyDict_SetItemString(d, "Permset",
1653                              (PyObject *) &Permset_Type) < 0)
1654         INITERROR;
1655
1656     /* 23.2.2 acl_perm_t values */
1657     PyModule_AddIntConstant(m, "ACL_READ", ACL_READ);
1658     PyModule_AddIntConstant(m, "ACL_WRITE", ACL_WRITE);
1659     PyModule_AddIntConstant(m, "ACL_EXECUTE", ACL_EXECUTE);
1660
1661     /* 23.2.5 acl_tag_t values */
1662     PyModule_AddIntConstant(m, "ACL_UNDEFINED_TAG", ACL_UNDEFINED_TAG);
1663     PyModule_AddIntConstant(m, "ACL_USER_OBJ", ACL_USER_OBJ);
1664     PyModule_AddIntConstant(m, "ACL_USER", ACL_USER);
1665     PyModule_AddIntConstant(m, "ACL_GROUP_OBJ", ACL_GROUP_OBJ);
1666     PyModule_AddIntConstant(m, "ACL_GROUP", ACL_GROUP);
1667     PyModule_AddIntConstant(m, "ACL_MASK", ACL_MASK);
1668     PyModule_AddIntConstant(m, "ACL_OTHER", ACL_OTHER);
1669
1670     /* Document extended functionality via easy-to-use constants */
1671     PyModule_AddIntConstant(m, "HAS_ACL_ENTRY", 1);
1672 #else
1673     PyModule_AddIntConstant(m, "HAS_ACL_ENTRY", 0);
1674 #endif
1675
1676 #ifdef HAVE_LINUX
1677     /* Linux libacl specific acl_to_any_text constants */
1678     PyModule_AddIntConstant(m, "TEXT_ABBREVIATE", TEXT_ABBREVIATE);
1679     PyModule_AddIntConstant(m, "TEXT_NUMERIC_IDS", TEXT_NUMERIC_IDS);
1680     PyModule_AddIntConstant(m, "TEXT_SOME_EFFECTIVE", TEXT_SOME_EFFECTIVE);
1681     PyModule_AddIntConstant(m, "TEXT_ALL_EFFECTIVE", TEXT_ALL_EFFECTIVE);
1682     PyModule_AddIntConstant(m, "TEXT_SMART_INDENT", TEXT_SMART_INDENT);
1683
1684     /* Linux libacl specific acl_check constants */
1685     PyModule_AddIntConstant(m, "ACL_MULTI_ERROR", ACL_MULTI_ERROR);
1686     PyModule_AddIntConstant(m, "ACL_DUPLICATE_ERROR", ACL_DUPLICATE_ERROR);
1687     PyModule_AddIntConstant(m, "ACL_MISS_ERROR", ACL_MISS_ERROR);
1688     PyModule_AddIntConstant(m, "ACL_ENTRY_ERROR", ACL_ENTRY_ERROR);
1689
1690     /* declare the Linux extensions */
1691     PyModule_AddIntConstant(m, "HAS_ACL_FROM_MODE", 1);
1692     PyModule_AddIntConstant(m, "HAS_ACL_CHECK", 1);
1693     PyModule_AddIntConstant(m, "HAS_EXTENDED_CHECK", 1);
1694     PyModule_AddIntConstant(m, "HAS_EQUIV_MODE", 1);
1695 #else
1696     PyModule_AddIntConstant(m, "HAS_ACL_FROM_MODE", 0);
1697     PyModule_AddIntConstant(m, "HAS_ACL_CHECK", 0);
1698     PyModule_AddIntConstant(m, "HAS_EXTENDED_CHECK", 0);
1699     PyModule_AddIntConstant(m, "HAS_EQUIV_MODE", 0);
1700 #endif
1701
1702 #ifdef IS_PY3K
1703     return m;
1704 #endif
1705 }