aboutsummaryrefslogtreecommitdiffstats
path: root/src/vnet/lldp/lldp_input.c
blob: e88f6fdba5f0bb211d8aa81cf3f838ad29b974c6 (plain)
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
 * Copyright (c) 2011-2016 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @file
 * @brief LLDP packet parsing implementation
 */
#include <vnet/lldp/lldp_node.h>
#include <vnet/lldp/lldp_protocol.h>
#include <vlibmemory/api.h>

typedef struct
{
  u32 hw_if_index;
  u8 chassis_id_len;
  u8 chassis_id_subtype;
  u8 portid_len;
  u8 portid_subtype;
  u16 ttl;
  u8 data[0];			/* this contains both chassis id (chassis_id_len bytes) and port
				   id (portid_len bytes) */
} lldp_intf_update_t;

static void
lldp_rpc_update_peer_cb (const lldp_intf_update_t * a)
{
  ASSERT (vlib_get_thread_index () == 0);

  lldp_intf_t *n = lldp_get_intf (&lldp_main, a->hw_if_index);
  if (!n)
    {
      /* LLDP turned off for this interface, ignore the update */
      return;
    }
  const u8 *chassis_id = a->data;
  const u8 *portid = a->data + a->chassis_id_len;

  if (n->chassis_id)
    {
      _vec_len (n->chassis_id) = 0;
    }
  vec_add (n->chassis_id, chassis_id, a->chassis_id_len);
  n->chassis_id_subtype = a->chassis_id_subtype;
  if (n->port_id)
    {
      _vec_len (n->port_id) = 0;
    }
  vec_add (n->port_id, portid, a->portid_len);
  n->port_id_subtype = a->portid_subtype;
  n->ttl = a->ttl;
  n->last_heard = vlib_time_now (lldp_main.vlib_main);
}

static void
lldp_rpc_update_peer (u32 hw_if_index, const u8 * chid, u8 chid_len,
		      u8 chid_subtype, const u8 * portid,
		      u8 portid_len, u8 portid_subtype, u16 ttl)
{
  const size_t data_size =
    sizeof (lldp_intf_update_t) + chid_len + portid_len;
  u8 data[data_size];
  lldp_intf_update_t *u = (lldp_intf_update_t *) data;
  u->hw_if_index = hw_if_index;
  u->chassis_id_len = chid_len;
  u->chassis_id_subtype = chid_subtype;
  u->ttl = ttl;
  u->portid_len = portid_len;
  u->portid_subtype = portid_subtype;
  clib_memcpy (u->data, chid, chid_len);
  clib_memcpy (u->data + chid_len, portid, portid_len);
  vl_api_rpc_call_main_thread (lldp_rpc_update_peer_cb, data, data_size);
}

lldp_tlv_code_t
lldp_tlv_get_code (const lldp_tlv_t * tlv)
{
  return tlv->head.byte1 >> 1;
}

void
lldp_tlv_set_code (lldp_tlv_t * tlv, lldp_tlv_code_t code)
{
  tlv->head.byte1 = (tlv->head.byte1 & 1) + (code << 1);
}

u16
lldp_tlv_get_length (const lldp_tlv_t * tlv)
{
  return (((u16) (tlv->head.byte1 & 1)) << 8) + tlv->head.byte2;
}

void
lldp_tlv_set_length (lldp_tlv_t * tlv, u16 length)
{
  tlv->head.byte2 = length & ((1 << 8) - 1);
  if (length > (1 << 8) - 1)
    {
      tlv->head.byte1 |= 1;
    }
  else
    {
      tlv->head.byte1 &= (1 << 8) - 2;
    }
}

lldp_main_t lldp_main;

