xref: /linux/tools/testing/selftests/filesystems/utils.h (revision c68946ee7eb7fb5dc19c8d11f7e4e696c8ee6508)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 
3 #ifndef __IDMAP_UTILS_H
4 #define __IDMAP_UTILS_H
5 
6 #ifndef _GNU_SOURCE
7 #define _GNU_SOURCE
8 #endif
9 #include <errno.h>
10 #include <linux/types.h>
11 #include <sched.h>
12 #include <signal.h>
13 #include <stdbool.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <syscall.h>
18 #include <sys/capability.h>
19 #include <sys/fsuid.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22 
23 extern int get_userns_fd(unsigned long nsid, unsigned long hostid,
24 			 unsigned long range);
25 
26 extern int caps_down(void);
27 
28 extern bool switch_ids(uid_t uid, gid_t gid);
29 
30 static inline bool switch_userns(int fd, uid_t uid, gid_t gid, bool drop_caps)
31 {
32 	if (setns(fd, CLONE_NEWUSER))
33 		return false;
34 
35 	if (!switch_ids(uid, gid))
36 		return false;
37 
38 	if (drop_caps && !caps_down())
39 		return false;
40 
41 	return true;
42 }
43 
44 #endif /* __IDMAP_UTILS_H */
45