File: _prctlmodule.c

package info (click to toggle)
python-prctl 1.7-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 176 kB
  • sloc: ansic: 705; python: 530; makefile: 80
file content (777 lines) | stat: -rw-r--r-- 22,945 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
/*
 * python-pctrl -- python interface to the prctl function
 * (c)2010-2018 Dennis Kaarsemaker <dennis@kaarsemaker.net>
 * See COPYING for licensing details
 */

#include <Python.h>
#if PY_MAJOR_VERSION >= 3
#define PyInt_FromLong PyLong_FromLong
#define PyInt_Check PyLong_Check
#define PyInt_AsLong PyLong_AsLong
#endif
#include "securebits.h"
#include <sys/capability.h>
#include <sys/prctl.h>
#include <sys/signal.h>

/* New in 2.6.32, but named and implemented inconsistently. The linux
 * implementation has two ways of setting the policy to the default, and thus
 * needs an extra argument. We ignore the first argument and always call
 * PR_MCE_KILL_SET. This makes our implementation simpler and keeps the prctl
 * interface more consistent
 */
#ifdef PR_MCE_KILL
#define PR_GET_MCE_KILL PR_MCE_KILL_GET
#define PR_SET_MCE_KILL PR_MCE_KILL
#endif

/* New in 2.6.XX (Ubuntu 10.10) */
#define NOT_SET (-1)
#ifdef PR_SET_PTRACER
/* This one has no getter for some reason, but guard against that being fixed  */
#ifndef PR_GET_PTRACER
#define PR_GET_PTRACER NOT_SET
/* Icky global variable to cache ptracer */
static int __cached_ptracer = NOT_SET;
#endif
#endif

/* This function is not in Python.h, so define it here */
#if PY_MAJOR_VERSION < 3
void Py_GetArgcArgv(int*, char***);
#else
void Py_GetArgcArgv(int*, wchar_t***);
#endif

