1
0
mirror of https://passt.top/passt synced 2024-09-28 10:05:47 +00:00

util: Add open_in_ns() helper

Most of our helpers which need to enter the pasta network namespace are
quite specialised.  Add one which is rather general - it just open()s a
given file in the namespace context and returns the fd back to the main
namespace.  This will have some future uses.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Signed-off-by: Stefano Brivio <sbrivio@redhat.com>
This commit is contained in:
David Gibson 2023-11-03 13:22:58 +11:00 committed by Stefano Brivio
parent 17d40d1cb5
commit 4f0b9f91e4
2 changed files with 54 additions and 0 deletions

53
util.c
View File

@ -364,6 +364,59 @@ bool ns_is_init(void)
return ret; return ret;
} }
/**
* struct open_in_ns_args - Parameters for do_open_in_ns()
* @c: Execution context
* @fd: Filled in with return value from open()
* @err: Filled in with errno if open() failed
* @path: Path to open
* @flags: open() flags
*/
struct open_in_ns_args {
const struct ctx *c;
int fd;
int err;
const char *path;
int flags;
};
/**
* do_open_in_ns() - Enter namespace and open a file
* @arg: See struct open_in_ns_args
*
* Must be called via NS_CALL()
*/
static int do_open_in_ns(void *arg)
{
struct open_in_ns_args *a = (struct open_in_ns_args *)arg;
ns_enter(a->c);
a->fd = open(a->path, a->flags);
a->err = errno;
return 0;
}
/**
* open_in_ns() - open() within the pasta namespace
* @c: Execution context
* @path: Path to open
* @flags: open() flags
*
* Return: fd of open()ed file or -1 on error, errno is set to indicate error
*/
int open_in_ns(const struct ctx *c, const char *path, int flags)
{
struct open_in_ns_args arg = {
.c = c, .path = path, .flags = flags,
};
NS_CALL(do_open_in_ns, &arg);
errno = arg.err;
return arg.fd;
}
/** /**
* pid_file() - Write PID to file, if requested to do so, and close it * pid_file() - Write PID to file, if requested to do so, and close it
* @fd: Open PID file descriptor, closed on exit, -1 to skip writing it * @fd: Open PID file descriptor, closed on exit, -1 to skip writing it

1
util.h
View File

@ -219,6 +219,7 @@ int bitmap_isset(const uint8_t *map, int bit);
char *line_read(char *buf, size_t len, int fd); char *line_read(char *buf, size_t len, int fd);
void ns_enter(const struct ctx *c); void ns_enter(const struct ctx *c);
bool ns_is_init(void); bool ns_is_init(void);
int open_in_ns(const struct ctx *c, const char *path, int flags);
void write_pidfile(int fd, pid_t pid); void write_pidfile(int fd, pid_t pid);
int __daemon(int pidfile_fd, int devnull_fd); int __daemon(int pidfile_fd, int devnull_fd);
int fls(unsigned long x); int fls(unsigned long x);