summaryrefslogtreecommitdiff
path: root/linuxnamespaces/syscalls.py
blob: d7154fc034ba2bfbc6bdd7fc6eb15cc3b51c48d0 (plain)
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
# Copyright 2024 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: GPL-3

"""Provide typed Python functions for a number of Linux system calls relevant
for Linux namespaces including the new mount API.
"""

import asyncio
import ctypes
import dataclasses
import enum
import errno
import os
import typing

from .atlocation import AtFlags, AtLocation, AtLocationLike, PathConvertible


LIBC_SO = ctypes.CDLL("libc.so.6", use_errno=True)


class CloneFlags(enum.IntFlag):
    """This value may be supplied to
    * unshare(2) flags
    * clone3(2) clone_args.flags
    * setns(2) nstype
    """

    NONE =           0x00000000
    NEWTIME =        0x00000080
    VM =             0x00000100
    FS =             0x00000200
    FILES =          0x00000400
    SIGHAND =        0x00000800
    PIDFD =          0x00001000
    PTRACE =         0x00002000
    VFORK =          0x00004000
    PARENT =         0x00008000
    THREAD =         0x00010000
    NEWNS =          0x00020000
    SYSVSEM =        0x00040000
    SETTLS =         0x00080000
    PARENT_SETTID =  0x00100000
    CHILD_CLEARTID = 0x00200000
    DETACHED =       0x00400000
    UNTRACED =       0x00800000
    CHILD_SETTID =   0x01000000
    NEWCGROUP =      0x02000000
    NEWUTS =         0x04000000
    NEWIPC =         0x08000000
    NEWUSER =        0x10000000
    NEWPID =         0x20000000
    NEWNET =         0x40000000
    IO =             0x80000000
    NS_FLAGS = (
        NEWCGROUP
        | NEWIPC
        | NEWNET
        | NEWNS
        | NEWPID
        | NEWTIME
        | NEWUSER
        | NEWUTS
    )
    UNSHARE_FLAGS = NS_FLAGS | FILES | FS | SYSVSEM


class EventFDFlags(enum.IntFlag):
    """This value may be supplied as flags to eventfd(2)."""

    NONE =            0
    CLOEXEC = 0o2000000
    NONBLOCK =   0o4000
    SEMAPHORE =     0o1
    ALL_FLAGS = CLOEXEC | NONBLOCK | SEMAPHORE