/* The prctl wrapper */
static PyObject *
prctl_prctl(PyObject *self, PyObject *args)
{
    long option = 0;
    long arg = 0;
    char *argstr = NULL;
    char name[17] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    int result;

    /*
     * Accept single int, two ints and int+string. That covers all current
     * prctl possibilities. int+string is required for (and only accepted for)
     * PR_SET_NAME
     */
    if(!PyArg_ParseTuple(args, "l|l", &option, &arg)) {
        if(!PyArg_ParseTuple(args, "ls", &option, &argstr)) {
            return NULL;
        }
        if(option != PR_SET_NAME) {
            PyErr_SetString(PyExc_TypeError, "an integer is required");
            return NULL;
        }
        PyErr_Clear();
    }
    else {
        if(option == PR_SET_NAME) {
            PyErr_SetString(PyExc_TypeError, "a string is required");
            return NULL;
        }
    }

    /* Validate the optional arguments */
    switch(option) {
#ifdef PR_CAPBSET_READ
        case(PR_CAPBSET_READ):
        case(PR_CAPBSET_DROP):
            if(!cap_valid(arg)) {
                PyErr_SetString(PyExc_ValueError, "Unknown capability");
                return NULL;
            }
            break;
#endif
        case(PR_SET_DUMPABLE):
        case(PR_SET_KEEPCAPS):
            /* Only 0 and 1 are allowed */
            arg = arg ? 1 : 0;
            break;
        case(PR_SET_ENDIAN):
            if(arg != PR_ENDIAN_LITTLE && arg != PR_ENDIAN_BIG && arg != PR_ENDIAN_PPC_LITTLE) {
                PyErr_SetString(PyExc_ValueError, "Unknown endianness");
                return NULL;
            }
            break;
        case(PR_SET_FPEMU):
            if(arg != PR_FPEMU_NOPRINT && arg != PR_FPEMU_SIGFPE) {
                PyErr_SetString(PyExc_ValueError, "Unknown floating-point emulation setting");
                return NULL;
            }
            break;
        case(PR_SET_FPEXC):
            if(arg & ~(PR_FP_EXC_SW_ENABLE | PR_FP_EXC_DIV | PR_FP_EXC_OVF |
                       PR_FP_EXC_UND | PR_FP_EXC_RES | PR_FP_EXC_INV |
                       PR_FP_EXC_DISABLED | PR_FP_EXC_NONRECOV |
                       PR_FP_EXC_ASYNC | PR_FP_EXC_PRECISE)) {
                PyErr_SetString(PyExc_ValueError, "Unknown floating-point exception mode");
                return NULL;
            }
            break;
#ifdef PR_MCE_KILL
        case(PR_SET_MCE_KILL):
            if(arg != PR_MCE_KILL_DEFAULT && arg != PR_MCE_KILL_EARLY && arg != PR_MCE_KILL_LATE) {
                PyErr_SetString(PyExc_ValueError, "Unknown memory corruption kill policy");
                return NULL;
            }
            break;
#endif
        case(PR_SET_NAME):
            if(strlen(argstr) > 16) {
                /* FIXME: warn */
            }
            strncpy(name, argstr, 16);
            break;
        case(PR_SET_PDEATHSIG):
            if(arg < 0 || arg > SIGRTMAX) {
                PyErr_SetString(PyExc_ValueError, "Unknown signal");
                return NULL;
            }
            break;
#ifdef PR_SET_SECCOMP
        case(PR_SET_SECCOMP):
#ifdef PR_SET_NO_NEW_PRIVS
        case(PR_SET_NO_NEW_PRIVS):
#endif
            if(!arg) {
                PyErr_SetString(PyExc_ValueError, "Argument must be 1");
                return NULL;
            }
            arg = 1;
            break;
#endif
#ifdef PR_SET_SECUREBITS
        case(PR_SET_SECUREBITS):
            if(arg & ~ ((1 << SECURE_NOROOT) | (1 << SECURE_NOROOT_LOCKED) |
                        (1 << SECURE_NO_SETUID_FIXUP) | (1 << SECURE_NO_SETUID_FIXUP_LOCKED) |
                        (1 << SECURE_KEEP_CAPS) | (1 << SECURE_KEEP_CAPS_LOCKED))) {
                PyErr_SetString(PyExc_ValueError, "Invalid securebits set");
                return NULL;
            }
            break;
#endif
        case(PR_SET_TIMING):
            if(arg != PR_TIMING_STATISTICAL && arg != PR_TIMING_TIMESTAMP) {
                PyErr_SetString(PyExc_ValueError, "Invalid timing constant");
                return NULL;
            }
            break;
#ifdef PR_SET_TSC
        case(PR_SET_TSC):
            if(arg != PR_TSC_ENABLE && arg != PR_TSC_SIGSEGV) {
                PyErr_SetString(PyExc_ValueError, "Invalid TSC setting");
                return NULL;
            }
            break;
#endif
        case(PR_SET_UNALIGN):
            if(arg != PR_UNALIGN_NOPRINT && arg != PR_UNALIGN_SIGBUS) {
                PyErr_SetString(PyExc_ValueError, "Invalid TSC setting");
                return NULL;
            }
            break;
    }
    /*
     * Calling prctl
     * There are 3 basic call modes:
     * - Setters and getters for which the return value is the result
     * - Getters for which the result is placed in arg2
     * - Getters and setters that deal with strings.
     *
     * This function takes care of all that and always returns Py_None for
     * settings or the result of a getter call as a PyInt or PyString.
     */
    switch(option) {
#ifdef PR_CAPBSET_READ
        case(PR_CAPBSET_READ):
        case(PR_CAPBSET_DROP):
#endif
#ifdef PR_SET_CHILD_SUBREAPER
        case(PR_SET_CHILD_SUBREAPER):
#endif
        case(PR_SET_DUMPABLE):
        case(PR_GET_DUMPABLE):
        case(PR_SET_ENDIAN):
        case(PR_SET_FPEMU):
        case(PR_SET_FPEXC):
        case(PR_SET_KEEPCAPS):
        case(PR_GET_KEEPCAPS):
#ifdef PR_MCE_KILL
        case(PR_GET_MCE_KILL):
#endif
#ifdef PR_GET_NO_NEW_PRIVS
        case(PR_GET_NO_NEW_PRIVS):
        case(PR_SET_NO_NEW_PRIVS):
#endif
        case(PR_SET_PDEATHSIG):
#if defined(PR_GET_PTRACER) && (PR_GET_PTRACER != NOT_SET)
        case(PR_GET_PTRACER):
#endif
#ifdef PR_SET_PTRACER
        case(PR_SET_PTRACER):
#endif
#ifdef PR_SET_SECCOMP
        case(PR_SET_SECCOMP):
        case(PR_GET_SECCOMP):
#endif
#ifdef PR_SET_SECUREBITS
        case(PR_SET_SECUREBITS):
        case(PR_GET_SECUREBITS):
#endif
#ifdef PR_GET_TIMERSLACK
        case(PR_GET_TIMERSLACK):
        case(PR_SET_TIMERSLACK):
#endif
        case(PR_SET_TIMING):
        case(PR_GET_TIMING):
#ifdef PR_SET_TSC
        case(PR_SET_TSC):
#endif
        case(PR_SET_UNALIGN):
            result = prctl(option, arg, 0, 0, 0);
            if(result < 0) {
                PyErr_SetFromErrno(PyExc_OSError);
                return NULL;
            }
            switch(option) {
#ifdef PR_CAPBSET_READ
                case(PR_CAPBSET_READ):
#endif
                case(PR_GET_DUMPABLE):
                case(PR_GET_KEEPCAPS):
#ifdef PR_GET_SECCOMP
                case(PR_GET_SECCOMP):
#endif
                case(PR_GET_TIMING):
                    return PyBool_FromLong(result);
#ifdef PR_MCE_KILL
                case(PR_GET_MCE_KILL):
#endif
#ifdef PR_GET_NO_NEW_PRIVS
                case(PR_GET_NO_NEW_PRIVS):
#endif
#if defined(PR_GET_PTRACER) && (PR_GET_PTRACER != NOT_SET)
                case(PR_GET_PTRACER):
#endif
#ifdef PR_GET_SECUREBITS
                case(PR_GET_SECUREBITS):
#endif
#ifdef PR_GET_TIMERSLACK
                case(PR_GET_TIMERSLACK):
#endif
                    return PyInt_FromLong(result);
#if defined(PR_GET_PTRACER) && (PR_GET_PTRACER == NOT_SET)
                case(PR_SET_PTRACER):
                    __cached_ptracer = arg;
                    break;
#endif
            }
            break;
#ifdef PR_GET_CHILD_SUBREAPER
        case(PR_GET_CHILD_SUBREAPER):
#endif
        case(PR_GET_ENDIAN):
        case(PR_GET_FPEMU):
        case(PR_GET_FPEXC):
        case(PR_GET_PDEATHSIG):
#ifdef PR_GET_TSC
        case(PR_GET_TSC):
#endif
        case(PR_GET_UNALIGN):
#ifdef PR_GET_TID_ADDRESS
        case(PR_GET_TID_ADDRESS):
#endif
            result = prctl(option, &arg, 0, 0, 0);
            if(result < 0) {
                PyErr_SetFromErrno(PyExc_OSError);
                return NULL;
            }
            return PyInt_FromLong(arg);
        case(PR_SET_NAME):
        case(PR_GET_NAME):
            result = prctl(option, name, 0, 0, 0);
            if(result < 0) {
                PyErr_SetFromErrno(PyExc_OSError);
                return NULL;
            }
            if(option == PR_GET_NAME) {
                return Py_BuildValue("s", name);
            }
            break;
#if defined(PR_GET_PTRACER) && (PR_GET_PTRACER == NOT_SET)
        case(PR_GET_PTRACER):
            if(__cached_ptracer == NOT_SET)
                return PyInt_FromLong(getppid());
            return PyInt_FromLong(__cached_ptracer);
#endif
#ifdef PR_MCE_KILL
        case(PR_SET_MCE_KILL):
            result = prctl(option, PR_MCE_KILL_SET, arg, 0, 0);
            if(result < 0) {
                PyErr_SetFromErrno(PyExc_OSError);
                return NULL;
            }
            break;
#endif
        default:
            PyErr_SetString(PyExc_ValueError, "Unknown prctl option");
            return NULL;
    }

    /* None is returned by default */
    Py_RETURN_NONE;
}

