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