static int
lldp_packet_scan (u32 hw_if_index, const lldp_tlv_t * pkt)
{
  const lldp_tlv_t *tlv = pkt;

#define TLV_VIOLATES_PKT_BOUNDARY(pkt, tlv)                               \
  (((((u8 *)tlv) + sizeof (lldp_tlv_t)) > ((u8 *)pkt + vec_len (pkt))) || \
   ((((u8 *)tlv) + lldp_tlv_get_length (tlv)) > ((u8 *)pkt + vec_len (pkt))))

  /* first tlv is always chassis id, followed by port id and ttl tlvs */
  if (TLV_VIOLATES_PKT_BOUNDARY (pkt, tlv) ||
      LLDP_TLV_NAME (chassis_id) != lldp_tlv_get_code (tlv))
    {
      return LLDP_ERROR_BAD_TLV;
    }

  u16 l = lldp_tlv_get_length (tlv);
  if (l < STRUCT_SIZE_OF (lldp_chassis_id_tlv_t, subtype) +
      LLDP_MIN_CHASS_ID_LEN ||
      l > STRUCT_SIZE_OF (lldp_chassis_id_tlv_t, subtype) +
      LLDP_MAX_CHASS_ID_LEN)
    {
      return LLDP_ERROR_BAD_TLV;
    }

  u8 chid_subtype = ((lldp_chassis_id_tlv_t *) tlv)->subtype;
  u8 *chid = ((lldp_chassis_id_tlv_t *) tlv)->id;
  u8 chid_len = l - STRUCT_SIZE_OF (lldp_chassis_id_tlv_t, subtype);

  tlv = (lldp_tlv_t *) ((u8 *) tlv + STRUCT_SIZE_OF (lldp_tlv_t, head) + l);

  if (TLV_VIOLATES_PKT_BOUNDARY (pkt, tlv) ||
      LLDP_TLV_NAME (port_id) != lldp_tlv_get_code (tlv))
    {
      return LLDP_ERROR_BAD_TLV;
    }
  l = lldp_tlv_get_length (tlv);
  if (l < STRUCT_SIZE_OF (lldp_port_id_tlv_t, subtype) +
      LLDP_MIN_PORT_ID_LEN ||
      l > STRUCT_SIZE_OF (lldp_chassis_id_tlv_t, subtype) +
      LLDP_MAX_PORT_ID_LEN)
    {
      return LLDP_ERROR_BAD_TLV;
    }

  u8 portid_subtype = ((lldp_port_id_tlv_t *) tlv)->subtype;
  u8 *portid = ((lldp_port_id_tlv_t *) tlv)->id;
  u8 portid_len = l - STRUCT_SIZE_OF (lldp_port_id_tlv_t, subtype);

  tlv = (lldp_tlv_t *) ((u8 *) tlv + STRUCT_SIZE_OF (lldp_tlv_t, head) + l);

  if (TLV_VIOLATES_PKT_BOUNDARY (pkt, tlv) ||
      LLDP_TLV_NAME (ttl) != lldp_tlv_get_code (tlv))
    {
      return LLDP_ERROR_BAD_TLV;
    }
  l = lldp_tlv_get_length (tlv);
  if (l != STRUCT_SIZE_OF (lldp_ttl_tlv_t, ttl))
    {
      return LLDP_ERROR_BAD_TLV;
    }
  u16 ttl = ntohs (((lldp_ttl_tlv_t *) tlv)->ttl);
  tlv = (lldp_tlv_t *) ((u8 *) tlv + STRUCT_SIZE_OF (lldp_tlv_t, head) + l);
  while (!TLV_VIOLATES_PKT_BOUNDARY (pkt, tlv) &&
	 LLDP_TLV_NAME (pdu_end) != lldp_tlv_get_code (tlv))
    {
      switch (lldp_tlv_get_code (tlv))
	{
#define F(num, type, str)     \
  case LLDP_TLV_NAME (type):  \
    /* ignore optional TLV */ \
    break;
	  foreach_lldp_optional_tlv_type (F);
#undef F
	default:
	  return LLDP_ERROR_BAD_TLV;
	}
      tlv = (lldp_tlv_t *) ((u8 *) tlv + STRUCT_SIZE_OF (lldp_tlv_t, head) +
			    lldp_tlv_get_length (tlv));
    }
  /* last tlv is pdu_end */
  if (TLV_VIOLATES_PKT_BOUNDARY (pkt, tlv) ||
      LLDP_TLV_NAME (pdu_end) != lldp_tlv_get_code (tlv) ||
      0 != lldp_tlv_get_length (tlv))
    {
      return LLDP_ERROR_BAD_TLV;
    }
  lldp_rpc_update_peer (hw_if_index, chid, chid_len, chid_subtype, portid,
			portid_len, portid_subtype, ttl);
  return LLDP_ERROR_NONE;
}

lldp_intf_t *
lldp_get_intf (lldp_main_t * lm, u32 hw_if_index)
{
  uword *p = hash_get (lm->intf_by_hw_if_index, hw_if_index);

  if (p)
    {
      return pool_elt_at_index (lm->intfs, p[0]);
    }
  return NULL;
}

lldp_intf_t *
lldp_create_intf (lldp_main_t * lm, u32 hw_if_index)
{

  uword *p;
  lldp_intf_t *n;
  p = hash_get (lm->intf_by_hw_if_index, hw_if_index);

  if (p == 0)
    {
      pool_get (lm->intfs, n);
      memset (n, 0, sizeof (*n));
      n->hw_if_index = hw_if_index;
      hash_set (lm->intf_by_hw_if_index, n->hw_if_index, n - lm->intfs);
    }
  else
    {
      n = pool_elt_at_index (lm->intfs, p[0]);
    }
  return n;
}

/*
 * lldp input routine
 */