/* While not part of prctl, this complements PR_SET_NAME */
static int __real_argc = -1;
static char **__real_argv = NULL;
#if PY_MAJOR_VERSION < 3
#define _Py_GetArgcArgv Py_GetArgcArgv
#else
/* In python 3, Py_GetArgcArgv doesn't actually return the real argv, but an
 * encoded copy of it. We try to find the real one by going back from the start
 * of environ.
 */
static char * encode(wchar_t *wstr) {
    PyObject *unicodestr = NULL, *bytesstr = NULL;
    char *str = NULL;

    unicodestr = PyUnicode_FromWideChar(wstr, -1);
    if(!unicodestr) {
        PyErr_Clear();
        return NULL;
    }

    bytesstr =  PyUnicode_AsEncodedString(unicodestr, PyUnicode_GetDefaultEncoding(), "strict");
    if(!bytesstr) {
        PyErr_Clear();
        Py_XDECREF(unicodestr);
        return NULL;
    }

    str = PyBytes_AsString(bytesstr);
    Py_XDECREF(unicodestr);
    Py_XDECREF(bytesstr);
    return str;
}

static int _Py_GetArgcArgv(int* argc, char ***argv) {
    int i = 0;
    wchar_t **argv_w;
    char **buf = NULL , *arg0 = NULL, *ptr = 0, *limit = NULL;

    Py_GetArgcArgv(argc, &argv_w);

    buf = (char **)malloc((*argc + 1) * sizeof(char *));
    buf[*argc] = NULL;

    /* Walk back from environ until you find argc-1 null-terminated strings. */
    ptr = environ[0] - 1;
    limit = ptr - 8192;
    for(i=*argc-1; i >= 1; --i) {
        ptr--;
        while (*ptr && ptr-- > limit);
        if (ptr <= limit) {
            free(buf);
            return 0;
        }
        buf[i] = (ptr + 1);
    }

    /* Now try to find argv[0] */
    arg0 = encode(argv_w[0]);
    if(!arg0) {
        free(buf);
        return 0;
    }
    ptr -= strlen(arg0);
    if(strcmp(ptr, arg0)) {
        free(buf);
        return 0;
    }

    buf[0] = ptr;
    *argv = buf;
    return 1;
}
#endif