class MountFlags(enum.IntFlag):
    """This value may be supplied as mountflags to mount(2)."""

    NONE = 0
    RDONLY =       1 << 0
    NOSUID =       1 << 1
    NODEV =        1 << 2
    NOEXEC =       1 << 3
    SYNCHRONOUS =  1 << 4
    REMOUNT =      1 << 5
    MANDLOCK =     1 << 6
    DIRSYNC =      1 << 7
    NOSYMFOLLOW =  1 << 8
    # Bit 9 vanished
    NOATIME =      1 << 10
    NODIRATIME =   1 << 11
    BIND =         1 << 12
    MOVE =         1 << 13
    REC =          1 << 14
    SILENT =       1 << 15
    POSIXACL =     1 << 16
    UNBINDABLE =   1 << 17
    PRIVATE =      1 << 18
    SLAVE =        1 << 19
    SHARED =       1 << 20
    RELATIME =     1 << 21
    KERNMOUNT =    1 << 22
    I_VERSION =    1 << 23
    STRICTATIME =  1 << 24
    LAZYTIME =     1 << 25
    SUBMOUNT =     1 << 26
    NOREMOTELOCK = 1 << 27
    NOSEC =        1 << 28
    BORN =         1 << 29
    ACTIVE =       1 << 30
    NOUSER =       1 << 31

    PROPAGATION_FLAGS = UNBINDABLE | PRIVATE | SLAVE | SHARED

    # Map each flag to:
    # * The flag value
    # * Whether the flag value is negated
    # * Whether the flag must be negated
    # * Whether the flag can be negated
    __flagstrmap = {
        "acl": (POSIXACL, False, False, False),
        "async": (SYNCHRONOUS, True, False, False),
        "atime": (NOATIME, True, False, True),
        "bind": (BIND, False, False, False),
        "dev": (NODEV, True, False, True),
        "diratime": (NODIRATIME, True, False, True),
        "dirsync": (DIRSYNC, False, False, False),
        "exec": (NOEXEC, True, False, True),
        "iversion": (I_VERSION, False, False, True),
        "lazytime": (LAZYTIME, False, False, True),
        "loud": (SILENT, True, False, False),
        "mand": (MANDLOCK, False, False, True),
        "private": (PRIVATE, False, False, False),
        "rbind": (BIND | REC, False, False, False),
        "relatime": (RELATIME, False, False, True),
        "remount": (REMOUNT, False, False, True),
        "ro": (RDONLY, False, False, False),
        "rprivate": (PRIVATE | REC, False, False, False),
        "rshared": (SHARED | REC, False, False, False),
        "rslave": (SLAVE | REC, False, False, False),
        "runbindable": (UNBINDABLE | REC, False, False, False),
        "rw": (RDONLY, True, False, False),
        "shared": (SHARED, False, False, False),
        "silent": (SILENT, False, False, False),
        "slave": (SLAVE, False, False, False),
        "strictatime": (STRICTATIME, False, False, True),
        "suid": (NOSUID, True, False, True),
        "symfollow": (NOSYMFOLLOW, True, False, True),
        "sync": (SYNCHRONOUS, False, False, False),
        "unbindable": (UNBINDABLE, False, False, False),
    }

    def change(self, flagsstr: str) -> "MountFlags":
        """Return modified mount flags after applying comma-separated mount
        flags represented as a str. Raise a ValueError if any given flag
        does not correspond to a textual mount flag.
        """
        ret = self
        for flagstr in flagsstr.split(","):
            if not flagstr:
                continue
            flag, negated, mustnegate, cannegate = self.__flagstrmap.get(
                flagstr.removeprefix("no"),
                (MountFlags.NONE, False, True, False),
            )
            if mustnegate <= flagstr.startswith("no") <= cannegate:
                if negated ^ flagstr.startswith("no"):
                    ret &= ~flag
                else:
                    if flag & MountFlags.PROPAGATION_FLAGS:
                        ret &= ~MountFlags.PROPAGATION_FLAGS
                    ret |= flag
            else:
                raise ValueError(f"not a valid mount flag: {flagstr!r}")
        return ret

    @staticmethod
    def fromstr(flagsstr: str) -> "MountFlags":
        """Construct mount flags by changing flags according to the passed
        flagsstr using the change method on an initial value with all flags
        cleared.
        """
        return MountFlags.NONE.change(flagsstr)

    __flagvals: list[tuple[int, str]] = sorted(
        [
            (RDONLY, "ro"),
            (NOSUID, "nosuid"),
            (NODEV, "nodev"),
            (NOEXEC, "noexec"),
            (SYNCHRONOUS, "sync"),
            (REMOUNT, "remount"),
            (MANDLOCK, "mand"),
            (DIRSYNC, "dirsync"),
            (NOSYMFOLLOW, "nosymfollow"),
            (NOATIME, "noatime"),
            (NODIRATIME, "nodiratime"),
            (BIND, "bind"),
            (BIND | REC, "rbind"),
            (SILENT, "silent"),
            (POSIXACL, "acl"),
            (UNBINDABLE, "unbindable"),
            (UNBINDABLE | REC, "runbindable"),
            (PRIVATE, "private"),
            (PRIVATE | REC, "rprivate"),
            (SLAVE, "slave"),
            (SLAVE | REC, "rslave"),
            (SHARED, "shared"),
            (SHARED | REC, "rshared"),
            (RELATIME, "relatime"),
            (I_VERSION, "iversion"),
            (STRICTATIME, "strictatime"),
            (LAZYTIME, "lazytime"),
        ],
        reverse=True,
    )

    def tostr(self) -> str:
        """Attempt to represent the flags in a comma-separated, textual way."""
        if (self & MountFlags.PROPAGATION_FLAGS).bit_count() > 1:
            raise ValueError("cannot represent conflicting propagation flags")
        parts: list[str] = []
        remain = self
        for val, text in MountFlags.__flagvals:
            # Older mypy think MountFlags.__flagvals and thus text was of type
            # MountFlags.
            assert isinstance(text, str)
            if remain & val == val:
                parts.insert(0, text)
                remain &= ~val
        if remain:
            raise ValueError("cannot represent flags {remain}")
        return ",".join(parts)


