aboutsummaryrefslogtreecommitdiffstats
path: root/test/test_cnat.py
blob: ff4c44033cb4c55b84487f6d97d2c1a988a5f58d (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
20
/*
 * Copyright (c) 2015 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.
 */
#ifndef included_vnet_api_errno_h
#define included_vnet_api_errno_h

#include <stdarg.h>
#include <vppinfra/types.h>
#include <vppinfra/format.h>

#define foreach_vnet_api_error						\
_(UNSPECIFIED, -1, "Unspecified Error")                                 \
_(INVALID_SW_IF_INDEX, -2, "Invalid sw_if_index")                       \
_(NO_SUCH_FIB, -3, "No such FIB / VRF")                                 \
_(NO_SUCH_INNER_FIB, -4, "No such inner FIB / VRF")                     \
_(NO_SUCH_LABEL, -5, "No such label")                                   \
_(NO_SUCH_ENTRY, -6, "No such entry")                                   \
_(INVALID_VALUE, -7, "Invalid value")                                   \
_(INVALID_VALUE_2, -8, "Invalid value #2")                              \
_(UNIMPLEMENTED, -9, "Unimplemented")                                   \
_(INVALID_SW_IF_INDEX_2, -10, "Invalid sw_if_index #2")                 \
_(SYSCALL_ERROR_1, -11, "System call error #1")                         \
_(SYSCALL_ERROR_2, -12, "System call error #2")                         \
_(SYSCALL_ERROR_3, -13, "System call error #3")                         \
_(SYSCALL_ERROR_4, -14, "System call error #4")                         \
_(SYSCALL_ERROR_5, -15, "System call error #5")                         \
_(SYSCALL_ERROR_6, -16, "System call error #6")                         \
_(SYSCALL_ERROR_7, -17, "System call error #7")                         \
_(SYSCALL_ERROR_8, -18, "System call error #8")                         \
_(SYSCALL_ERROR_9, -19, "System call error #9")                         \
_(SYSCALL_ERROR_10, -20, "System call error #10")                       \
_(FEATURE_DISABLED, -30, "Feature disabled by configuration")           \
_(INVALID_REGISTRATION, -31, "Invalid registration")                    \
_(NEXT_HOP_NOT_IN_FIB, -50, "Next hop not in FIB")                      \
_(UNKNOWN_DESTINATION, -51, "Unknown destination")                      \
_(NO_PATHS_IN_ROUTE, -52, "No paths specified in route")                \
_(NEXT_HOP_NOT_FOUND_MP, -53, "Next hop not found (multipath)")         \
_(NO_MATCHING_INTERFACE, -54, "No matching interface for probe")        \
_(INVALID_VLAN, -55, "Invalid VLAN")                                    \
_(VLAN_ALREADY_EXISTS, -56, "VLAN subif already exists")                \
_(INVALID_SRC_ADDRESS, -57, "Invalid src address")                      \
_(INVALID_DST_ADDRESS, -58, "Invalid dst address")                      \
_(ADDRESS_LENGTH_MISMATCH, -59, "Address length mismatch")              \
_(ADDRESS_NOT_FOUND_FOR_INTERFACE, -60, "Address not found for interface") \
_(ADDRESS_NOT_DELETABLE, -61, "Address not deletable")                  \
_(IP6_NOT_ENABLED, -62, "ip6 not enabled")				\
_(NO_SUCH_NODE, -63, "No such graph node")				\
_(NO_SUCH_NODE2, -64, "No such graph node #2")				\
_(NO_SUCH_TABLE, -65, "No such table")                                  \
_(NO_SUCH_TABLE2, -66, "No such table #2")                              \
_(NO_SUCH_TABLE3, -67, "No such table #3")                              \
_(SUBIF_ALREADY_EXISTS, -68, "Subinterface already exists")             \
_(SUBIF_CREATE_FAILED, -69, "Subinterface creation failed")		\
_(INVALID_MEMORY_SIZE, -70, "Invalid memory size requested")            \
_(INVALID_INTERFACE, -71, "Invalid interface")                          \
_(INVALID_VLAN_TAG_COUNT, -72, "Invalid number of tags for requested operation") \
_(INVALID_ARGUMENT, -73, "Invalid argument")                            \
_(UNEXPECTED_INTF_STATE, -74, "Unexpected interface state")             \
_(TUNNEL_EXIST, -75, "Tunnel already exists")                           \
_(INVALID_DECAP_NEXT, -76, "Invalid decap-next")			\
_(RESPONSE_NOT_READY, -77, "Response not ready")			\
_(NOT_CONNECTED, -78, "Not connected to the data plane")                \
_(IF_ALREADY_EXISTS, -79, "Interface already exists")                   \
_(BOND_SLAVE_NOT_ALLOWED, -80, "Operation not allowed on slave of BondEthernet") \
_(VALUE_EXIST, -81, "Value already exists")                             \
_(SAME_SRC_DST, -82, "Source and destination are the same")             \
_(IP6_MULTICAST_ADDRESS_NOT_PRESENT, -83, "IP6 multicast address required") \
_(SR_POLICY_NAME_NOT_PRESENT, -84, "Segment routing policy name required") \
_(NOT_RUNNING_AS_ROOT, -85, "Not running as root") \
_(ALREADY_CONNECTED, -86, "Connection to the data plane already exists") \
_(UNSUPPORTED_JNI_VERSION, -87, "Unsupported JNI version") \
_(FAILED_TO_ATTACH_TO_JAVA_THREAD, -88, "Failed to attach to Java thread") \
_(INVALID_WORKER, -89, "Invalid worker thread")                         \
_(LISP_DISABLED, -90, "LISP is disabled")                               \
_(CLASSIFY_TABLE_NOT_FOUND, -91, "Classify table not found")            \
_(INVALID_EID_TYPE, -92, "Unsupported LISP EID type")                   \
_(CANNOT_CREATE_PCAP_FILE, -93, "Cannot create pcap file")              \
_(INCORRECT_ADJACENCY_TYPE, -94, "Invalid adjacency type for this operation") \
_(EXCEEDED_NUMBER_OF_RANGES_CAPACITY, -95, "Operation would exceed configured capacity of ranges") \
_(EXCEEDED_NUMBER_OF_PORTS_CAPACITY, -96, "Operation would exceed capacity of number of ports") \
_(INVALID_ADDRESS_FAMILY, -97, "Invalid address family")                \
_(INVALID_SUB_SW_IF_INDEX, -98, "Invalid sub-interface sw_if_index")    \
_(TABLE_TOO_BIG, -99, "Table too big")                                  \
_(CANNOT_ENABLE_DISABLE_FEATURE, -100, "Cannot enable/disable feature") \
_(BFD_EEXIST, -101, "Duplicate BFD object")                             \
_(BFD_ENOENT, -102, "No such BFD object")                               \
_(BFD_EINUSE, -103, "BFD object in use")                                \
_(BFD_NOTSUPP, -104, "BFD feature not supported")                       \
_(ADDRESS_IN_USE, -105, "Address in use")				\
_(ADDRESS_NOT_IN_USE, -106, "Address not in use")			\
_(QUEUE_FULL, -107, "Queue full")                                       \
_(APP_UNSUPPORTED_CFG, -108, "Unsupported application config")		\
_(URI_FIFO_CREATE_FAILED, -109, "URI FIFO segment create failed")       \
_(LISP_RLOC_LOCAL, -110, "RLOC address is local")                       \
_(BFD_EAGAIN, -111, "BFD object cannot be manipulated at this time")	\
_(INVALID_GPE_MODE, -112, "Invalid GPE mode")                           \
_(LISP_GPE_ENTRIES_PRESENT, -113, "LISP GPE entries are present")       \
_(ADDRESS_FOUND_FOR_INTERFACE, -114, "Address found for interface")	\
_(SESSION_CONNECT, -115, "Session failed to connect")              	\
_(ENTRY_ALREADY_EXISTS, -116, "Entry already exists")			\
_(SVM_SEGMENT_CREATE_FAIL, -117, "Svm segment create fail")		\
_(APPLICATION_NOT_ATTACHED, -118, "Application not attached")           \
_(BD_ALREADY_EXISTS, -119, "Bridge domain already exists")              \
_(BD_IN_USE, -120, "Bridge domain has member interfaces")		\
_(BD_NOT_MODIFIABLE, -121, "Bridge domain 0 can't be deleted/modified") \
_(BD_ID_EXCEED_MAX, -122, "Bridge domain ID exceeds 16M limit")		\
_(SUBIF_DOESNT_EXIST, -123, "Subinterface doesn't exist")               \
_(L2_MACS_EVENT_CLINET_PRESENT, -124, "Client already exist for L2 MACs events") \
_(INVALID_QUEUE, -125, "Invalid queue")                 		\
_(UNSUPPORTED, -126, "Unsupported")					\
_(DUPLICATE_IF_ADDRESS, -127, "Address already present on another interface")	\
_(APP_INVALID_NS, -128, "Invalid application namespace")			\
_(APP_WRONG_NS_SECRET, -129, "Wrong app namespace secret")		\
_(APP_CONNECT_SCOPE, -130, "Connect scope")				\
_(APP_ALREADY_ATTACHED, -131, "App already attached")			\
_(SESSION_REDIRECT, -132, "Redirect failed")				\
_(ILLEGAL_NAME, -133, "Illegal name")					\
_(NO_NAME_SERVERS, -134, "No name servers configured")			\
_(NAME_SERVER_NOT_FOUND, -135, "Name server not found")			\
_(NAME_RESOLUTION_NOT_ENABLED, -136, "Name resolution not enabled")	\
_(NAME_SERVER_FORMAT_ERROR, -137, "Server format error (bug!)")		\
_(NAME_SERVER_NO_SUCH_NAME, -138, "No such name")                       \
_(NAME_SERVER_NO_ADDRESSES, -139, "No addresses available")		\
_(NAME_SERVER_NEXT_SERVER, -140, "Retry with new server")		\
_(APP_CONNECT_FILTERED, -141, "Connect was filtered")			\
_(ACL_IN_USE_INBOUND, -142, "Inbound ACL in use")			\
_(ACL_IN_USE_OUTBOUND, -143, "Outbound ACL in use")			\
_(INIT_FAILED, -144, "Initialization Failed")				\
_(NETLINK_ERROR, -145, "Netlink error")                                 \
_(BIER_BSL_UNSUP, -146, "BIER bit-string-length unsupported")		\
_(INSTANCE_IN_USE, -147, "Instance in use")				\
_(INVALID_SESSION_ID, -148, "Session ID out of range")			\
_(ACL_IN_USE_BY_LOOKUP_CONTEXT, -149, "ACL in use by a lookup context")	\
_(INVALID_VALUE_3, -150, "Invalid value #3")                            \
_(NON_ETHERNET, -151, "Interface is not an Ethernet interface")         \
_(BD_ALREADY_HAS_BVI, -152, "Bridge domain already has a BVI interface") \
_(INVALID_PROTOCOL, -153, "Invalid Protocol")                           \
_(INVALID_ALGORITHM, -154, "Invalid Algorithm")                         \
_(RSRC_IN_USE, -155, "Resource In Use")                                 \
_(KEY_LENGTH, -156, "invalid Key Length")                               \
_(FIB_PATH_UNSUPPORTED_NH_PROTO, -157, "Unsupported FIB Path protocol") \
_(API_ENDIAN_FAILED, -159, "Endian mismatch detected")			\
_(NO_CHANGE, -160, "No change in table")				\
_(MISSING_CERT_KEY, -161, "Missing certifcate or key")                  \
_(LIMIT_EXCEEDED, -162, "limit exceeded")

typedef enum
{
#define _(a,b,c) VNET_API_ERROR_##a = (b),
  foreach_vnet_api_error
#undef _
    VNET_API_N_ERROR,
} vnet_api_error_t;

/* *INDENT-OFF* */
static inline u8 *
format_vnet_api_errno (u8 * s, va_list * args)
{
  vnet_api_error_t api_error = va_arg (*args, vnet_api_error_t);
#ifdef _
#undef _
#endif
#define _(a, b, c)           \
  case b:                    \
    s = format (s, "%s", c); \
    break;
  switch (api_error)
    {
      foreach_vnet_api_error
      default:
       	s = format (s, "UNKNOWN");
        break;
    }
  return s;
#undef _
}
/* *INDENT-ON* */
@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
#!/usr/bin/env python3

import unittest

from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto, INVALID_INDEX
from itertools import product

from scapy.packet import Raw
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP, TCP, ICMP
from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror
from scapy.layers.inet6 import IPv6, IPerror6, ICMPv6DestUnreach
from scapy.layers.inet6 import ICMPv6EchoRequest, ICMPv6EchoReply

import struct

from ipaddress import ip_address, ip_network, \
    IPv4Address, IPv6Address, IPv4Network, IPv6Network

from vpp_object import VppObject
from vpp_papi import VppEnum

N_PKTS = 15


class Ep(object):
    """ CNat endpoint """

    def __init__(self, ip=None, port=0, l4p=TCP,
                 sw_if_index=INVALID_INDEX, is_v6=False):
        self.ip = ip
        if ip is None:
            self.ip = "::" if is_v6 else "0.0.0.0"
        self.port = port
        self.l4p = l4p
        self.sw_if_index = sw_if_index
        if is_v6:
            self.if_af = VppEnum.vl_api_address_family_t.ADDRESS_IP6
        else:
            self.if_af = VppEnum.vl_api_address_family_t.ADDRESS_IP4

    def encode(self):
        return {'addr': self.ip,
                'port': self.port,
                'sw_if_index': self.sw_if_index,
                'if_af': self.if_af}

    @classmethod
    def from_pg(cls, pg, is_v6=False):
        if pg is None:
            return cls(is_v6=is_v6)
        else:
            return cls(sw_if_index=pg.sw_if_index, is_v6=is_v6)

    @property
    def isV6(self):
        return ":" in self.ip

    def __str__(self):
        return ("%s:%d" % (self.ip, self.port))


class EpTuple(object):
    """ CNat endpoint """

    def __init__(self, src, dst):
        self.src = src
        self.dst = dst

    def encode(self):
        return {'src_ep': self.src.encode(),
                'dst_ep': self.dst.encode()}

    def __str__(self):
        return ("%s->%s" % (self.src, self.dst))


class VppCNatTranslation(VppObject):

    def __init__(self, test, iproto, vip, paths):
        self._test = test
        self.vip = vip
        self.iproto = iproto
        self.paths = paths
        self.encoded_paths = []
        for path in self.paths:
            self.encoded_paths.append(path.encode())

    def __str__(self):
        return ("%s %s %s" % (self.vip, self.iproto, self.paths))

    @property
    def vl4_proto(self):
        ip_proto = VppEnum.vl_api_ip_proto_t
        return {
            UDP: ip_proto.IP_API_PROTO_UDP,
            TCP: ip_proto.IP_API_PROTO_TCP,
        }[self.iproto]

    def add_vpp_config(self):
        r = self._test.vapi.cnat_translation_update(
            {'vip': self.vip.encode(),
             'ip_proto': self.vl4_proto,
             'n_paths': len(self.paths),
             'paths': self.encoded_paths})
        self._test.registry.register(self, self._test.logger)
        self.id = r.id

    def modify_vpp_config(self, paths):
        self.paths = paths
        self.encoded_paths = []
        for path in self.paths:
            self.encoded_paths.append(path.encode())

        r = self._test.vapi.cnat_translation_update(
            {'vip': self.vip.encode(),
             'ip_proto': self.vl4_proto,
             'n_paths': len(self.paths),
             'paths': self.encoded_paths})
        self._test.registry.register(self, self._test.logger)

    def remove_vpp_config(self):
        self._test.vapi.cnat_translation_del(id=self.id)

    def query_vpp_config(self):
        for t in self._test.vapi.cnat_translation_dump():
            if self.id == t.translation.id:
                return t.translation
        return None

    def object_id(self):
        return ("cnat-translation-%s" % (self.vip))

    def get_stats(self):
        c = self._test.statistics.get_counter("/net/cnat-translation")
        return c[0][self.id]


class TestCNatTranslation(VppTestCase):
    """ CNat Translation """
    extra_vpp_punt_config = ["cnat", "{",
                             "session-db-buckets", "64",
                             "session-cleanup-timeout", "0.1",
                             "session-max-age", "1",
                             "tcp-max-age", "1",
                             "scanner", "off", "}"]

    @classmethod
    def setUpClass(cls):
        super(TestCNatTranslation, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        super(TestCNatTranslation, cls).tearDownClass()

    def setUp(self):
        super(TestCNatTranslation, self).setUp()

        self.create_pg_interfaces(range(3))

        for i in self.pg_interfaces:
            i.admin_up()
            i.config_ip4()
            i.resolve_arp()
            i.config_ip6()
            i.resolve_ndp()

    def tearDown(self):
        for i in self.pg_interfaces:
            i.unconfig_ip4()
            i.unconfig_ip6()
            i.admin_down()
        super(TestCNatTranslation, self).tearDown()

    def cnat_create_translation(self, vip, nbr):
        ip_v = "ip6" if vip.isV6 else "ip4"
        dep = Ep(getattr(self.pg1.remote_hosts[nbr], ip_v), 4000 + nbr)
        sep = Ep("::", 0) if vip.isV6 else Ep("0.0.0.0", 0)
        t1 = VppCNatTranslation(
            self, vip.l4p, vip,
            [EpTuple(sep, dep), EpTuple(sep, dep)])
        t1.add_vpp_config()
        return t1

    def cnat_test_translation(self, t1, nbr, sports, isV6=False):
        ip_v = "ip6" if isV6 else "ip4"
        ip_class = IPv6 if isV6 else IP
        vip = t1.vip

        #
        # Flows
        #
        for src in self.pg0.remote_hosts:
            for sport in sports:
                # from client to vip
                p1 = (Ether(dst=self.pg0.local_mac,
                            src=src.mac) /
                      ip_class(src=getattr(src, ip_v), dst=vip.ip) /
                      vip.l4p(sport=sport, dport=vip.port) /
                      Raw())

                self.vapi.cli("trace add pg-input 1")
                rxs = self.send_and_expect(self.pg0,
                                           p1 * N_PKTS,
                                           self.pg1)
                self.logger.info(self.vapi.cli("show trace max 1"))

                for rx in rxs:
                    self.assert_packet_checksums_valid(rx)
                    self.assertEqual(
                        rx[ip_class].dst,
                        getattr(self.pg1.remote_hosts[nbr], ip_v))
                    self.assertEqual(rx[vip.l4p].dport, 4000 + nbr)
                    self.assertEqual(
                        rx[ip_class].src,
                        getattr(src, ip_v))
                    self.assertEqual(rx[vip.l4p].sport, sport)

                # from vip to client
                p1 = (Ether(dst=self.pg1.local_mac,
                            src=self.pg1.remote_mac) /
                      ip_class(src=getattr(
                          self.pg1.remote_hosts[nbr],
                          ip_v),
                          dst=getattr(src, ip_v)) /
                      vip.l4p(sport=4000 + nbr, dport=sport) /
                      Raw())

                rxs = self.send_and_expect(self.pg1,
                                           p1 * N_PKTS,
                                           self.pg0)

                for rx in rxs:
                    self.assert_packet_checksums_valid(rx)
                    self.assertEqual(
                        rx[ip_class].dst,
                        getattr(src, ip_v))
                    self.assertEqual(rx[vip.l4p].dport, sport)
                    self.assertEqual(rx[ip_class].src, vip.ip)
                    self.assertEqual(rx[vip.l4p].sport, vip.port)

                #
                # packets to the VIP that do not match a
                # translation are dropped
                #
                p1 = (Ether(dst=self.pg0.local_mac,
                            src=src.mac) /
                      ip_class(src=getattr(src, ip_v), dst=vip.ip) /
                      vip.l4p(sport=sport, dport=6666) /
                      Raw())

                self.send_and_assert_no_replies(self.pg0,
                                                p1 * N_PKTS,
                                                self.pg1)

                #
                # packets from the VIP that do not match a
                # session are forwarded
                #
                p1 = (Ether(dst=self.pg1.local_mac,
                            src=self.pg1.remote_mac) /
                      ip_class(src=getattr(
                          self.pg1.remote_hosts[nbr],
                          ip_v),
                          dst=getattr(src, ip_v)) /
                      vip.l4p(sport=6666, dport=sport) /
                      Raw())

                rxs = self.send_and_expect(self.pg1,
                                           p1 * N_PKTS,
                                           self.pg0)

    def cnat_test_translation_update(self, t1, sports, isV6=False):
        ip_v = "ip6" if isV6 else "ip4"
        ip_class = IPv6 if isV6 else IP
        vip = t1.vip

        #
        # modify the translation to use a different backend
        #
        dep = Ep(getattr(self.pg2, 'remote_' + ip_v), 5000)
        sep = Ep("::", 0) if isV6 else Ep("0.0.0.0", 0)
        t1.modify_vpp_config([EpTuple(sep, dep)])

        #
        # existing flows follow the old path
        #
        for src in self.pg0.remote_hosts:
            for sport in sports:
                # from client to vip
                p1 = (Ether(dst=self.pg0.local_mac,
                            src=src.mac) /
                      ip_class(src=getattr(src, ip_v), dst=vip.ip) /
                      vip.l4p(sport=sport, dport=vip.port) /
                      Raw())

                rxs = self.send_and_expect(self.pg0,
                                           p1 * N_PKTS,
                                           self.pg1)

        #
        # new flows go to the new backend
        #
        for src in self.pg0.remote_hosts:
            p1 = (Ether(dst=self.pg0.local_mac,
                        src=src.mac) /
                  ip_class(src=getattr(src, ip_v), dst=vip.ip) /
                  vip.l4p(sport=9999, dport=vip.port) /
                  Raw())

            rxs = self.send_and_expect(self.pg0,
                                       p1 * N_PKTS,
                                       self.pg2)

    def cnat_translation(self, vips, isV6=False):
        """ CNat Translation """

        ip_class = IPv6 if isV6 else IP
        ip_v = "ip6" if isV6 else "ip4"
        sports = [1234, 1233]

        #
        # turn the scanner off whilst testing otherwise sessions
        # will time out
        #
        self.vapi.cli("test cnat scanner off")

        sessions = self.vapi.cnat_session_dump()

        trs = []
        for nbr, vip in enumerate(vips):
            trs.append(self.cnat_create_translation(vip, nbr))

        self.logger.info(self.vapi.cli("sh cnat client"))
        self.logger.info(self.vapi.cli("sh cnat translation"))

        #
        # translations
        #
        for nbr, vip in enumerate(vips):
            self.cnat_test_translation(trs[nbr], nbr, sports, isV6=isV6)
            self.cnat_test_translation_update(trs[nbr], sports, isV6=isV6)
            if isV6:
                self.logger.info(self.vapi.cli(
                    "sh ip6 fib %s" % self.pg0.remote_ip6))
            else:
                self.logger.info(self.vapi.cli(
                    "sh ip fib %s" % self.pg0.remote_ip4))
            self.logger.info(self.vapi.cli("sh cnat session verbose"))

        #
        # turn the scanner back on and wait until the sessions
        # all disapper
        #
        self.vapi.cli("test cnat scanner on")

        n_tries = 0
        sessions = self.vapi.cnat_session_dump()
        while (len(sessions) and n_tries < 100):
            n_tries += 1
            sessions = self.vapi.cnat_session_dump()
            self.sleep(2)
            self.logger.info(self.vapi.cli("show cnat session verbose"))

        self.assertTrue(n_tries < 100)
        self.vapi.cli("test cnat scanner off")

        #
        # load some flows again and purge
        #
        for vip in vips:
            for src in self.pg0.remote_hosts:
                for sport in sports:
                    # from client to vip
                    p1 = (Ether(dst=self.pg0.local_mac,
                                src=src.mac) /
                          ip_class(src=getattr(src, ip_v), dst=vip.ip) /
                          vip.l4p(sport=sport, dport=vip.port) /
                          Raw())
                    self.send_and_expect(self.pg0,
                                         p1 * N_PKTS,
                                         self.pg2)

        for tr in trs:
            tr.remove_vpp_config()

        self.assertTrue(self.vapi.cnat_session_dump())
        self.vapi.cnat_session_purge()
        self.assertFalse(self.vapi.cnat_session_dump())

    def test_icmp(self):
        vips = [
            Ep("30.0.0.1", 5555),
            Ep("30.0.0.2", 5554),
            Ep("30.0.0.2", 5553, UDP),
            Ep("30::1", 6666),
            Ep("30::2", 5553, UDP),
        ]
        sport = 1234

        self.pg0.generate_remote_hosts(len(vips))
        self.pg0.configure_ipv6_neighbors()
        self.pg0.configure_ipv4_neighbors()

        self.pg1.generate_remote_hosts(len(vips))
        self.pg1.configure_ipv6_neighbors()
        self.pg1.configure_ipv4_neighbors()

        self.vapi.cli("test cnat scanner off")
        trs = []
        for nbr, vip in enumerate(vips):
            trs.append(self.cnat_create_translation(vip, nbr))

        self.logger.info(self.vapi.cli("sh cnat client"))
        self.logger.info(self.vapi.cli("sh cnat translation"))

        for nbr, vip in enumerate(vips):
            if vip.isV6:
                client_addr = self.pg0.remote_hosts[0].ip6
                remote_addr = self.pg1.remote_hosts[nbr].ip6
                remote2_addr = self.pg2.remote_hosts[0].ip6
            else:
                client_addr = self.pg0.remote_hosts[0].ip4
                remote_addr = self.pg1.remote_hosts[nbr].ip4
                remote2_addr = self.pg2.remote_hosts[0].ip4
            IP46 = IPv6 if vip.isV6 else IP
            # from client to vip
            p1 = (Ether(dst=self.pg0.local_mac,
                        src=self.pg0.remote_hosts[0].mac) /
                  IP46(src=client_addr, dst=vip.ip) /
                  vip.l4p(sport=sport, dport=vip.port) /
                  Raw())

            rxs = self.send_and_expect(self.pg0,
                                       p1 * N_PKTS,
                                       self.pg1)

            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].dst, remote_addr)
                self.assertEqual(rx[vip.l4p].dport, 4000 + nbr)
                self.assertEqual(rx[IP46].src, client_addr)
                self.assertEqual(rx[vip.l4p].sport, sport)

            InnerIP = rxs[0][IP46]

            ICMP46 = ICMPv6DestUnreach if vip.isV6 else ICMP
            ICMPelem = ICMPv6DestUnreach(code=1) if vip.isV6 else ICMP(type=11)
            # from vip to client, ICMP error
            p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
                  IP46(src=remote_addr, dst=client_addr) /
                  ICMPelem / InnerIP)

            rxs = self.send_and_expect(self.pg1,
                                       p1 * N_PKTS,
                                       self.pg0)

            TCPUDPError = TCPerror if vip.l4p == TCP else UDPerror
            IP46error = IPerror6 if vip.isV6 else IPerror
            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].src, vip.ip)
                self.assertEqual(rx[ICMP46][IP46error].src, client_addr)
                self.assertEqual(rx[ICMP46][IP46error].dst, vip.ip)
                self.assertEqual(rx[ICMP46][IP46error]
                                 [TCPUDPError].sport, sport)
                self.assertEqual(rx[ICMP46][IP46error]
                                 [TCPUDPError].dport, vip.port)

            # from other remote to client, ICMP error
            # outside shouldn't be NAT-ed
            p1 = (Ether(dst=self.pg2.local_mac, src=self.pg2.remote_mac) /
                  IP46(src=remote2_addr, dst=client_addr) /
                  ICMPelem / InnerIP)

            rxs = self.send_and_expect(self.pg1,
                                       p1 * N_PKTS,
                                       self.pg0)

            TCPUDPError = TCPerror if vip.l4p == TCP else UDPerror
            IP46error = IPerror6 if vip.isV6 else IPerror
            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].src, remote2_addr)
                self.assertEqual(rx[ICMP46][IP46error].src, client_addr)
                self.assertEqual(rx[ICMP46][IP46error].dst, vip.ip)
                self.assertEqual(rx[ICMP46][IP46error]
                                 [TCPUDPError].sport, sport)
                self.assertEqual(rx[ICMP46][IP46error]
                                 [TCPUDPError].dport, vip.port)

        self.vapi.cnat_session_purge()

    def test_cnat6(self):
        # """ CNat Translation ipv6 """
        vips = [
            Ep("30::1", 5555),
            Ep("30::2", 5554),
            Ep("30::2", 5553, UDP),
        ]

        self.pg0.generate_remote_hosts(len(vips))
        self.pg0.configure_ipv6_neighbors()
        self.pg1.generate_remote_hosts(len(vips))
        self.pg1.configure_ipv6_neighbors()

        self.cnat_translation(vips, isV6=True)

    def test_cnat4(self):
        # """ CNat Translation ipv4 """

        vips = [
            Ep("30.0.0.1", 5555),
            Ep("30.0.0.2", 5554),
            Ep("30.0.0.2", 5553, UDP),
        ]

        self.pg0.generate_remote_hosts(len(vips))
        self.pg0.configure_ipv4_neighbors()
        self.pg1.generate_remote_hosts(len(vips))
        self.pg1.configure_ipv4_neighbors()

        self.cnat_translation(vips)