static PyObject *
prctl_set_proctitle(PyObject *self, PyObject *args)
{
    int argc = 0;
    char **argv;
    int len;
    char *title;
    if(!PyArg_ParseTuple(args, "s", &title)) {
        return NULL;
    }
    if(__real_argc > 0)  {
        argc = __real_argc;
        argv = __real_argv;
    }
    else {
        _Py_GetArgcArgv(&argc, &argv);
        __real_argc = argc;
        __real_argv = argv;
    }

    if(argc <= 0) {
        PyErr_SetString(PyExc_RuntimeError, "Failed to locate argc/argv");
        return NULL;
    }
    /* Determine up to where we can write */
    len = (size_t)(argv[argc-1]) + strlen(argv[argc-1]) - (size_t)(argv[0]);
    strncpy(argv[0], title, len);
    if(strlen(title) < len)
        memset(argv[0] + strlen(title), 0, len - strlen(title));
    Py_RETURN_NONE;
}

/* TODO: Add a getter? */

static PyObject * prctl_get_caps_flag(PyObject *list, cap_t caps, int flag) {
    int i;
    PyObject *ret, *item, *val;
    cap_flag_value_t value;

    if(list && !PySequence_Check(list)) {
        PyErr_SetString(PyExc_TypeError, "A sequence of integers is required");
        return NULL;
    }
    ret = PyDict_New();
    if(!list)
        return ret;
    for(i=0; i < PyList_Size(list); i++) {
        item = PyList_GetItem(list, i);
        if(!PyInt_Check(item)) {
            PyErr_SetString(PyExc_TypeError, "A sequence of integers is required");
            return ret; /* Return the list so it can be freed */
        }
        if(cap_get_flag(caps, PyInt_AsLong(item), flag, &value) == -1) {
            PyErr_SetFromErrno(PyExc_OSError);
            return ret;
        }
        val = PyBool_FromLong(value);
        PyDict_SetItem(ret, item, val);
        Py_XDECREF(val);
    }
    return ret;
}

