]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd-network/lldp-network.c
Merge pull request #2959 from keszybz/stop-resolving-localdomain
[thirdparty/systemd.git] / src / libsystemd-network / lldp-network.c
1 /***
2 This file is part of systemd.
3
4 Copyright (C) 2014 Tom Gundersen
5 Copyright (C) 2014 Susant Sahani
6
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #include <linux/filter.h>
22 #include <netinet/if_ether.h>
23
24 #include "fd-util.h"
25 #include "lldp-network.h"
26 #include "socket-util.h"
27
28 int lldp_network_bind_raw_socket(int ifindex) {
29
30 static const struct sock_filter filter[] = {
31 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct ethhdr, h_dest)), /* A <- 4 bytes of destination MAC */
32 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0180c200, 1, 0), /* A != 01:80:c2:00 */
33 BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */
34 BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(struct ethhdr, h_dest) + 4), /* A <- remaining 2 bytes of destination MAC */
35 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0000, 3, 0), /* A != 00:00 */
36 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0003, 2, 0), /* A != 00:03 */
37 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x000e, 1, 0), /* A != 00:0e */
38 BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */
39 BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(struct ethhdr, h_proto)), /* A <- protocol */
40 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_LLDP, 1, 0), /* A != ETHERTYPE_LLDP */
41 BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */
42 BPF_STMT(BPF_RET + BPF_K, (uint32_t) -1), /* accept packet */
43 };
44
45 static const struct sock_fprog fprog = {
46 .len = ELEMENTSOF(filter),
47 .filter = (struct sock_filter*) filter,
48 };
49
50 union sockaddr_union saddrll = {
51 .ll.sll_family = AF_PACKET,
52 .ll.sll_ifindex = ifindex,
53 };
54
55 _cleanup_close_ int fd = -1;
56 int r;
57
58 assert(ifindex > 0);
59
60 fd = socket(PF_PACKET, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, htons(ETHERTYPE_LLDP));
61 if (fd < 0)
62 return -errno;
63
64 r = setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &fprog, sizeof(fprog));
65 if (r < 0)
66 return -errno;
67
68 r = bind(fd, &saddrll.sa, sizeof(saddrll.ll));
69 if (r < 0)
70 return -errno;
71
72 r = fd;
73 fd = -1;
74
75 return r;
76 }