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