| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <linux/filter.h> |
| 4 |
#include <linux/if_ether.h> |
| 5 |
|
| 6 |
#include "fd-util.h" |
| 7 |
#include "lldp-network.h" |
| 8 |
#include "socket-util.h" |
| 9 |
|
| 10 |
int lldp_network_bind_raw_socket(int ifindex) { |
| 11 |
static const struct sock_filter filter[] = { |
| 12 |
BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct ethhdr, h_dest)), /* A <- 4 bytes of destination MAC */ |
| 13 |
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0180c200, 1, 0), /* A != 01:80:c2:00 */ |
| 14 |
BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */ |
| 15 |
BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(struct ethhdr, h_dest) + 4), /* A <- remaining 2 bytes of destination MAC */ |
| 16 |
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0000, 3, 0), /* A != 00:00 */ |
| 17 |
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0003, 2, 0), /* A != 00:03 */ |
| 18 |
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x000e, 1, 0), /* A != 00:0e */ |
| 19 |
BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */ |
| 20 |
BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(struct ethhdr, h_proto)), /* A <- protocol */ |
| 21 |
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETH_P_LLDP, 1, 0), /* A != ETH_P_LLDP */ |
| 22 |
BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */ |
| 23 |
BPF_STMT(BPF_RET + BPF_K, UINT32_MAX), /* accept packet */ |
| 24 |
}; |
| 25 |
static const struct sock_fprog fprog = { |
| 26 |
.len = ELEMENTSOF(filter), |
| 27 |
.filter = (struct sock_filter*) filter, |
| 28 |
}; |
| 29 |
struct packet_mreq mreq = { |
| 30 |
.mr_ifindex = ifindex, |
| 31 |
.mr_type = PACKET_MR_MULTICAST, |
| 32 |
.mr_alen = ETH_ALEN, |
| 33 |
.mr_address = { 0x01, 0x80, 0xC2, 0x00, 0x00, 0x00 } |
| 34 |
}; |
| 35 |
union sockaddr_union saddrll = { |
| 36 |
.ll.sll_family = AF_PACKET, |
| 37 |
.ll.sll_ifindex = ifindex, |
| 38 |
}; |
| 39 |
_cleanup_close_ int fd = -EBADF; |
| 40 |
|
| 41 |
assert(ifindex > 0); |
| 42 |
|
| 43 |
fd = socket(AF_PACKET, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, |
| 44 |
htobe16(ETH_P_LLDP)); |
| 45 |
if (fd < 0) |
| 46 |
return -errno; |
| 47 |
|
| 48 |
if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &fprog, sizeof(fprog)) < 0) |
| 49 |
return -errno; |
| 50 |
|
| 51 |
/* customer bridge */ |
| 52 |
if (setsockopt(fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) |
| 53 |
return -errno; |
| 54 |
|
| 55 |
/* non TPMR bridge */ |
| 56 |
mreq.mr_address[ETH_ALEN - 1] = 0x03; |
| 57 |
if (setsockopt(fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) |
| 58 |
return -errno; |
| 59 |
|
| 60 |
/* nearest bridge */ |
| 61 |
mreq.mr_address[ETH_ALEN - 1] = 0x0E; |
| 62 |
if (setsockopt(fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) |
| 63 |
return -errno; |
| 64 |
|
| 65 |
if (bind(fd, &saddrll.sa, sizeof(saddrll.ll)) < 0) |
| 66 |
return -errno; |
| 67 |
|
| 68 |
return TAKE_FD(fd); |
| 69 |
} |