lldp_error_t
lldp_input (vlib_main_t * vm, vlib_buffer_t * b0, u32 bi0)
{
  lldp_main_t *lm = &lldp_main;
  lldp_error_t e;

  /* find our interface */
  vnet_sw_interface_t *sw_interface = vnet_get_sw_interface (lm->vnet_main,
							     vnet_buffer
							     (b0)->sw_if_index
							     [VLIB_RX]);
  lldp_intf_t *n = lldp_get_intf (lm, sw_interface->hw_if_index);

  if (!n)
    {
      /* lldp disabled on this interface, we're done */
      return LLDP_ERROR_DISABLED;
    }

  /* Actually scan the packet */
  e = lldp_packet_scan (sw_interface->hw_if_index,
			vlib_buffer_get_current (b0));

  return e;
}

/*
 * setup function
 */
static clib_error_t *
lldp_init (vlib_main_t * vm)
{
  clib_error_t *error;
  lldp_main_t *lm = &lldp_main;

  if ((error = vlib_call_init_function (vm, lldp_template_init)))
    return error;

  lm->vlib_main = vm;
  lm->vnet_main = vnet_get_main ();
  lm->msg_tx_hold = 4;		/* default value per IEEE 802.1AB-2009 */
  lm->msg_tx_interval = 30;	/* default value per IEEE 802.1AB-2009 */

  return 0;
}