static int prctl_set_caps_flag(PyObject *list, cap_t caps, int flag, cap_flag_value_t value) {
    int i;
    cap_value_t cap;
    PyObject *item;

    if(list && !PySequence_Check(list)) {
        PyErr_SetString(PyExc_TypeError, "A sequence of integers is required");
        return 0;
    }
    if(!list)
        return 1;

    for(i=0; i < PyList_Size(list); i++) {
        item = PyList_GetItem(list, i);
        if(!PyInt_Check(item)) {
            PyErr_SetString(PyExc_TypeError, "A sequence of integers is required");
            return 0;
        }
        cap = PyInt_AsLong(item);
        if(cap_set_flag(caps, flag, 1, &cap, value) == -1) {
            PyErr_SetFromErrno(PyExc_OSError);
            return 0;
        }
    }
    return 1;
}

static PyObject * prctl_get_caps(PyObject *self, PyObject *args)
{
    PyObject *effective = NULL;
    PyObject *permitted = NULL;
    PyObject *inheritable = NULL;
    PyObject *effective_ = NULL;
    PyObject *permitted_ = NULL;
    PyObject *inheritable_ = NULL;
    PyObject *ret = NULL;
    PyObject *key = NULL;
    cap_t caps = NULL;

    if(!PyArg_ParseTuple(args, "O|OO", &effective, &permitted, &inheritable)) {
        return NULL;
    }
    caps = cap_get_proc();
    if(!caps) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }
    effective_ = prctl_get_caps_flag(effective, caps, CAP_EFFECTIVE);
    if(PyErr_Occurred()) goto error;
    permitted_ = prctl_get_caps_flag(permitted, caps, CAP_PERMITTED);
    if(PyErr_Occurred()) goto error;
    inheritable_ = prctl_get_caps_flag(inheritable, caps, CAP_INHERITABLE);
    if(PyErr_Occurred()) goto error;

    /* Now build the dict */
    ret = PyDict_New();
    key = PyInt_FromLong(CAP_EFFECTIVE);
    PyDict_SetItem(ret, key, effective_);
    Py_XDECREF(key);
    key = PyInt_FromLong(CAP_PERMITTED);
    PyDict_SetItem(ret, key, permitted_);
    Py_XDECREF(key);
    key = PyInt_FromLong(CAP_INHERITABLE);
    PyDict_SetItem(ret, key, inheritable_);
    Py_XDECREF(key);

error:
    cap_free(caps);
    Py_XDECREF(effective_);
    Py_XDECREF(permitted_);
    Py_XDECREF(inheritable_);

    return ret;
}

static PyObject * prctl_set_caps(PyObject *self, PyObject *args)
{
    PyObject *effective_set = NULL;
    PyObject *permitted_set = NULL;
    PyObject *inheritable_set = NULL;
    PyObject *effective_clear = NULL;
    PyObject *permitted_clear = NULL;
    PyObject *inheritable_clear = NULL;
    cap_t caps = NULL;

    if(!PyArg_ParseTuple(args, "O|OOOOO", &effective_set, &permitted_set, &inheritable_set,
                                          &effective_clear, &permitted_clear, &inheritable_clear)) {
        return NULL;
    }
    caps = cap_get_proc();
    if(!caps) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }
    if(!prctl_set_caps_flag(effective_set, caps, CAP_EFFECTIVE, CAP_SET))
        return NULL;
    if(!prctl_set_caps_flag(permitted_set, caps, CAP_PERMITTED, CAP_SET))
        return NULL;
    if(!prctl_set_caps_flag(inheritable_set, caps, CAP_INHERITABLE, CAP_SET))
        return NULL;
    if(!prctl_set_caps_flag(effective_clear, caps, CAP_EFFECTIVE, CAP_CLEAR))
        return NULL;
    if(!prctl_set_caps_flag(permitted_clear, caps, CAP_PERMITTED, CAP_CLEAR))
        return NULL;
    if(!prctl_set_caps_flag(inheritable_clear, caps, CAP_INHERITABLE, CAP_CLEAR))
        return NULL;

    if(cap_set_proc(caps) == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }

    Py_RETURN_NONE;
}