class MountSetattrFlags(enum.IntFlag):
    """This value may be supplied as flags to mount_setattr(2)."""

    NONE = 0
    AT_SYMLINK_NOFOLLOW = 0x100
    AT_NO_AUTOMOUNT =     0x800
    AT_EMPTY_PATH =      0x1000
    AT_RECURSIVE =       0x8000

    @staticmethod
    def from_atflags(flags: AtFlags) -> "MountSetattrFlags":
        ret = MountSetattrFlags.NONE
        if flags & AtFlags.AT_SYMLINK_NOFOLLOW:
            ret |= MountSetattrFlags.AT_SYMLINK_NOFOLLOW
        if flags & AtFlags.AT_NO_AUTOMOUNT:
            ret |= MountSetattrFlags.AT_NO_AUTOMOUNT
        if flags & AtFlags.AT_EMPTY_PATH:
            ret |= MountSetattrFlags.AT_EMPTY_PATH
        return ret


class MountAttrFlags(enum.IntFlag):
    """This value may be supplied as attr->attr_set or attr->attr_clr to
    mount_setattr(2).
    """

    NONE        = 0x000000
    RDONLY      = 0x000001  # Mount read-only.
    NOSUID      = 0x000002  # Ignore suid and sgid bits.
    NODEV       = 0x000004  # Disallow access to device special files.
    NOEXEC      = 0x000008  # Disallow program execution.
    RELATIME    = 0x000000  # - Update atime relative to mtime/ctime.
    NOATIME     = 0x000010  # - Do not update access times.
    STRICTATIME = 0x000020  # - Always perform atime updates
    _ATIME      = 0x000070 | NOATIME | STRICTATIME
                            # Setting on how atime should be updated.
    NODIRATIME  = 0x000080  # Do not update directory access times.
    IDMAP       = 0x100000  # Idmap mount to @userns_fd in struct mount_attr.
    NOSYMFOLLOW = 0x200000  # Do not follow symlinks.

    ALL_FLAGS = (
        RDONLY
        | NOSYMFOLLOW
        | NODEV
        | NOEXEC
        | _ATIME
        | NODIRATIME
        | IDMAP
        | NOSYMFOLLOW
    )


class MountAttr(ctypes.Structure):
    """This value may be supplied to mount_setattr(2) as attr."""

    _fields_ = [
        ("attr_set", ctypes.c_ulonglong),
        ("attr_clr", ctypes.c_ulonglong),
        ("propagation", ctypes.c_ulonglong),
        ("userns_fd", ctypes.c_ulonglong),
    ]


class MoveMountFlags(enum.IntFlag):
    """This value may be supplied to move_mount(2) as flags."""

    NONE =         0x00000000
    F_SYMLINKS =   0x00000001  # Follow symlinks on from path
    F_AUTOMOUNTS = 0x00000002  # Follow automounts on from path
    F_EMPTY_PATH = 0x00000004  # Empty from path permitted
    T_SYMLINKS =   0x00000010  # Follow symlinks on to path
    T_AUTOMOUNTS = 0x00000020  # Follow automounts on to path
    T_EMPTY_PATH = 0x00000040  # Empty to path permitted
    SET_GROUP =    0x00000100  # Set sharing group instead
    ALL_FLAGS = (
        F_SYMLINKS
        | F_AUTOMOUNTS
        | F_EMPTY_PATH
        | T_SYMLINKS
        | T_AUTOMOUNTS
        | T_EMPTY_PATH
        | SET_GROUP
    )


class OpenTreeFlags(enum.IntFlag):
    """This value may be supplied to open_tree(2) as flags."""

    NONE = 0
    OPEN_TREE_CLONE =       0x1
    OPEN_TREE_CLOEXEC = os.O_CLOEXEC
    AT_SYMLINK_NOFOLLOW = 0x100
    AT_NO_AUTOMOUNT =     0x800
    AT_EMPTY_PATH =      0x1000
    AT_RECURSIVE =       0x8000
    ALL_FLAGS = (
        OPEN_TREE_CLONE
        | OPEN_TREE_CLOEXEC
        | AT_SYMLINK_NOFOLLOW
        | AT_NO_AUTOMOUNT
        | AT_EMPTY_PATH
        | AT_RECURSIVE
    )