VLIB_INIT_FUNCTION (lldp_init);

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
pan class="n">remaining_time > 0: before = time.time() capture = self._get_capture(remaining_time, filter_out_fn) elapsed_time = time.time() - before if capture: if len(capture.res) == expected_count: # bingo, got the packets we expected return capture elif len(capture.res) > expected_count: self.test.logger.error( ppc("Unexpected packets captured:", capture)) break else: self.test.logger.debug("Partial capture containing %s " "packets doesn't match expected " "count %s (yet?)" % (len(capture.res), expected_count)) elif expected_count == 0: # bingo, got None as we expected - return empty capture return PacketList() remaining_time -= elapsed_time if capture: self.generate_debug_aid("count-mismatch") raise Exception("Captured packets mismatch, captured %s packets, " "expected %s packets on %s" % (len(capture.res), expected_count, name)) else: raise Exception("No packets captured on %s" % name) def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc): """ Assert that nothing unfiltered was captured on interface :param remark: remark printed into debug logs :param filter_out_fn: filter applied to each packet, packets for which the filter returns True are removed from capture """ if os.path.isfile(self.out_path): try: capture = self.get_capture( 0, remark=remark, filter_out_fn=filter_out_fn) if not capture or len(capture.res) == 0: # junk filtered out, we're good return except: pass self.generate_debug_aid("empty-assert") if remark: raise AssertionError( "Non-empty capture file present for interface %s (%s)" % (self.name, remark)) else: raise AssertionError("Capture file present for interface %s" % self.name) def wait_for_capture_file(self, timeout=1): """ Wait until pcap capture file appears :param timeout: How long to wait for the packet (default 1s) :returns: True/False if the file is present or appears within timeout """ deadline = time.time() + timeout if not os.path.isfile(self.out_path): self.test.logger.debug("Waiting for capture file %s to appear, " "timeout is %ss" % (self.out_path, timeout)) else: self.test.logger.debug("Capture file %s already exists" % self.out_path) return True while time.time() < deadline: if os.path.isfile(self.out_path): break time.sleep(0) # yield if os.path.isfile(self.out_path): self.test.logger.debug("Capture file appeared after %fs" % (time.time() - (deadline - timeout))) else: self.test.logger.debug("Timeout - capture file still nowhere") return False return True def verify_enough_packet_data_in_pcap(self): """ Check if enough data is available in file handled by internal pcap reader so that a whole packet can be read. :returns: True if enough data present, else False """ orig_pos = self._pcap_reader.f.tell() # save file position enough_data = False # read packet header from pcap packet_header_size = 16 caplen = None end_pos = None hdr = self._pcap_reader.f.read(packet_header_size) if len(hdr) == packet_header_size: # parse the capture length - caplen sec, usec, caplen, wirelen = struct.unpack( self._pcap_reader.endian + "IIII", hdr) self._pcap_reader.f.seek(0, 2) # seek to end of file end_pos = self._pcap_reader.f.tell() # get position at end if end_pos >= orig_pos + len(hdr) + caplen: enough_data = True # yay, we have enough data self._pcap_reader.f.seek(orig_pos, 0) # restore original position return enough_data def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc): """ Wait for next packet captured with a timeout :param timeout: How long to wait for the packet :returns: Captured packet if no packet arrived within timeout :raises Exception: if no packet arrives within timeout """ deadline = time.time() + timeout if self._pcap_reader is None: if not self.wait_for_capture_file(timeout): raise CaptureTimeoutError("Capture file %s did not appear " "within timeout" % self.out_path) while time.time() < deadline: try: self._pcap_reader = PcapReader(self.out_path) break except: self.test.logger.debug( "Exception in scapy.PcapReader(%s): %s" % (self.out_path, format_exc())) if not self._pcap_reader: raise CaptureTimeoutError("Capture file %s did not appear within " "timeout" % self.out_path) poll = False if timeout > 0: self.test.logger.debug("Waiting for packet") else: poll = True self.test.logger.debug("Polling for packet") while time.time() < deadline or poll: if not self.verify_enough_packet_data_in_pcap(): time.sleep(0) # yield poll = False continue p = self._pcap_reader.recv() if p is not None: if filter_out_fn is not None and filter_out_fn(p): self.test.logger.debug( "Packet received after %ss was filtered out" % (time.time() - (deadline - timeout))) else: self.test.logger.debug( "Packet received after %fs" % (time.time() - (deadline - timeout))) return p time.sleep(0) # yield poll = False self.test.logger.debug("Timeout - no packets received") raise CaptureTimeoutError("Packet didn't arrive within timeout") def create_arp_req(self): """Create ARP request applicable for this interface""" return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) / ARP(op=ARP.who_has, pdst=self.local_ip4, psrc=self.remote_ip4, hwsrc=self.remote_mac)) def create_ndp_req(self): """Create NDP - NS applicable for this interface""" nsma = in6_getnsma(inet_pton(socket.AF_INET6, self.local_ip6)) d = inet_ntop(socket.AF_INET6, nsma) return (Ether(dst=in6_getnsmac(nsma)) / IPv6(dst=d, src=self.remote_ip6) / ICMPv6ND_NS(tgt=self.local_ip6) / ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac)) def resolve_arp(self, pg_interface=None): """Resolve ARP using provided packet-generator interface :param pg_interface: interface used to resolve, if None then this interface is used """ if pg_interface is None: pg_interface = self self.test.logger.info("Sending ARP request for %s on port %s" % (self.local_ip4, pg_interface.name)) arp_req = self.create_arp_req() pg_interface.add_stream(arp_req) pg_interface.enable_capture() self.test.pg_start() self.test.logger.info(self.test.vapi.cli("show trace")) try: captured_packet = pg_interface.wait_for_packet(1) except: self.test.logger.info("No ARP received on port %s" % pg_interface.name) return arp_reply = captured_packet.copy() # keep original for exception # Make Dot1AD packet content recognizable to scapy if arp_reply.type == 0x88a8: arp_reply.type = 0x8100 arp_reply = Ether(str(arp_reply)) try: if arp_reply[ARP].op == ARP.is_at: self.test.logger.info("VPP %s MAC address is %s " % (self.name, arp_reply[ARP].hwsrc)) self._local_mac = arp_reply[ARP].hwsrc else: self.test.logger.info("No ARP received on port %s" % pg_interface.name) except: self.test.logger.error( ppp("Unexpected response to ARP request:", captured_packet)) raise def resolve_ndp(self, pg_interface=None, timeout=1): """Resolve NDP using provided packet-generator interface :param pg_interface: interface used to resolve, if None then this interface is used :param timeout: how long to wait for response before giving up """ if pg_interface is None: pg_interface = self self.test.logger.info("Sending NDP request for %s on port %s" % (self.local_ip6, pg_interface.name)) ndp_req = self.create_ndp_req() pg_interface.add_stream(ndp_req) pg_interface.enable_capture() self.test.pg_start() now = time.time() deadline = now + timeout # Enabling IPv6 on an interface can generate more than the # ND reply we are looking for (namely MLD). So loop through # the replies to look for want we want. while now < deadline: try: captured_packet = pg_interface.wait_for_packet( deadline - now, filter_out_fn=None) except: self.test.logger.error( "Timeout while waiting for NDP response") raise ndp_reply = captured_packet.copy() # keep original for exception # Make Dot1AD packet content recognizable to scapy if ndp_reply.type == 0x88a8: ndp_reply.type = 0x8100 ndp_reply = Ether(str(ndp_reply)) try: ndp_na = ndp_reply[ICMPv6ND_NA] opt = ndp_na[ICMPv6NDOptDstLLAddr] self.test.logger.info("VPP %s MAC address is %s " % (self.name, opt.lladdr)) self._local_mac = opt.lladdr self.test.logger.debug(self.test.vapi.cli("show trace")) # we now have the MAC we've been after return except: self.test.logger.info( ppp("Unexpected response to NDP request:", captured_packet)) now = time.time() self.test.logger.debug(self.test.vapi.cli("show trace")) raise Exception("Timeout while waiting for NDP response")