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