class TestCNatSourceNAT(VppTestCase):
    """ CNat Source NAT """
    extra_vpp_punt_config = ["cnat", "{",
                             "session-cleanup-timeout", "0.1",
                             "session-max-age", "1",
                             "tcp-max-age", "1",
                             "scanner", "off", "}"]

    @classmethod
    def setUpClass(cls):
        super(TestCNatSourceNAT, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        super(TestCNatSourceNAT, cls).tearDownClass()

    def setUp(self):
        super(TestCNatSourceNAT, self).setUp()

        self.create_pg_interfaces(range(3))

        for i in self.pg_interfaces:
            i.admin_up()
            i.config_ip4()
            i.resolve_arp()
            i.config_ip6()
            i.resolve_ndp()

        self.pg0.configure_ipv6_neighbors()
        self.pg0.configure_ipv4_neighbors()
        self.pg1.generate_remote_hosts(2)
        self.pg1.configure_ipv4_neighbors()
        self.pg1.configure_ipv6_neighbors()

        self.vapi.cnat_set_snat_addresses(
            snat_ip4=self.pg2.remote_hosts[0].ip4,
            snat_ip6=self.pg2.remote_hosts[0].ip6,
            sw_if_index=INVALID_INDEX)
        self.vapi.feature_enable_disable(
            enable=1,
            arc_name="ip6-unicast",
            feature_name="cnat-snat-ip6",
            sw_if_index=self.pg0.sw_if_index)
        self.vapi.feature_enable_disable(
            enable=1,
            arc_name="ip4-unicast",
            feature_name="cnat-snat-ip4",
            sw_if_index=self.pg0.sw_if_index)

        policie_tbls = VppEnum.vl_api_cnat_snat_policy_table_t
        self.vapi.cnat_set_snat_policy(
            policy=VppEnum.vl_api_cnat_snat_policies_t.CNAT_POLICY_IF_PFX)
        for i in self.pg_interfaces:
            self.vapi.cnat_snat_policy_add_del_if(
                sw_if_index=i.sw_if_index, is_add=1,
                table=policie_tbls.CNAT_POLICY_INCLUDE_V6)
            self.vapi.cnat_snat_policy_add_del_if(
                sw_if_index=i.sw_if_index, is_add=1,
                table=policie_tbls.CNAT_POLICY_INCLUDE_V4)

    def tearDown(self):
        self.vapi.cnat_session_purge()
        for i in self.pg_interfaces:
            i.unconfig_ip4()
            i.unconfig_ip6()
            i.admin_down()
        super(TestCNatSourceNAT, self).tearDown()

    def test_snat_v6(self):
        # """ CNat Source Nat v6 """
        self.sourcenat_test_tcp_udp_conf(TCP, isV6=True)
        self.sourcenat_test_tcp_udp_conf(UDP, isV6=True)
        self.sourcenat_test_icmp_err_conf(isV6=True)
        self.sourcenat_test_icmp_echo6_conf()

    def test_snat_v4(self):
        # """ CNat Source Nat v4 """
        self.sourcenat_test_tcp_udp_conf(TCP)
        self.sourcenat_test_tcp_udp_conf(UDP)
        self.sourcenat_test_icmp_err_conf()
        self.sourcenat_test_icmp_echo4_conf()

    def sourcenat_test_icmp_echo6_conf(self):
        sports = [1234, 1235]
        dports = [6661, 6662]

        for nbr, remote_host in enumerate(self.pg1.remote_hosts):
            client_addr = self.pg0.remote_hosts[0].ip6
            remote_addr = self.pg1.remote_hosts[nbr].ip6
            src_nat_addr = self.pg2.remote_hosts[0].ip6

            # ping from pods to outside network
            p1 = (
                Ether(dst=self.pg0.local_mac,
                      src=self.pg0.remote_hosts[0].mac) /
                IPv6(src=client_addr, dst=remote_addr) /
                ICMPv6EchoRequest(id=0xfeed) /
                Raw())

            rxs = self.send_and_expect(
                self.pg0,
                p1 * N_PKTS,
                self.pg1)

            for rx in rxs:
                self.assertEqual(rx[IPv6].src, src_nat_addr)
                self.assert_packet_checksums_valid(rx)

            received_id = rx[0][ICMPv6EchoRequest].id
            # ping reply from outside to pods
            p2 = (
                Ether(dst=self.pg1.local_mac,
                      src=self.pg1.remote_hosts[nbr].mac) /
                IPv6(src=remote_addr, dst=src_nat_addr) /
                ICMPv6EchoReply(id=received_id))
            rxs = self.send_and_expect(
                self.pg1,
                p2 * N_PKTS,
                self.pg0)

            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IPv6].src, remote_addr)
                self.assertEqual(rx[ICMPv6EchoReply].id, 0xfeed)

    def sourcenat_test_icmp_echo4_conf(self):
        sports = [1234, 1235]
        dports = [6661, 6662]

        for nbr, remote_host in enumerate(self.pg1.remote_hosts):
            IP46 = IP
            client_addr = self.pg0.remote_hosts[0].ip4
            remote_addr = self.pg1.remote_hosts[nbr].ip4
            src_nat_addr = self.pg2.remote_hosts[0].ip4

            # ping from pods to outside network
            p1 = (
                Ether(dst=self.pg0.local_mac,
                      src=self.pg0.remote_hosts[0].mac) /
                IP46(src=client_addr, dst=remote_addr) /
                ICMP(type=8, id=0xfeed) /
                Raw())

            rxs = self.send_and_expect(
                self.pg0,
                p1 * N_PKTS,
                self.pg1)

            for rx in rxs:
                self.assertEqual(rx[IP46].src, src_nat_addr)
                self.assert_packet_checksums_valid(rx)

            received_id = rx[0][ICMP].id
            # ping reply from outside to pods
            p2 = (
                Ether(dst=self.pg1.local_mac,
                      src=self.pg1.remote_hosts[nbr].mac) /
                IP46(src=remote_addr, dst=src_nat_addr) /
                ICMP(type=0, id=received_id))
            rxs = self.send_and_expect(
                self.pg1,
                p2 * N_PKTS,
                self.pg0)

            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].src, remote_addr)
                self.assertEqual(rx[ICMP].id, 0xfeed)

    def sourcenat_test_icmp_err_conf(self, isV6=False):
        sports = [1234, 1235]
        dports = [6661, 6662]

        for nbr, remote_host in enumerate(self.pg1.remote_hosts):
            if isV6:
                IP46 = IPv6
                client_addr = self.pg0.remote_hosts[0].ip6
                remote_addr = self.pg1.remote_hosts[nbr].ip6
                src_nat_addr = self.pg2.remote_hosts[0].ip6
                ICMP46 = ICMPv6DestUnreach
                ICMPelem = ICMPv6DestUnreach(code=1)
                IP46error = IPerror6
            else:
                IP46 = IP
                client_addr = self.pg0.remote_hosts[0].ip4
                remote_addr = self.pg1.remote_hosts[nbr].ip4
                src_nat_addr = self.pg2.remote_hosts[0].ip4
                IP46error = IPerror
                ICMP46 = ICMP
                ICMPelem = ICMP(type=11)

            # from pods to outside network
            p1 = (
                Ether(dst=self.pg0.local_mac,
                      src=self.pg0.remote_hosts[0].mac) /
                IP46(src=client_addr, dst=remote_addr) /
                TCP(sport=sports[nbr], dport=dports[nbr]) /
                Raw())

            rxs = self.send_and_expect(
                self.pg0,
                p1 * N_PKTS,
                self.pg1)
            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].dst, remote_addr)
                self.assertEqual(rx[TCP].dport, dports[nbr])
                self.assertEqual(rx[IP46].src, src_nat_addr)
                sport = rx[TCP].sport

            InnerIP = rxs[0][IP46]
            # from outside to pods, ICMP error
            p2 = (
                Ether(dst=self.pg1.local_mac,
                      src=self.pg1.remote_hosts[nbr].mac) /
                IP46(src=remote_addr, dst=src_nat_addr) /
                ICMPelem / InnerIP)

            rxs = self.send_and_expect(
                self.pg1,
                p2 * N_PKTS,
                self.pg0)

            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].src, remote_addr)
                self.assertEqual(rx[ICMP46][IP46error].src, client_addr)
                self.assertEqual(rx[ICMP46][IP46error].dst, remote_addr)
                self.assertEqual(rx[ICMP46][IP46error]
                                 [TCPerror].sport, sports[nbr])
                self.assertEqual(rx[ICMP46][IP46error]
                                 [TCPerror].dport, dports[nbr])

    def sourcenat_test_tcp_udp_conf(self, l4p, isV6=False):
        sports = [1234, 1235]
        dports = [6661, 6662]

        for nbr, remote_host in enumerate(self.pg1.remote_hosts):
            if isV6:
                IP46 = IPv6
                client_addr = self.pg0.remote_hosts[0].ip6
                remote_addr = self.pg1.remote_hosts[nbr].ip6
                src_nat_addr = self.pg2.remote_hosts[0].ip6
                exclude_prefix = ip_network(
                    "%s/100" % remote_addr, strict=False)
            else:
                IP46 = IP
                client_addr = self.pg0.remote_hosts[0].ip4
                remote_addr = self.pg1.remote_hosts[nbr].ip4
                src_nat_addr = self.pg2.remote_hosts[0].ip4
                exclude_prefix = ip_network(
                    "%s/16" % remote_addr, strict=False)
            # from pods to outside network
            p1 = (
                Ether(dst=self.pg0.local_mac,
                      src=self.pg0.remote_hosts[0].mac) /
                IP46(src=client_addr, dst=remote_addr) /
                l4p(sport=sports[nbr], dport=dports[nbr]) /
                Raw())

            self.vapi.cli("trace add pg-input 1")
            rxs = self.send_and_expect(
                self.pg0,
                p1 * N_PKTS,
                self.pg1)
            self.logger.info(self.vapi.cli("show trace max 1"))

            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].dst, remote_addr)
                self.assertEqual(rx[l4p].dport, dports[nbr])
                self.assertEqual(rx[IP46].src, src_nat_addr)
                sport = rx[l4p].sport

            # from outside to pods
            p2 = (
                Ether(dst=self.pg1.local_mac,
                      src=self.pg1.remote_hosts[nbr].mac) /
                IP46(src=remote_addr, dst=src_nat_addr) /
                l4p(sport=dports[nbr], dport=sport) /
                Raw())

            rxs = self.send_and_expect(
                self.pg1,
                p2 * N_PKTS,
                self.pg0)

            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].dst, client_addr)
                self.assertEqual(rx[l4p].dport, sports[nbr])
                self.assertEqual(rx[l4p].sport, dports[nbr])
                self.assertEqual(rx[IP46].src, remote_addr)

            # add remote host to exclude list
            self.vapi.cnat_snat_policy_add_del_exclude_pfx(
                prefix=exclude_prefix, is_add=1)
            self.vapi.cnat_session_purge()

            rxs = self.send_and_expect(
                self.pg0,
                p1 * N_PKTS,
                self.pg1)
            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].dst, remote_addr)
                self.assertEqual(rx[l4p].dport, dports[nbr])
                self.assertEqual(rx[IP46].src, client_addr)

            # remove remote host from exclude list
            self.vapi.cnat_snat_policy_add_del_exclude_pfx(
                prefix=exclude_prefix, is_add=0)
            self.vapi.cnat_session_purge()

            rxs = self.send_and_expect(
                self.pg0,
                p1 * N_PKTS,
                self.pg1)

            for rx in rxs:
                self.assert_packet_checksums_valid(rx)
                self.assertEqual(rx[IP46].dst, remote_addr)
                self.assertEqual(rx[l4p].dport, dports[nbr])
                self.assertEqual(rx[IP46].src, src_nat_addr)

            self.vapi.cnat_session_purge()