class PrctlOption(enum.IntEnum):
    """This value may be supplied to prctl(2) as option."""

    PR_SET_PDEATHSIG = 1
    PR_CAP_AMBIENT = 47


class UmountFlags(enum.IntFlag):
    """This value may be supplied to umount2(2) as flags."""

    NONE = 0
    FORCE = 1
    DETACH = 2
    EXPIRE = 4
    NOFOLLOW = 8
    ALL_FLAGS = FORCE | DETACH | EXPIRE | NOFOLLOW


def call_libc(funcname: str, *args: typing.Any) -> int:
    """Call a function from the C library with given args. This assumes that
    the function returns an integer that is non-negative on success. On
    failure, an OSError with errno is raised.
    """
    ret: int = LIBC_SO[funcname](*args)
    if ret < 0:
        err = ctypes.get_errno()
        raise OSError(
            err, f"{funcname}() failed with error {err}: {os.strerror(err)}"
        )
    return ret


@dataclasses.dataclass
class CapabilitySets:
    """Represent the main capability sets that capget/capset deal with."""

    effective: int
    permitted: int
    inheritable: int

    @staticmethod
    def _create_header(pid: int) -> ctypes.Array[ctypes.c_uint32]:
        return (ctypes.c_uint32 * 2)(
            0x20080522,  # _LINUX_CAPABILITY_VERSION_3
            pid,
        )

    @classmethod
    def get(cls, pid: int = 0) -> "CapabilitySets":
        """Call capget to retrieve the current capability sets."""
        header = cls._create_header(pid)
        data = (ctypes.c_uint32 * 6)()
        call_libc("capget", ctypes.byref(header), ctypes.byref(data))
        return cls(
            (data[3] << 32) | data[0],
            (data[4] << 32) | data[1],
            (data[5] << 32) | data[2],
        )

    def set(self, pid: int = 0) -> None:
        """Call capset to set the capabilities."""
        header = self._create_header(pid)
        data = (ctypes.c_uint32 * 6)(
            self.effective & 0xffffffff,
            self.permitted & 0xffffffff,
            self.inheritable & 0xffffffff,
            self.effective >> 32,
            self.permitted >> 32,
            self.inheritable >> 32,
        )
        call_libc("capset", ctypes.byref(header), ctypes.byref(data))


class EventFD:
    """Represent a file descriptor returned from eventfd(2)."""

    def __init__(
        self, initval: int = 0, flags: EventFDFlags = EventFDFlags.NONE
    ) -> None:
        if flags & ~EventFDFlags.ALL_FLAGS:
            raise ValueError("invalid flags for eventfd")
        self.fd = call_libc("eventfd", initval, int(flags))

    def read(self) -> int:
        """Decrease the value of the eventfd using eventfd_read."""
        if self.fd < 0:
            raise ValueError("attempt to read from closed eventfd")
        cvalue = ctypes.c_ulonglong()
        call_libc("eventfd_read", self.fd, ctypes.byref(cvalue))
        return cvalue.value

    def __handle_readable(self, fd: int, fut: asyncio.Future[int]) -> None:
        """Internal helper of aread."""
        try:
            if fd != self.fd:
                raise RuntimeError("EventFD file descriptor changed")
            try:
                result = self.read()
            except OSError as err:
                if err.errno == errno.EAGAIN:
                    return
                raise
        except Exception as exc:
            fut.get_loop().remove_reader(fd)
            fut.set_exception(exc)
        else:
            fut.get_loop().remove_reader(fd)
            fut.set_result(result)

    def aread(self) -> typing.Awaitable[int]:
        """Decrease the value of the eventfd asynchronously. It must have been
        constructed using EventFDFlags.NONBLOCK.
        """
        if self.fd < 0:
            raise ValueError("attempt to read from closed eventfd")
        loop = asyncio.get_running_loop()
        fut: asyncio.Future[int] = loop.create_future()
        loop.add_reader(self.fd, self.__handle_readable, self.fd, fut)
        return fut

    def write(self, value: int = 1) -> None:
        """Add the given value to the eventfd using eventfd_write."""
        if self.fd < 0:
            raise ValueError("attempt to read from closed eventfd")
        if value < 0 or (value >> 64):
            raise ValueError("value for eventfd_write out of range")
        call_libc("eventfd_write", self.fd, ctypes.c_ulonglong(value))

    def fileno(self) -> int:
        """Return the underlying file descriptor."""
        return self.fd

    def close(self) -> None:
        """Close the underlying file descriptor."""
        if self.fd >= 0:
            try:
                os.close(self.fd)
            finally:
                self.fd = -1

    __del__ = close

    def __bool__(self) -> bool:
        """Return True unless the eventfd is closed."""
        return self.fd >= 0

    def __enter__(self) -> "EventFD":
        """When used as a context manager, the EventFD is closed on scope exit.
        """
        return self

    def __exit__(
        self,
        exc_type: typing.Any,
        exc_value: typing.Any,
        traceback: typing.Any,
    ) -> None:
        self.close()


