• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) Linux Test Project, 2014-2020
4  */
5 
6 #include <stdio.h>
7 #include "lapi/namespaces_constants.h"
8 
9 #define NS_MAX 5
10 static int ns_types[NS_MAX];
11 static int ns_fds[NS_MAX];
12 static int ns_total;
13 
get_ns_fd(int pid,const char * ns)14 static int get_ns_fd(int pid, const char *ns)
15 {
16 	char tmp[PATH_MAX];
17 	struct stat st;
18 	int fd = -1;
19 
20 	sprintf(tmp, "/proc/%d/ns/%s", pid, ns);
21 	if (stat(tmp, &st) == 0) {
22 		fd = SAFE_OPEN(tmp, O_RDONLY);
23 	} else {
24 		if (errno != ENOENT)
25 			tst_brk(TBROK|TERRNO, "failed to stat %s", tmp);
26 	}
27 	return fd;
28 }
29 
init_ns_type(int clone_type,const char * proc_name)30 static void init_ns_type(int clone_type, const char *proc_name)
31 {
32 	int fd;
33 
34 	fd = get_ns_fd(getpid(), proc_name);
35 	if (fd != -1) {
36 		ns_types[ns_total] = clone_type;
37 		ns_fds[ns_total] = fd;
38 		tst_res(TINFO, "ns_name=%s, ns_fds[%d]=%d, ns_types[%d]=0x%x",
39 			 proc_name, ns_total, fd, ns_total, clone_type);
40 		ns_total++;
41 	}
42 }
43 
init_available_ns(void)44 static void init_available_ns(void)
45 {
46 	init_ns_type(CLONE_NEWIPC, "ipc");
47 	init_ns_type(CLONE_NEWNS, "mnt");
48 	init_ns_type(CLONE_NEWNET, "net");
49 	init_ns_type(CLONE_NEWPID, "pid");
50 	init_ns_type(CLONE_NEWUTS, "uts");
51 }
52 
close_ns_fds(void)53 static void close_ns_fds(void)
54 {
55 	int i;
56 
57 	for (i = 0; i < ns_total; i++)
58 		if (ns_fds[i] != -1)
59 			SAFE_CLOSE(ns_fds[i]);
60 }
61