Skip to content

Commit aa72511

Browse files
committed
refactor: remove global ifindex variable
1 parent dcd1af3 commit aa72511

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

mem.c

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ int read_kernel_memory_xdp_fd;
4444
struct mem_ebpf *mem_ebpf_skel;
4545

4646
/* XDP attachment and network trigger resources */
47-
int ifindex = -1;
4847
int raw_sockfd = -1;
4948
struct bpf_link *bpf_prog_link = NULL;
5049
const char *loopback_interface = "lo";
@@ -156,7 +155,7 @@ static int init_mmap() {
156155
* and binds it to loopback interface.
157156
* Returns 0 on success, negative errno value on failure.
158157
*/
159-
static int init_raw_socket(void) {
158+
static int init_raw_socket(int ifindex) {
160159
struct sockaddr_ll sll;
161160

162161
/* Create raw socket */
@@ -225,15 +224,15 @@ int load_ebpf_mem_progs() {
225224
/* Attach the uprobe to the 'read_kernel_memory' function in the current executable */
226225
bpf_prog_link = bpf_program__attach(mem_ebpf_skel->progs.read_kernel_memory_uprobe);
227226
if (!bpf_prog_link) {
228-
fprintf(stderr, "Failed to attach eBPF Uprobe program, use XDP fallback one...\n");
227+
fprintf(stderr, "Failed to attach eBPF Uprobe program, use XDP fallback...\n");
229228

230229
/* Check if can create raw sockets for XDP */
231230
if (check_capability(CAP_NET_RAW) <= 0) {
232231
WARN("LEMON does not have CAP_NET_RAW to create raw sockets for XDP");
233232
}
234233

235234
/* Get loopback interface index by name "lo" (usually 1) */
236-
ifindex = if_nametoindex(loopback_interface);
235+
int ifindex = if_nametoindex(loopback_interface);
237236
if (ifindex <= 0) {
238237
perror("Failed to get interface index");
239238
return -errno;
@@ -246,7 +245,7 @@ int load_ebpf_mem_progs() {
246245
}
247246

248247
/* Create socket for sending trigger packets */
249-
if ((ret = init_raw_socket())) {
248+
if ((ret = init_raw_socket(ifindex))) {
250249
return ret;
251250
}
252251
}
@@ -309,9 +308,12 @@ uintptr_t phys_to_virt(const uintptr_t phy_addr) {
309308
* Returns 0 on success, negative errno value on failure.
310309
*/
311310
static int send_xdp_trigger_packet(const uintptr_t addr, const size_t size) {
311+
int ifindex;
312+
ssize_t sent_bytes;
312313
struct trigger_frame frame;
313314
struct sockaddr_ll dest_addr;
314-
ssize_t sent_bytes;
315+
316+
ifindex = if_nametoindex(loopback_interface);
315317

316318
/* Initialize frame structure */
317319
memset(&frame, 0, sizeof(frame));

0 commit comments

Comments
 (0)