#ifdef cap_to_name
static PyObject * prctl_cap_to_name(PyObject *self, PyObject *args) {
    cap_value_t cap;
    char *name;
    PyObject *ret;

    if(!PyArg_ParseTuple(args, "i", &cap)){
        return NULL;
    }
    name = cap_to_name(cap);
    if(!name) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }
    ret = Py_BuildValue("s", name+4); /* Exclude the cap_ prefix */
    cap_free(name);
    return ret;
}
#endif

static PyMethodDef PrctlMethods[] = {
    {"get_caps", prctl_get_caps, METH_VARARGS, "Get process capabilities"},
    {"set_caps", prctl_set_caps, METH_VARARGS, "Set process capabilities"},
#ifdef cap_to_name
    {"cap_to_name", prctl_cap_to_name, METH_VARARGS, "Convert capability number to name"},
#endif
    {"prctl", prctl_prctl, METH_VARARGS, "Call prctl"},
    {"set_proctitle", prctl_set_proctitle, METH_VARARGS, "Set the process title"},
    {NULL, NULL, 0, NULL} /* Sentinel */
};

#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef prctlmodule = {
    PyModuleDef_HEAD_INIT,
    "_prctl",
    NULL,
    -1,
    PrctlMethods
};
#endif

/* These macros avoid tediously repeating a name 2 or 4 times */
#define namedconstant(x) PyModule_AddIntConstant(_prctl, #x, x)
#define namedattribute(x) do{ \
    PyModule_AddIntConstant(_prctl, "PR_GET_" #x,  PR_GET_ ## x); \
    PyModule_AddIntConstant(_prctl, "PR_SET_" #x,  PR_SET_ ## x); \
} while(0)

PyMODINIT_FUNC
#if PY_MAJOR_VERSION < 3
init_prctl(void)
#else
PyInit__prctl(void)
#endif
{
#if PY_MAJOR_VERSION < 3
    PyObject *_prctl = Py_InitModule("_prctl", PrctlMethods);
#else
    PyObject *_prctl = PyModule_Create(&prctlmodule);
#endif
    /* Add the PR_* constants */
#ifdef PR_CAPBSET_READ
    namedconstant(PR_CAPBSET_READ);
    namedconstant(PR_CAPBSET_DROP);
#endif
    namedattribute(DUMPABLE);
    namedattribute(ENDIAN);
    namedconstant(PR_ENDIAN_BIG);
    namedconstant(PR_ENDIAN_LITTLE);
    namedconstant(PR_ENDIAN_PPC_LITTLE);
    namedattribute(FPEMU);
    namedconstant(PR_FPEMU_NOPRINT);
    namedconstant(PR_FPEMU_SIGFPE);
    namedattribute(FPEXC);
    namedconstant(PR_FP_EXC_SW_ENABLE);
    namedconstant(PR_FP_EXC_DIV);
    namedconstant(PR_FP_EXC_OVF);
    namedconstant(PR_FP_EXC_UND);
    namedconstant(PR_FP_EXC_RES);
    namedconstant(PR_FP_EXC_INV);
    namedconstant(PR_FP_EXC_DISABLED);
    namedconstant(PR_FP_EXC_NONRECOV);
    namedconstant(PR_FP_EXC_ASYNC);
    namedconstant(PR_FP_EXC_PRECISE);
    namedattribute(KEEPCAPS);
#ifdef PR_MCE_KILL
    namedattribute(MCE_KILL);
    namedconstant(PR_MCE_KILL_DEFAULT);
    namedconstant(PR_MCE_KILL_EARLY);
    namedconstant(PR_MCE_KILL_LATE);
#endif
    namedattribute(NAME);
    namedattribute(PDEATHSIG);
#ifdef PR_SET_PTRACER
    namedattribute(PTRACER);
#endif
#ifdef PR_SET_PTRACER_ANY
    namedconstant(PR_SET_PTRACER_ANY);
#endif
#ifdef PR_SET_CHILD_SUBREAPER
    namedattribute(CHILD_SUBREAPER);
#endif
#ifdef PR_SET_NO_NEW_PRIVS
    namedattribute(NO_NEW_PRIVS);
#endif

#ifdef PR_GET_SECCOMP
    namedattribute(SECCOMP);
#endif
#ifdef PR_GET_SECUREBITS
    namedattribute(SECUREBITS);
#endif
#ifdef PR_GET_TIMERSLACK
    namedattribute(TIMERSLACK);
#endif
    namedattribute(TIMING);
    namedconstant(PR_TIMING_STATISTICAL);
    namedconstant(PR_TIMING_TIMESTAMP);
#ifdef PR_SET_TSC
    namedattribute(TSC);
    namedconstant(PR_TSC_ENABLE);
    namedconstant(PR_TSC_SIGSEGV);
#endif
    namedattribute(UNALIGN);
    namedconstant(PR_UNALIGN_NOPRINT);
    namedconstant(PR_UNALIGN_SIGBUS);
#ifdef PR_GET_TID_ADDRESS
    namedconstant(PR_GET_TID_ADDRESS);
#endif
    /* Add the CAP_* constants too */
    namedconstant(CAP_EFFECTIVE);
    namedconstant(CAP_PERMITTED);
    namedconstant(CAP_INHERITABLE);
    namedconstant(CAP_CHOWN);
    namedconstant(CAP_DAC_OVERRIDE);
    namedconstant(CAP_DAC_READ_SEARCH);
    namedconstant(CAP_FOWNER);
    namedconstant(CAP_FSETID);
    namedconstant(CAP_KILL);
    namedconstant(CAP_SETGID);
    namedconstant(CAP_SETUID);
    namedconstant(CAP_SETPCAP);
    namedconstant(CAP_LINUX_IMMUTABLE);
    namedconstant(CAP_NET_BIND_SERVICE);
    namedconstant(CAP_NET_BROADCAST);
    namedconstant(CAP_NET_ADMIN);
    namedconstant(CAP_NET_RAW);
    namedconstant(CAP_IPC_LOCK);
    namedconstant(CAP_IPC_OWNER);
    namedconstant(CAP_SYS_MODULE);
    namedconstant(CAP_SYS_RAWIO);
    namedconstant(CAP_SYS_CHROOT);
    namedconstant(CAP_SYS_PTRACE);
    namedconstant(CAP_SYS_PACCT);
    namedconstant(CAP_SYS_ADMIN);
    namedconstant(CAP_SYS_BOOT);
    namedconstant(CAP_SYS_NICE);
    namedconstant(CAP_SYS_RESOURCE);
    namedconstant(CAP_SYS_TIME);
    namedconstant(CAP_SYS_TTY_CONFIG);
    namedconstant(CAP_MKNOD);
    namedconstant(CAP_LEASE);
    namedconstant(CAP_AUDIT_WRITE);
    namedconstant(CAP_AUDIT_CONTROL);
#ifdef CAP_SETFCAP
    namedconstant(CAP_SETFCAP);
#endif
#ifdef CAP_MAC_OVERRIDE
    namedconstant(CAP_MAC_OVERRIDE);
#endif
#ifdef CAP_MAC_ADMIN
    namedconstant(CAP_MAC_ADMIN);
#endif
#ifdef CAP_SYSLOG
    namedconstant(CAP_SYSLOG);
#endif
#ifdef CAP_WAKE_ALARM
    namedconstant(CAP_WAKE_ALARM);
#endif
    /* And the securebits constants */
    namedconstant(SECURE_KEEP_CAPS);
    namedconstant(SECURE_NO_SETUID_FIXUP);
    namedconstant(SECURE_NOROOT);
    namedconstant(SECURE_KEEP_CAPS_LOCKED);
    namedconstant(SECURE_NO_SETUID_FIXUP_LOCKED);
    namedconstant(SECURE_NOROOT_LOCKED);
    namedconstant(SECBIT_KEEP_CAPS);
    namedconstant(SECBIT_NO_SETUID_FIXUP);
    namedconstant(SECBIT_NOROOT);
    namedconstant(SECBIT_KEEP_CAPS_LOCKED);
    namedconstant(SECBIT_NO_SETUID_FIXUP_LOCKED);
    namedconstant(SECBIT_NOROOT_LOCKED);
#if PY_MAJOR_VERSION >= 3
    return _prctl;
#endif
}