def mount(
    source: PathConvertible,
    target: PathConvertible,
    filesystemtype: str | None,
    flags: MountFlags = MountFlags.NONE,
    data: str | None = None,
) -> None:
    """Python wrapper for mount(2)."""
    if (flags & MountFlags.PROPAGATION_FLAGS).bit_count() > 1:
        raise ValueError("invalid flags for mount")
    if (
        flags & MountFlags.PROPAGATION_FLAGS
        and flags & ~(
            MountFlags.PROPAGATION_FLAGS | MountFlags.REC | MountFlags.SILENT
        )
    ):
        raise ValueError("invalid flags for mount")
    call_libc(
        "mount",
        os.fsencode(source),
        os.fsencode(target),
        None if filesystemtype is None else os.fsencode(filesystemtype),
        int(flags),
        None if data is None else os.fsencode(data),
    )


def mount_setattr(
    filesystem: AtLocationLike,
    recursive: bool,
    attr_set: MountAttrFlags = MountAttrFlags.NONE,
    attr_clr: MountAttrFlags = MountAttrFlags.NONE,
    propagation: int = 0,
    userns_fd: int = -1,
) -> None:
    """Python wrapper for mount_setattr(2)."""
    filesystem = AtLocation(filesystem)
    flags = MountSetattrFlags.from_atflags(filesystem.flags)
    if recursive:
        flags |= MountSetattrFlags.AT_RECURSIVE
    if attr_clr & MountAttrFlags.IDMAP:
        raise ValueError("cannot clear the MOUNT_ATTR_IDMAP flag")
    attr = MountAttr(attr_set, attr_clr, propagation, userns_fd)
    call_libc(
        "mount_setattr",
        filesystem.fd,
        os.fsencode(filesystem.location),
        int(flags),
        ctypes.byref(attr),
        ctypes.sizeof(attr),
    )


def move_mount(
    from_: AtLocationLike,
    to: AtLocationLike,
    flags: MoveMountFlags = MoveMountFlags.NONE,
) -> None:
    """Python wrapper for move_mount(2)."""
    from_ = AtLocation(from_)
    to = AtLocation(to)
    if flags & ~MoveMountFlags.ALL_FLAGS:
        raise ValueError("invalid flags for move_mount")
    if from_.flags & AtFlags.AT_SYMLINK_NOFOLLOW:
        flags &= ~MoveMountFlags.F_SYMLINKS
    else:
        flags |= MoveMountFlags.F_SYMLINKS
    if from_.flags & AtFlags.AT_NO_AUTOMOUNT:
        flags &= ~MoveMountFlags.F_AUTOMOUNTS
    else:
        flags |= MoveMountFlags.F_AUTOMOUNTS
    if from_.flags & AtFlags.AT_EMPTY_PATH:
        flags |= MoveMountFlags.F_EMPTY_PATH
    else:
        flags &= ~MoveMountFlags.F_EMPTY_PATH
    if to.flags & AtFlags.AT_SYMLINK_NOFOLLOW:
        flags &= ~MoveMountFlags.T_SYMLINKS
    else:
        flags |= MoveMountFlags.T_SYMLINKS
    if to.flags & AtFlags.AT_NO_AUTOMOUNT:
        flags &= ~MoveMountFlags.T_AUTOMOUNTS
    else:
        flags |= MoveMountFlags.T_AUTOMOUNTS
    if to.flags & AtFlags.AT_EMPTY_PATH:
        flags |= MoveMountFlags.T_EMPTY_PATH
    else:
        flags &= ~MoveMountFlags.T_EMPTY_PATH
    call_libc(
        "move_mount",
        from_.fd,
        os.fsencode(from_.location),
        to.fd,
        os.fsencode(to.location),
        int(flags),
    )