class TestCNatDHCP(VppTestCase):
    """ CNat Translation """
    extra_vpp_punt_config = ["cnat", "{",
                             "session-db-buckets", "64",
                             "session-cleanup-timeout", "0.1",
                             "session-max-age", "1",
                             "tcp-max-age", "1",
                             "scanner", "off", "}"]

    @classmethod
    def setUpClass(cls):
        super(TestCNatDHCP, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        super(TestCNatDHCP, cls).tearDownClass()

    def tearDown(self):
        for i in self.pg_interfaces:
            i.admin_down()
        super(TestCNatDHCP, self).tearDown()

    def create_translation(self, vip_pg, *args, is_v6=False):
        vip = Ep(sw_if_index=vip_pg.sw_if_index, is_v6=is_v6)
        paths = []
        for (src_pg, dst_pg) in args:
            paths.append(EpTuple(
                Ep.from_pg(src_pg, is_v6=is_v6),
                Ep.from_pg(dst_pg, is_v6=is_v6)
            ))
        t1 = VppCNatTranslation(self, TCP, vip, paths)
        t1.add_vpp_config()
        return t1

    def make_addr(self, sw_if_index, i, is_v6):
        if is_v6:
            return "fd01:%x::%u" % (sw_if_index, i + 1)
        else:
            return "172.16.%u.%u" % (sw_if_index, i)

    def make_prefix(self, sw_if_index, i, is_v6):
        if is_v6:
            return "%s/128" % self.make_addr(sw_if_index, i, is_v6)
        else:
            return "%s/32" % self.make_addr(sw_if_index, i, is_v6)

    def check_resolved(self, tr, vip_pg, *args, i=0, is_v6=False):
        qt1 = tr.query_vpp_config()
        self.assertEqual(str(qt1.vip.addr), self.make_addr(
            vip_pg.sw_if_index, i, is_v6))
        for (src_pg, dst_pg), path in zip(args, qt1.paths):
            if src_pg:
                self.assertEqual(str(path.src_ep.addr), self.make_addr(
                    src_pg.sw_if_index, i, is_v6))
            if dst_pg:
                self.assertEqual(str(path.dst_ep.addr), self.make_addr(
                    dst_pg.sw_if_index, i, is_v6))

    def config_ips(self, rng, is_add=1, is_v6=False):
        for pg, i in product(self.pg_interfaces, rng):
            self.vapi.sw_interface_add_del_address(
                sw_if_index=pg.sw_if_index,
                prefix=self.make_prefix(pg.sw_if_index, i, is_v6),
                is_add=is_add)

    def test_dhcp_v4(self):
        self.create_pg_interfaces(range(5))
        for i in self.pg_interfaces:
            i.admin_up()
        pglist = (self.pg0, (self.pg1, self.pg2), (self.pg1, self.pg4))
        t1 = self.create_translation(*pglist)
        self.config_ips([0])
        self.check_resolved(t1, *pglist)
        self.config_ips([1])
        self.config_ips([0], is_add=0)
        self.check_resolved(t1, *pglist, i=1)
        self.config_ips([1], is_add=0)
        t1.remove_vpp_config()

    def test_dhcp_v6(self):
        self.create_pg_interfaces(range(5))
        for i in self.pg_interfaces:
            i.admin_up()
        pglist = (self.pg0, (self.pg1, self.pg2), (self.pg1, self.pg4))
        t1 = self.create_translation(*pglist, is_v6=True)
        self.config_ips([0], is_v6=True)
        self.check_resolved(t1, *pglist, is_v6=True)
        self.config_ips([1], is_v6=True)
        self.config_ips([0], is_add=0, is_v6=True)
        self.check_resolved(t1, *pglist, i=1, is_v6=True)
        self.config_ips([1], is_add=0, is_v6=True)
        t1.remove_vpp_config()

    def test_dhcp_snat(self):
        self.create_pg_interfaces(range(1))
        for i in self.pg_interfaces:
            i.admin_up()
        self.vapi.cnat_set_snat_addresses(sw_if_index=self.pg0.sw_if_index)
        self.config_ips([0], is_v6=False)
        self.config_ips([0], is_v6=True)
        r = self.vapi.cnat_get_snat_addresses()
        self.assertEqual(str(r.snat_ip4), self.make_addr(
            self.pg0.sw_if_index, 0, False))
        self.assertEqual(str(r.snat_ip6), self.make_addr(
            self.pg0.sw_if_index, 0, True))
        self.config_ips([1], is_v6=False)
        self.config_ips([1], is_v6=True)
        self.config_ips([0], is_add=0, is_v6=False)
        self.config_ips([0], is_add=0, is_v6=True)
        r = self.vapi.cnat_get_snat_addresses()
        self.assertEqual(str(r.snat_ip4), self.make_addr(
            self.pg0.sw_if_index, 1, False))
        self.assertEqual(str(r.snat_ip6), self.make_addr(
            self.pg0.sw_if_index, 1, True))
        self.config_ips([1], is_add=0, is_v6=False)
        self.config_ips([1], is_add=0, is_v6=True)
        self.vapi.cnat_set_snat_addresses(sw_if_index=INVALID_INDEX)


if __name__ == '__main__':
    unittest.main(testRunner=VppTestRunner)