]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/libsystemd-network/lldp-network.c
Merge pull request #2495 from heftig/master
[thirdparty/systemd.git] / src / libsystemd-network / lldp-network.c
CommitLineData
ad1ad5c8
SS
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 <linux/if_ether.h>
23
3ffd4af2 24#include "fd-util.h"
7a6f1457 25#include "lldp-internal.h"
3ffd4af2
LP
26#include "lldp-network.h"
27#include "lldp-tlv.h"
28#include "socket-util.h"
ad1ad5c8
SS
29
30int lldp_network_bind_raw_socket(int ifindex) {
31 typedef struct LLDPFrame {
32 struct ethhdr hdr;
33 uint8_t tlvs[0];
34 } LLDPFrame;
35
36 struct sock_filter filter[] = {
37 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(LLDPFrame, hdr.h_dest)), /* A <- 4 bytes of destination MAC */
38 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0180c200, 1, 0), /* A != 01:80:c2:00 */
39 BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */
40 BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(LLDPFrame, hdr.h_dest) + 4), /* A <- remaining 2 bytes of destination MAC */
41 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0000, 3, 0), /* A != 00:00 */
42 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0003, 2, 0), /* A != 00:03 */
43 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x000e, 1, 0), /* A != 00:0e */
44 BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */
45 BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(LLDPFrame, hdr.h_proto)), /* A <- protocol */
46 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_LLDP, 1, 0), /* A != ETHERTYPE_LLDP */
47 BPF_STMT(BPF_RET + BPF_K, 0), /* drop packet */
48 BPF_STMT(BPF_RET + BPF_K, (uint32_t) -1), /* accept packet */
49 };
50
51 struct sock_fprog fprog = {
52 .len = ELEMENTSOF(filter),
53 .filter = filter
54 };
55
56 _cleanup_close_ int s = -1;
57
58 union sockaddr_union saddrll = {
59 .ll.sll_family = AF_PACKET,
60 .ll.sll_ifindex = ifindex,
61 };
62
63 int r;
64
65 assert(ifindex > 0);
66
67 s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
68 if (s < 0)
69 return -errno;
70
71 r = setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER, &fprog, sizeof(fprog));
72 if (r < 0)
73 return -errno;
74
75 r = bind(s, &saddrll.sa, sizeof(saddrll.ll));
76 if (r < 0)
77 return -errno;
78
79 r = s;
80 s = -1;
81
82 return r;
83}