-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclose_range.c
94 lines (74 loc) · 1.79 KB
/
close_range.c
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
/*
* Copyright 2023-2024 Gaël PORTAY
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <unistd.h>
#include "iamroot.h"
static int (*sym)(unsigned int, unsigned int, int);
hidden int next_close_range(unsigned int first, unsigned int last, int flags)
{
if (!sym)
sym = dlsym(RTLD_NEXT, "close_range");
if (!sym)
return __dl_set_errno_and_perror(ENOSYS, -1);
return sym(first, last, flags);
}
#ifdef __linux__
struct __close_range {
int first;
int last;
char buf[PATH_MAX];
};
static int __callback(const char *path, const char *filename, void *user)
{
struct __close_range *data = (struct __close_range *)user;
int fd;
(void)path;
if (!user)
return __set_errno(EINVAL, -1);
fd = __strtofd(filename, NULL);
if (fd == -1)
return -1;
if (fd < data->first || fd > data->last)
return 0;
if (*data->buf)
__strncat(data->buf, ", ");
__strncat(data->buf, filename);
__info("%s: %i -> '%s'\n", "close_range", fd, __fpath(fd));
return 0;
}
#endif
int close_range(unsigned int first, unsigned int last, int flags)
{
#ifdef __linux__
struct __close_range data = {
.first = first,
.last = last,
.buf = { 0 },
};
int err, ret;
err = __dir_iterate("/proc/self/fd", __callback, &data);
if (err == -1)
__strncpy(data.buf, "(error)");
#else
int ret;
#endif
ret = next_close_range(first, last, flags);
#ifdef __linux__
__debug("%s(first: %u <-> '%s', last: %u <-> '%s', flags: 0x%x) -> %i, fds: { %s }\n",
__func__, first, __fpath(first), last, __fpath2(last), flags,
ret, data.buf);
#else
__debug("%s(first: %u <-> '%s', last: %u <-> '%s', flags: 0x%x) -> %i\n",
__func__, first, __fpath(first), last, __fpath2(last), flags,
ret);
#endif
return ret;
}