def open_tree(
    source: AtLocationLike, flags: OpenTreeFlags = OpenTreeFlags.NONE
) -> AtLocation:
    """Python wrapper for open_tree(2)."""
    source = AtLocation(source)
    if flags & ~OpenTreeFlags.ALL_FLAGS:
        raise ValueError("invalid flags for open_tree")
    if (
        flags & OpenTreeFlags.AT_RECURSIVE
        and not flags & OpenTreeFlags.OPEN_TREE_CLONE
    ):
        raise ValueError("invalid flags for open_tree")
    if source.flags & AtFlags.AT_SYMLINK_NOFOLLOW:
        flags |= OpenTreeFlags.AT_SYMLINK_NOFOLLOW
    else:
        flags &= ~OpenTreeFlags.AT_SYMLINK_NOFOLLOW
    if source.flags & AtFlags.AT_NO_AUTOMOUNT:
        flags |= OpenTreeFlags.AT_NO_AUTOMOUNT
    else:
        flags &= ~OpenTreeFlags.AT_NO_AUTOMOUNT
    if source.flags & AtFlags.AT_EMPTY_PATH:
        flags |= OpenTreeFlags.AT_EMPTY_PATH
    else:
        flags &= ~OpenTreeFlags.AT_EMPTY_PATH
    return AtLocation(
        call_libc(
            "open_tree", source.fd, os.fsencode(source.location), int(flags)
        )
    )


def pivot_root(new_root: PathConvertible, put_old: PathConvertible) -> None:
    """Python wrapper for pivot_root(2)."""
    call_libc("pivot_root", os.fsencode(new_root), os.fsencode(put_old))


def prctl(
    option: PrctlOption | int,
    arg2: int = 0,
    arg3: int = 0,
    arg4: int = 0,
    arg5: int = 0,
) -> int:
    """Python wrapper for prctl(2)."""
    return call_libc("prctl", int(option), arg2, arg3, arg4, arg5)


def prctl_raise_ambient_capabilities(capabilities: int) -> None:
    """Raise all ambient capabilities in the given bitfield. If multiple bits
    are set, this results in multiple prctl(2) syscalls.
    """
    while capabilities:
        cap = capabilities & (~capabilities + 1)
        capabilities ^= cap
        prctl(
            PrctlOption.PR_CAP_AMBIENT,
            2,  # PR_CAP_AMBIENT_RAISE
            cap.bit_length() - 1,
        )


def prctl_set_pdeathsig(signum: int) -> None:
    """Set the parent-death signal of the calling process."""
    if signum < 0:
        raise ValueError("invalid signal number")
    prctl(PrctlOption.PR_SET_PDEATHSIG, signum)


def setns(fd: int, nstype: CloneFlags = CloneFlags.NONE) -> None:
    """Python wrapper for setns(2)."""
    if fd < 0:
        raise ValueError("invalid file descriptor")
    if nstype & ~CloneFlags.NS_FLAGS != 0:
        raise ValueError("invalid nstype for setns")
    call_libc("setns", fd, int(nstype))


def umount(
    path: PathConvertible, flags: UmountFlags = UmountFlags.NONE
) -> None:
    """Python wrapper for umount(2)."""
    if flags & ~UmountFlags.ALL_FLAGS:
        raise ValueError("umount flags out of range")
    if flags & UmountFlags.EXPIRE and flags & (
        UmountFlags.FORCE | UmountFlags.DETACH
    ):
        raise ValueError("invalid flags for umount")
    call_libc("umount2", os.fsencode(path), int(flags))


def unshare(flags: CloneFlags) -> None:
    """Python wrapper for unshare(2)."""
    if flags & ~CloneFlags.UNSHARE_FLAGS:
        raise ValueError("invalid flags for unshare")
    call_libc("unshare", int(flags))