summaryrefslogtreecommitdiffstats
path: root/test/ipfix.py
blob: 97b559e083b1eb49befdd167f3c2aa4de32ed5a2 (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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
#!/usr/bin/env python
# IPFIX support for Scapy (RFC7011)

from scapy.all import *


# IPFIX Information Elements http://www.iana.org/assignments/ipfix/ipfix.xhtml
information_elements = {
    1:   "octetDeltaCount",
    2:   "packetDeltaCount",
    3:   "deltaFlowCount",
    4:   "protocolIdentifier",
    5:   "ipClassOfService",
    6:   "tcpControlBits",
    7:   "sourceTransportPort",
    8:   "sourceIPv4Address",
    9:   "sourceIPv4PrefixLength",
    10:  "ingressInterface",
    11:  "destinationTransportPort",
    12:  "destinationIPv4Address",
    13:  "destinationIPv4PrefixLength",
    14:  "egressInterface",
    15:  "ipNextHopIPv4Address",
    16:  "bgpSourceAsNumber",
    17:  "bgpDestinationAsNumber",
    18:  "bgpNextHopIPv4Address",
    19:  "postMCastPacketDeltaCount",
    20:  "postMCastOctetDeltaCount",
    21:  "flowEndSysUpTime",
    22:  "flowStartSysUpTime",
    23:  "postOctetDeltaCount",
    24:  "postPacketDeltaCount",
    25:  "minimumIpTotalLength",
    26:  "maximumIpTotalLength",
    27:  "sourceIPv6Address",
    28:  "destinationIPv6Address",
    29:  "sourceIPv6PrefixLength",
    30:  "destinationIPv6PrefixLength",
    31:  "flowLabelIPv6",
    32:  "icmpTypeCodeIPv4",
    33:  "igmpType",
    34:  "samplingInterval",
    35:  "samplingAlgorithm",
    36:  "flowActiveTimeout",
    37:  "flowIdleTimeout",
    38:  "engineType",
    39:  "engineId",
    40:  "exportedOctetTotalCount",
    41:  "exportedMessageTotalCount",
    42:  "exportedFlowRecordTotalCount",
    43:  "ipv4RouterSc",
    44:  "sourceIPv4Prefix",
    45:  "destinationIPv4Prefix",
    46:  "mplsTopLabelType",
    47:  "mplsTopLabelIPv4Address",
    48:  "samplerId",
    49:  "samplerMode",
    50:  "samplerRandomInterval",
    51:  "classId",
    52:  "minimumTTL",
    53:  "maximumTTL",
    54:  "fragmentIdentification",
    55:  "postIpClassOfService",
    56:  "sourceMacAddress",
    57:  "postDestinationMacAddress",
    58:  "vlanId",
    59:  "postVlanId",
    60:  "ipVersion",
    61:  "flowDirection",
    62:  "ipNextHopIPv6Address",
    63:  "bgpNextHopIPv6Address",
    64:  "ipv6ExtensionHeaders",
    70:  "mplsTopLabelStackSection",
    71:  "mplsLabelStackSection2",
    72:  "mplsLabelStackSection3",
    73:  "mplsLabelStackSection4",
    74:  "mplsLabelStackSection5",
    75:  "mplsLabelStackSection6",
    76:  "mplsLabelStackSection7",
    77:  "mplsLabelStackSection8",
    78:  "mplsLabelStackSection9",
    79:  "mplsLabelStackSection10",
    80:  "destinationMacAddress",
    81:  "postSourceMacAddress",
    82:  "interfaceName",
    83:  "interfaceDescription",
    84:  "samplerName",
    85:  "octetTotalCount",
    86:  "packetTotalCount",
    87:  "flagsAndSamplerId",
    88:  "fragmentOffset",
    89:  "forwardingStatus",
    90:  "mplsVpnRouteDistinguisher",
    91:  "mplsTopLabelPrefixLength",
    92:  "srcTrafficIndex",
    93:  "dstTrafficIndex",
    94:  "applicationDescription",
    95:  "applicationId",
    96:  "applicationName",
    98:  "postIpDiffServCodePoint",
    99:  "multicastReplicationFactor",
    100: "className",
    101: "classificationEngineId",
    102: "layer2packetSectionOffset",
    103: "layer2packetSectionSize",
    104: "layer2packetSectionData",
    128: "bgpNextAdjacentAsNumber",
    129: "bgpPrevAdjacentAsNumber",
    130: "exporterIPv4Address",
    131: "exporterIPv6Address",
    132: "droppedOctetDeltaCount",
    133: "droppedPacketDeltaCount",
    134: "droppedOctetTotalCount",
    135: "droppedPacketTotalCount",
    136: "flowEndReason",
    137: "commonPropertiesId",
    138: "observationPointId",
    139: "icmpTypeCodeIPv6",
    140: "mplsTopLabelIPv6Address",
    141: "lineCardId",
    142: "portId",
    143: "meteringProcessId",
    144: "exportingProcessId",
    145: "templateId",
    146: "wlanChannelId",
    147: "wlanSSID",
    148: "flowId",
    149: "observationDomainId",
    150: "flowStartSeconds",
    151: "flowEndSeconds",
    152: "flowStartMilliseconds",
    153: "flowEndMilliseconds",
    154: "flowStartMicroseconds",
    155: "flowEndMicroseconds",
    156: "flowStartNanoseconds",
    157: "flowEndNanoseconds",
    158: "flowStartDeltaMicroseconds",
    159: "flowEndDeltaMicroseconds",
    160: "systemInitTimeMilliseconds",
    161: "flowDurationMilliseconds",
    162: "flowDurationMicroseconds",
    163: "observedFlowTotalCount",
    164: "ignoredPacketTotalCount",
    165: "ignoredOctetTotalCount",
    166: "notSentFlowTotalCount",
    167: "notSentPacketTotalCount",
    168: "notSentOctetTotalCount",
    169: "destinationIPv6Prefix",
    170: "sourceIPv6Prefix",
    171: "postOctetTotalCount",
    172: "postPacketTotalCount",
    173: "flowKeyIndicator",
    174: "postMCastPacketTotalCount",
    175: "postMCastOctetTotalCount",
    176: "icmpTypeIPv4",
    177: "icmpCodeIPv4",
    178: "icmpTypeIPv6",
    179: "icmpCodeIPv6",
    180: "udpSourcePort",
    181: "udpDestinationPort",
    182: "tcpSourcePort",
    183: "tcpDestinationPort",
    184: "tcpSequenceNumber",
    185: "tcpAcknowledgementNumber",
    186: "tcpWindowSize",
    187: "tcpUrgentPointer",
    188: "tcpHeaderLength",
    189: "ipHeaderLength",
    190: "totalLengthIPv4",
    191: "payloadLengthIPv6",
    192: "ipTTL",
    193: "nextHeaderIPv6",
    194: "mplsPayloadLength",
    195: "ipDiffServCodePoint",
    196: "ipPrecedence",
    197: "fragmentFlags",
    198: "octetDeltaSumOfSquares",
    199: "octetTotalSumOfSquares",
    200: "mplsTopLabelTTL",
    201: "mplsLabelStackLength",
    202: "mplsLabelStackDepth",
    203: "mplsTopLabelExp",
    204: "ipPayloadLength",
    205: "udpMessageLength",
    206: "isMulticast",
    207: "ipv4IHL",
    208: "ipv4Options",
    209: "tcpOptions",
    210: "paddingOctets",
    211: "collectorIPv4Address",
    212: "collectorIPv6Address",
    213: "exportInterface",
    214: "exportProtocolVersion",
    215: "exportTransportProtocol",
    216: "collectorTransportPort",
    217: "exporterTransportPort",
    218: "tcpSynTotalCount",
    219: "tcpFinTotalCount",
    220: "tcpRstTotalCount",
    221: "tcpPshTotalCount",
    222: "tcpAckTotalCount",
    223: "tcpUrgTotalCount",
    224: "ipTotalLength",
    225: "postNATSourceIPv4Address",
    226: "postNATDestinationIPv4Address",
    227: "postNAPTSourceTransportPort",
    228: "postNAPTDestinationTransportPort",
    229: "natOriginatingAddressRealm",
    230: "natEvent",
    231: "initiatorOctets",
    232: "responderOctets",
    233: "firewallEvent",
    234: "ingressVRFID",
    235: "egressVRFID",
    236: "VRFname",
    237: "postMplsTopLabelExp",
    238: "tcpWindowScale",
    239: "biflowDirection",
    240: "ethernetHeaderLength",
    241: "ethernetPayloadLength",
    242: "ethernetTotalLength",
    243: "dot1qVlanId",
    244: "dot1qPriority",
    245: "dot1qCustomerVlanId",
    246: "dot1qCustomerPriority",
    247: "metroEvcId",
    248: "metroEvcType",
    249: "pseudoWireId",
    250: "pseudoWireType",
    251: "pseudoWireControlWord",
    252: "ingressPhysicalInterface",
    253: "egressPhysicalInterface",
    254: "postDot1qVlanId",
    255: "postDot1qCustomerVlanId",
    256: "ethernetType",
    257: "postIpPrecedence",
    258: "collectionTimeMilliseconds",
    259: "exportSctpStreamId",
    260: "maxExportSeconds",
    261: "maxFlowEndSeconds",
    262: "messageMD5Checksum",
    263: "messageScope",
    264: "minExportSeconds",
    265: "minFlowStartSeconds",
    266: "opaqueOctets",
    267: "sessionScope",
    268: "maxFlowEndMicroseconds",
    269: "maxFlowEndMilliseconds",
    270: "maxFlowEndNanoseconds",
    271: "minFlowStartMicroseconds",
    272: "minFlowStartMilliseconds",
    273: "minFlowStartNanoseconds",
    274: "collectorCertificate",
    275: "exporterCertificate",
    276: "dataRecordsReliability",
    277: "observationPointType",
    278: "newConnectionDeltaCount",
    279: "connectionSumDurationSeconds",
    280: "connectionTransactionId",
    281: "postNATSourceIPv6Address",
    282: "postNATDestinationIPv6Address",
    283: "natPoolId",
    284: "natPoolName",
    285: "anonymizationFlags",
    286: "anonymizationTechnique",
    287: "informationElementIndex",
    288: "p2pTechnology",
    289: "tunnelTechnology",
    290: "encryptedTechnology",
    291: "basicList",
    292: "subTemplateList",
    293: "subTemplateMultiList",
    294: "bgpValidityState",
    295: "IPSecSPI",
    296: "greKey",
    297: "natType",
    298: "initiatorPackets",
    299: "responderPackets",
    300: "observationDomainName",
    301: "selectionSequenceId",
    302: "selectorId",
    303: "informationElementId",
    304: "selectorAlgorithm",
    305: "samplingPacketInterval",
    306: "samplingPacketSpace",
    307: "samplingTimeInterval",
    308: "samplingTimeSpace",
    309: "samplingSize",
    310: "samplingPopulation",
    311: "samplingProbability",
    312: "dataLinkFrameSize",
    313: "ipHeaderPacketSection",
    314: "ipPayloadPacketSection",
    315: "dataLinkFrameSection",
    316: "mplsLabelStackSection",
    317: "mplsPayloadPacketSection",
    318: "selectorIdTotalPktsObserved",
    319: "selectorIdTotalPktsSelected",
    320: "absoluteError",
    321: "relativeError",
    322: "observationTimeSeconds",
    323: "observationTimeMilliseconds",
    324: "observationTimeMicroseconds",
    325: "observationTimeNanoseconds",
    326: "digestHashValue",
    327: "hashIPPayloadOffset",
    328: "hashIPPayloadSize",
    329: "hashOutputRangeMin",
    330: "hashOutputRangeMax",
    331: "hashSelectedRangeMin",
    332: "hashSelectedRangeMax",
    333: "hashDigestOutput",
    334: "hashInitialiserValue",
    335: "selectorName",
    336: "upperCILimit",
    337: "lowerCILimit",
    338: "confidenceLevel",
    339: "informationElementDataType",
    340: "informationElementDescription",
    341: "informationElementName",
    342: "informationElementRangeBegin",
    343: "informationElementRangeEnd",
    344: "informationElementSemantics",
    345: "informationElementUnits",
    346: "privateEnterpriseNumber",
    347: "virtualStationInterfaceId",
    348: "virtualStationInterfaceName",
    349: "virtualStationUUID",
    350: "virtualStationName",
    351: "layer2SegmentId",
    352: "layer2OctetDeltaCount",
    353: "layer2OctetTotalCount",
    354: "ingressUnicastPacketTotalCount",
    355: "ingressMulticastPacketTotalCount",
    356: "ingressBroadcastPacketTotalCount",
    357: "egressUnicastPacketTotalCount",
    358: "egressBroadcastPacketTotalCount",
    359: "monitoringIntervalStartMilliSeconds",
    360: "monitoringIntervalEndMilliSeconds",
    361: "portRangeStart",
    362: "portRangeEnd",
    363: "portRangeStepSize",
    364: "portRangeNumPorts",
    365: "staMacAddress",
    366: "staIPv4Address",
    367: "wtpMacAddress",
    368: "ingressInterfaceType",
    369: "egressInterfaceType",
    370: "rtpSequenceNumber",
    371: "userName",
    372: "applicationCategoryName",
    373: "applicationSubCategoryName",
    374: "applicationGroupName",
    375: "originalFlowsPresent",
    376: "originalFlowsInitiated",
    377: "originalFlowsCompleted",
    378: "distinctCountOfSourceIPAddress",
    379: "distinctCountOfDestinationIPAddress",
    380: "distinctCountOfSourceIPv4Address",
    381: "distinctCountOfDestinationIPv4Address",
    382: "distinctCountOfSourceIPv6Address",
    383: "distinctCountOfDestinationIPv6Address",
    384: "valueDistributionMethod",
    385: "rfc3550JitterMilliseconds",
    386: "rfc3550JitterMicroseconds",
    387: "rfc3550JitterNanoseconds",
    388: "dot1qDEI",
    389: "dot1qCustomerDEI",
    390: "flowSelectorAlgorithm",
    391: "flowSelectedOctetDeltaCount",
    392: "flowSelectedPacketDeltaCount",
    393: "flowSelectedFlowDeltaCount",
    394: "selectorIDTotalFlowsObserved",
    395: "selectorIDTotalFlowsSelected",
    396: "samplingFlowInterval",
    397: "samplingFlowSpacing",
    398: "flowSamplingTimeInterval",
    399: "flowSamplingTimeSpacing",
    400: "hashFlowDomain",
    401: "transportOctetDeltaCount",
    402: "transportPacketDeltaCount",
    403: "originalExporterIPv4Address",
    404: "originalExporterIPv6Address",
    405: "originalObservationDomainId",
    406: "intermediateProcessId",
    407: "ignoredDataRecordTotalCount",
    408: "dataLinkFrameType",
    409: "sectionOffset",
    410: "sectionExportedOctets",
    411: "dot1qServiceInstanceTag",
    412: "dot1qServiceInstanceId",
    413: "dot1qServiceInstancePriority",
    414: "dot1qCustomerSourceMacAddress",
    415: "dot1qCustomerDestinationMacAddress",
    417: "postLayer2OctetDeltaCount",
    418: "postMCastLayer2OctetDeltaCount",
    420: "postLayer2OctetTotalCount",
    421: "postMCastLayer2OctetTotalCount",
    422: "minimumLayer2TotalLength",
    423: "maximumLayer2TotalLength",
    424: "droppedLayer2OctetDeltaCount",
    425: "droppedLayer2OctetTotalCount",
    426: "ignoredLayer2OctetTotalCount",
    427: "notSentLayer2OctetTotalCount",
    428: "layer2OctetDeltaSumOfSquares",
    429: "layer2OctetTotalSumOfSquares",
    430: "layer2FrameDeltaCount",
    431: "layer2FrameTotalCount",
    432: "pseudoWireDestinationIPv4Address",
    433: "ignoredLayer2FrameTotalCount",
    434: "mibObjectValueInteger",
    435: "mibObjectValueOctetString",
    436: "mibObjectValueOID",
    437: "mibObjectValueBits",
    438: "mibObjectValueIPAddress",
    439: "mibObjectValueCounter",
    440: "mibObjectValueGauge",
    441: "mibObjectValueTimeTicks",
    442: "mibObjectValueUnsigned",
    443: "mibObjectValueTable",
    444: "mibObjectValueRow",
    445: "mibObjectIdentifier",
    446: "mibSubIdentifier",
    447: "mibIndexIndicator",
    448: "mibCaptureTimeSemantics",
    449: "mibContextEngineID",
    450: "mibContextName",
    451: "mibObjectName",
    452: "mibObjectDescription",
    453: "mibObjectSyntax",
    454: "mibModuleName",
    455: "mobileIMSI",
    456: "mobileMSISDN",
    457: "httpStatusCode",
    458: "sourceTransportPortsLimit",
    459: "httpRequestMethod",
    460: "httpRequestHost",
    461: "httpRequestTarget",
    462: "httpMessageVersion",
    466: "natQuotaExceededEvent",
    471: "maxSessionEntries",
    472: "maxBIBEntries",
    473: "maxEntriesPerUser",
    475: "maxFragmentsPendingReassembly"
}


class IPFIX(Packet):
    name = "IPFIX"
    fields_desc = [ShortField("version", 10),
                   ShortField("length", None),
                   IntField("exportTime", None),
                   IntField("sequenceNumber", 1),
                   IntField("observationDomainID", 1)]


class FieldSpecifier(Packet):
    name = "Field Specifier"
    fields_desc = [ShortEnumField(
        "informationElement", None, information_elements),
        ShortField("fieldLength", None)]

    def extract_padding(self, s):
        return "", s


class Template(Packet):
    name = "Template"
    fields_desc = [ShortField("templateID", 256),
                   FieldLenField("fieldCount", None, count_of="fields"),
                   PacketListField("templateFields", [], FieldSpecifier,
                                   count_from=lambda p: p.fieldCount)]


class Data(Packet):
    name = "Data"
    fields_desc = [
        StrLenField("data", "", length_from=lambda p: p.underlayer.length - 4)]

    def extract_padding(self, s):
        return "", s


class Set(Packet):
    name = "Set"
    fields_desc = [ShortField("setID", 256),
                   ShortField("length", None)]

    def guess_payload_class(self, payload):
        if self.setID == 2:
            return Template
        elif self.setID > 255:
            return Data
        else:
            return Packet.guess_payload_class(self, payload)


bind_layers(IPFIX, Set)
bind_layers(UDP, IPFIX, dport=4739)


class IPFIXDecoder(object):
    """ IPFIX data set decoder """

    def __init__(self):
        self._templates = []

    def add_template(self, template):
        """
        Add IPFIX tempalte

        :param template: IPFIX template
        """
        templateID = template.templateID
        fields = []
        rec_len = 0
        for field in template.templateFields:
            fields.append(
                {'name': field.informationElement, 'len': field.fieldLength})
            rec_len += field.fieldLength
        self._templates.append(
            {'id': templateID, 'fields': fields, 'rec_len': rec_len})

    def decode_data_set(self, data_set):
        """
        Decode IPFIX data

        :param data_set: IPFIX data set
        :returns: List of decoded data records.
        """
        data = []
        for template in self._templates:
            if template['id'] == data_set.setID:
                offset = 0
                d = data_set[Data].data
                for i in range(len(d) / template['rec_len']):
                    record = {}
                    for field in template['fields']:
                        f = d[offset:offset + field['len']]
                        offset += field['len']
                        record.update({field['name']: f})
                    data.append(record)
                break
        return data
> adj_walk_ctx_t; static int adj_nbr_walk_cb (BVT(clib_bihash_kv) * kvp, void *arg) { adj_walk_ctx_t *ctx = arg; // FIXME: can't stop early... if (ADJ_WALK_RC_STOP == ctx->awc_cb(kvp->value, ctx->awc_ctx)) return (BIHASH_WALK_STOP); return (BIHASH_WALK_CONTINUE); } void adj_nbr_walk (u32 sw_if_index, fib_protocol_t adj_nh_proto, adj_walk_cb_t cb, void *ctx) { if (!ADJ_NBR_ITF_OK(adj_nh_proto, sw_if_index)) return; adj_walk_ctx_t awc = { .awc_ctx = ctx, .awc_cb = cb, }; BV(clib_bihash_foreach_key_value_pair) ( adj_nbr_tables[adj_nh_proto][sw_if_index], adj_nbr_walk_cb, &awc); } /** * @brief Walk adjacencies on a link with a given v4 next-hop. * that is visit the adjacencies with different link types. */ void adj_nbr_walk_nh4 (u32 sw_if_index, const ip4_address_t *addr, adj_walk_cb_t cb, void *ctx) { if (!ADJ_NBR_ITF_OK(FIB_PROTOCOL_IP4, sw_if_index)) return; ip46_address_t nh = { .ip4 = *addr, }; vnet_link_t linkt; adj_index_t ai; FOR_EACH_VNET_LINK(linkt) { ai = adj_nbr_find (FIB_PROTOCOL_IP4, linkt, &nh, sw_if_index); if (INDEX_INVALID != ai) cb(ai, ctx); } } /** * @brief Walk adjacencies on a link with a given v6 next-hop. * that is visit the adjacencies with different link types. */ void adj_nbr_walk_nh6 (u32 sw_if_index, const ip6_address_t *addr, adj_walk_cb_t cb, void *ctx) { if (!ADJ_NBR_ITF_OK(FIB_PROTOCOL_IP6, sw_if_index)) return; ip46_address_t nh = { .ip6 = *addr, }; vnet_link_t linkt; adj_index_t ai; FOR_EACH_VNET_LINK(linkt) { ai = adj_nbr_find (FIB_PROTOCOL_IP6, linkt, &nh, sw_if_index); if (INDEX_INVALID != ai) cb(ai, ctx); } } /** * @brief Walk adjacencies on a link with a given next-hop. * that is visit the adjacencies with different link types. */ void adj_nbr_walk_nh (u32 sw_if_index, fib_protocol_t adj_nh_proto, const ip46_address_t *nh, adj_walk_cb_t cb, void *ctx) { if (!ADJ_NBR_ITF_OK(adj_nh_proto, sw_if_index)) return; switch (adj_nh_proto) { case FIB_PROTOCOL_IP4: adj_nbr_walk_nh4(sw_if_index, &nh->ip4, cb, ctx); break; case FIB_PROTOCOL_IP6: adj_nbr_walk_nh6(sw_if_index, &nh->ip6, cb, ctx); break; case FIB_PROTOCOL_MPLS: ASSERT(0); break; } } /** * Flags associated with the interface state walks */ typedef enum adj_nbr_interface_flags_t_ { ADJ_NBR_INTERFACE_UP = (1 << 0), } adj_nbr_interface_flags_t; /** * Context for the state change walk of the DB */ typedef struct adj_nbr_interface_state_change_ctx_t_ { /** * Flags on the interface */ adj_nbr_interface_flags_t flags; } adj_nbr_interface_state_change_ctx_t; static adj_walk_rc_t adj_nbr_interface_state_change_one (adj_index_t ai, void *arg) { /* * Back walk the graph to inform the forwarding entries * that this interface state has changed. Do this synchronously * since this is the walk that provides convergence */ adj_nbr_interface_state_change_ctx_t *ctx = arg; fib_node_back_walk_ctx_t bw_ctx = { .fnbw_reason = ((ctx->flags & ADJ_NBR_INTERFACE_UP) ? FIB_NODE_BW_REASON_FLAG_INTERFACE_UP : FIB_NODE_BW_REASON_FLAG_INTERFACE_DOWN), /* * the force sync applies only as far as the first fib_entry. * And it's the fib_entry's we need to converge away from * the adjacencies on the now down link */ .fnbw_flags = (!(ctx->flags & ADJ_NBR_INTERFACE_UP) ? FIB_NODE_BW_FLAG_FORCE_SYNC : FIB_NODE_BW_FLAG_NONE), }; ip_adjacency_t *adj; adj = adj_get(ai); adj->ia_flags |= ADJ_FLAG_SYNC_WALK_ACTIVE; fib_walk_sync(FIB_NODE_TYPE_ADJ, ai, &bw_ctx); adj->ia_flags &= ~ADJ_FLAG_SYNC_WALK_ACTIVE; return (ADJ_WALK_RC_CONTINUE); } /** * @brief Registered function for SW interface state changes */ static clib_error_t * adj_nbr_sw_interface_state_change (vnet_main_t * vnm, u32 sw_if_index, u32 flags) { fib_protocol_t proto; /* * walk each adj on the interface and trigger a walk from that adj */ for (proto = FIB_PROTOCOL_IP4; proto <= FIB_PROTOCOL_IP6; proto++) { adj_nbr_interface_state_change_ctx_t ctx = { .flags = ((flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) ? ADJ_NBR_INTERFACE_UP : 0), }; adj_nbr_walk(sw_if_index, proto, adj_nbr_interface_state_change_one, &ctx); } return (NULL); } VNET_SW_INTERFACE_ADMIN_UP_DOWN_FUNCTION_PRIO( adj_nbr_sw_interface_state_change, VNET_ITF_FUNC_PRIORITY_HIGH); /** * @brief Invoked on each SW interface of a HW interface when the * HW interface state changes */ static walk_rc_t adj_nbr_hw_sw_interface_state_change (vnet_main_t * vnm, u32 sw_if_index, void *arg) { adj_nbr_interface_state_change_ctx_t *ctx = arg; fib_protocol_t proto; /* * walk each adj on the interface and trigger a walk from that adj */ for (proto = FIB_PROTOCOL_IP4; proto <= FIB_PROTOCOL_IP6; proto++) { adj_nbr_walk(sw_if_index, proto, adj_nbr_interface_state_change_one, ctx); } return (WALK_CONTINUE); } /** * @brief Registered callback for HW interface state changes */ static clib_error_t * adj_nbr_hw_interface_state_change (vnet_main_t * vnm, u32 hw_if_index, u32 flags) { /* * walk SW interface on the HW */ adj_nbr_interface_state_change_ctx_t ctx = { .flags = ((flags & VNET_HW_INTERFACE_FLAG_LINK_UP) ? ADJ_NBR_INTERFACE_UP : 0), }; vnet_hw_interface_walk_sw(vnm, hw_if_index, adj_nbr_hw_sw_interface_state_change, &ctx); return (NULL); } VNET_HW_INTERFACE_LINK_UP_DOWN_FUNCTION_PRIO( adj_nbr_hw_interface_state_change, VNET_ITF_FUNC_PRIORITY_HIGH); static adj_walk_rc_t adj_nbr_interface_delete_one (adj_index_t ai, void *arg) { /* * Back walk the graph to inform the forwarding entries * that this interface has been deleted. */ fib_node_back_walk_ctx_t bw_ctx = { .fnbw_reason = FIB_NODE_BW_REASON_FLAG_INTERFACE_DELETE, }; ip_adjacency_t *adj; adj_lock(ai); adj = adj_get(ai); adj->ia_flags |= ADJ_FLAG_SYNC_WALK_ACTIVE; fib_walk_sync(FIB_NODE_TYPE_ADJ, ai, &bw_ctx); adj->ia_flags &= ~ADJ_FLAG_SYNC_WALK_ACTIVE; adj_unlock(ai); return (ADJ_WALK_RC_CONTINUE); } /** * adj_nbr_interface_add_del * * Registered to receive interface Add and delete notifications */ static clib_error_t * adj_nbr_interface_add_del (vnet_main_t * vnm, u32 sw_if_index, u32 is_add) { fib_protocol_t proto; if (is_add) { /* * not interested in interface additions. we will not back walk * to resolve paths through newly added interfaces. Why? The control * plane should have the brains to add interfaces first, then routes. * So the case where there are paths with a interface that matches * one just created is the case where the path resolved through an * interface that was deleted, and still has not been removed. The * new interface added, is NO GUARANTEE that the interface being * added now, even though it may have the same sw_if_index, is the * same interface that the path needs. So tough! * If the control plane wants these routes to resolve it needs to * remove and add them again. */ return (NULL); } for (proto = FIB_PROTOCOL_IP4; proto <= FIB_PROTOCOL_IP6; proto++) { adj_nbr_walk(sw_if_index, proto, adj_nbr_interface_delete_one, NULL); } return (NULL); } VNET_SW_INTERFACE_ADD_DEL_FUNCTION(adj_nbr_interface_add_del); static adj_walk_rc_t adj_nbr_show_one (adj_index_t ai, void *arg) { vlib_cli_output (arg, "[@%d] %U", ai, format_ip_adjacency, ai, FORMAT_IP_ADJACENCY_NONE); return (ADJ_WALK_RC_CONTINUE); } static clib_error_t * adj_nbr_show (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { adj_index_t ai = ADJ_INDEX_INVALID; ip46_address_t nh = ip46_address_initializer; u32 sw_if_index = ~0; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "%U", unformat_vnet_sw_interface, vnet_get_main(), &sw_if_index)) ; else if (unformat (input, "%U", unformat_ip46_address, &nh, IP46_TYPE_ANY)) ; else if (unformat (input, "%d", &ai)) ; else break; } if (ADJ_INDEX_INVALID != ai) { vlib_cli_output (vm, "[@%d] %U", ai, format_ip_adjacency, ai, FORMAT_IP_ADJACENCY_DETAIL); } else if (~0 != sw_if_index) { fib_protocol_t proto; if (ip46_address_is_zero(&nh)) { for (proto = FIB_PROTOCOL_IP4; proto <= FIB_PROTOCOL_IP6; proto++) { adj_nbr_walk(sw_if_index, proto, adj_nbr_show_one, vm); } } else { proto = (ip46_address_is_ip4(&nh) ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6); adj_nbr_walk_nh(sw_if_index, proto, &nh, adj_nbr_show_one, vm); } } else { fib_protocol_t proto; for (proto = FIB_PROTOCOL_IP4; proto <= FIB_PROTOCOL_IP6; proto++) { vec_foreach_index(sw_if_index, adj_nbr_tables[proto]) { adj_nbr_walk(sw_if_index, proto, adj_nbr_show_one, vm); } } } return 0; } /*? * Show all neighbour adjacencies. * @cliexpar * @cliexstart{sh adj nbr} * [@2] ipv4 via 1.0.0.2 loop0: IP4: 00:00:22:aa:bb:cc -> 00:00:11:aa:bb:cc * [@3] mpls via 1.0.0.2 loop0: MPLS_UNICAST: 00:00:22:aa:bb:cc -> 00:00:11:aa:bb:cc * [@4] ipv4 via 1.0.0.3 loop0: IP4: 00:00:22:aa:bb:cc -> 00:00:11:aa:bb:cc * [@5] mpls via 1.0.0.3 loop0: MPLS_UNICAST: 00:00:22:aa:bb:cc -> 00:00:11:aa:bb:cc * @cliexend ?*/ VLIB_CLI_COMMAND (ip4_show_fib_command, static) = { .path = "show adj nbr", .short_help = "show adj nbr [<adj_index>] [interface]", .function = adj_nbr_show, }; u8* format_adj_nbr_incomplete (u8* s, va_list *ap) { index_t index = va_arg(*ap, index_t); CLIB_UNUSED(u32 indent) = va_arg(*ap, u32); vnet_main_t * vnm = vnet_get_main(); ip_adjacency_t * adj = adj_get(index); s = format (s, "arp-%U", format_vnet_link, adj->ia_link); s = format (s, ": via %U", format_ip46_address, &adj->sub_type.nbr.next_hop, adj_proto_to_46(adj->ia_nh_proto)); s = format (s, " %U", format_vnet_sw_if_index_name, vnm, adj->rewrite_header.sw_if_index); return (s); } u8* format_adj_nbr (u8* s, va_list *ap) { index_t index = va_arg(*ap, index_t); CLIB_UNUSED(u32 indent) = va_arg(*ap, u32); ip_adjacency_t * adj = adj_get(index); s = format (s, "%U", format_vnet_link, adj->ia_link); s = format (s, " via %U ", format_ip46_address, &adj->sub_type.nbr.next_hop, adj_proto_to_46(adj->ia_nh_proto)); s = format (s, "%U", format_vnet_rewrite, &adj->rewrite_header, sizeof (adj->rewrite_data), 0); return (s); } static void adj_dpo_lock (dpo_id_t *dpo) { adj_lock(dpo->dpoi_index); } static void adj_dpo_unlock (dpo_id_t *dpo) { adj_unlock(dpo->dpoi_index); } static void adj_mem_show (void) { fib_show_memory_usage("Adjacency", pool_elts(adj_pool), pool_len(adj_pool), sizeof(ip_adjacency_t)); } const static dpo_vft_t adj_nbr_dpo_vft = { .dv_lock = adj_dpo_lock, .dv_unlock = adj_dpo_unlock, .dv_format = format_adj_nbr, .dv_mem_show = adj_mem_show, .dv_get_urpf = adj_dpo_get_urpf, }; const static dpo_vft_t adj_nbr_incompl_dpo_vft = { .dv_lock = adj_dpo_lock, .dv_unlock = adj_dpo_unlock, .dv_format = format_adj_nbr_incomplete, .dv_get_urpf = adj_dpo_get_urpf, }; /** * @brief The per-protocol VLIB graph nodes that are assigned to an adjacency * object. * * this means that these graph nodes are ones from which a nbr is the * parent object in the DPO-graph. */ const static char* const nbr_ip4_nodes[] = { "ip4-rewrite", NULL, }; const static char* const nbr_ip6_nodes[] = { "ip6-rewrite", NULL, }; const static char* const nbr_mpls_nodes[] = { "mpls-output", NULL, }; const static char* const nbr_ethernet_nodes[] = { "adj-l2-rewrite", NULL, }; const static char* const * const nbr_nodes[DPO_PROTO_NUM] = { [DPO_PROTO_IP4] = nbr_ip4_nodes, [DPO_PROTO_IP6] = nbr_ip6_nodes, [DPO_PROTO_MPLS] = nbr_mpls_nodes, [DPO_PROTO_ETHERNET] = nbr_ethernet_nodes, }; const static char* const nbr_incomplete_ip4_nodes[] = { "ip4-arp", NULL, }; const static char* const nbr_incomplete_ip6_nodes[] = { "ip6-discover-neighbor", NULL, }; const static char* const nbr_incomplete_mpls_nodes[] = { "mpls-adj-incomplete", NULL, }; const static char* const * const nbr_incomplete_nodes[DPO_PROTO_NUM] = { [DPO_PROTO_IP4] = nbr_incomplete_ip4_nodes, [DPO_PROTO_IP6] = nbr_incomplete_ip6_nodes, [DPO_PROTO_MPLS] = nbr_incomplete_mpls_nodes, }; void adj_nbr_module_init (void) { dpo_register(DPO_ADJACENCY, &adj_nbr_dpo_vft, nbr_nodes); dpo_register(DPO_ADJACENCY_INCOMPLETE, &adj_nbr_incompl_dpo_vft, nbr_incomplete_nodes); }