summaryrefslogtreecommitdiffstats
path: root/test/test_l2xc_multi_instance.py
blob: 2a6e41c8791e7e8fc2e2a809fa6800e74fdba79d (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
#!/usr/bin/env python3
"""L2XC Multi-instance Test Case HLD:

**NOTES:**
    - higher number (more than 15) of pg-l2 interfaces causes problems => only
      14 pg-l2 interfaces and 10 cross-connects are tested
    - jumbo packets in configuration with 14 l2-pg interfaces leads to
      problems too

**config 1**
    - add 14 pg-l2 interfaces
    - add 10 cross-connects (two cross-connects per pair of l2-pg interfaces)

**test 1**
    - send L2 MAC frames between all pairs of pg-l2 interfaces

**verify 1**
    - all packets received correctly in case of cross-connected l2-pg
      interfaces
    - no packet received in case of not cross-connected l2-pg interfaces

**config 2**
    - delete 4 cross-connects

**test 2**
    - send L2 MAC frames between all pairs of pg-l2 interfaces

**verify 2**
    - all packets received correctly in case of cross-connected l2-pg
      interfaces
    - no packet received in case of not cross-connected l2-pg interfaces

**config 3**
    - add new 4 cross-connects

**test 3**
    - send L2 MAC frames between all pairs of pg-l2 interfaces

**verify 3**
    - all packets received correctly in case of cross-connected l2-pg
      interfaces
    - no packet received in case of not cross-connected l2-pg interfaces

**config 4**
    - delete 10 cross-connects

**test 4**
    - send L2 MAC frames between all pairs of pg-l2 interfaces

**verify 4**
    - no packet received on all of l2-pg interfaces (no cross-connect created)
"""

import unittest
import random

from scapy.packet import Raw
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP

from framework import VppTestCase, VppTestRunner
from util import Host, ppp


class TestL2xcMultiInst(VppTestCase):
    """ L2XC Multi-instance Test Case """

    @classmethod
    def setUpClass(cls):
        """
        Perform standard class setup (defined by class method setUpClass in
        class VppTestCase) before running the test case, set test case related
        variables and configure VPP.
        """
        super(TestL2xcMultiInst, cls).setUpClass()

        try:
            # Create pg interfaces
            cls.create_pg_interfaces(range(14))

            # Packet flows mapping pg0 -> pg1 etc.
            cls.flows = dict()
            for i in range(len(cls.pg_interfaces)):
                delta = 1 if i % 2 == 0 else -1
                cls.flows[cls.pg_interfaces[i]] =\
                    [cls.pg_interfaces[i + delta]]

            # Mapping between packet-generator index and lists of test hosts
            cls.hosts_by_pg_idx = dict()
            for pg_if in cls.pg_interfaces:
                cls.hosts_by_pg_idx[pg_if.sw_if_index] = []

            # Create test host entries
            cls.create_hosts(70)

            # Packet sizes - jumbo packet (9018 bytes) skipped
            cls.pg_if_packet_sizes = [64, 512, 1518]

            # Set up all interfaces
            for i in cls.pg_interfaces:
                i.admin_up()

            # Create list of x-connected pg_interfaces
            cls.pg_in_xc = list()

            # Create list of not x-connected pg_interfaces
            cls.pg_not_in_xc = list()
            for pg_if in cls.pg_interfaces:
                cls.pg_not_in_xc.append(pg_if)

        except Exception:
            super(TestL2xcMultiInst, cls).tearDownClass()
            raise

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

    def setUp(self):
        """
        Clear trace and packet infos before running each test.
        """
        super(TestL2xcMultiInst, self).setUp()
        self.reset_packet_infos()

    def tearDown(self):
        """
        Show various debug prints after each test.
        """
        super(TestL2xcMultiInst, self).tearDown()

    def show_commands_at_teardown(self):
        self.logger.info(self.vapi.ppcli("show l2patch"))

    @classmethod
    def create_hosts(cls, count):
        """
        Create required number of host MAC addresses and distribute them among
        interfaces. Create host IPv4 address for every host MAC address.

        :param int count: Number of hosts to create MAC/IPv4 addresses for.
        """
        n_int = len(cls.pg_interfaces)
        macs_per_if = count // n_int
        i = -1
        for pg_if in cls.pg_interfaces:
            i += 1
            start_nr = macs_per_if * i
            end_nr = count if i == (n_int - 1) else macs_per_if * (i + 1)
            hosts = cls.hosts_by_pg_idx[pg_if.sw_if_index]
            for j in range(start_nr, end_nr):
                host = Host(
                    "00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j),
                    "172.17.1%02u.%u" % (pg_if.sw_if_index, j))
                hosts.append(host)

    def create_xconnects(self, count, start=0):
        """
        Create required number of cross-connects (always two cross-connects per
        pair of packet-generator interfaces).

        :param int count: Number of cross-connects to be created.
        :param int start: Starting index of packet-generator interfaces. \
        (Default value = 0)
        """
        for i in range(count):
            rx_if = self.pg_interfaces[i + start]
            delta = 1 if i % 2 == 0 else -1
            tx_if = self.pg_interfaces[i + start + delta]
            self.vapi.sw_interface_set_l2_xconnect(rx_if.sw_if_index,
                                                   tx_if.sw_if_index, 1)
            self.logger.info("Cross-connect from %s to %s created"
                             % (tx_if.name, rx_if.name))
            if self.pg_in_xc.count(rx_if) == 0:
                self.pg_in_xc.append(rx_if)
            if self.pg_not_in_xc.count(rx_if) == 1:
                self.pg_not_in_xc.remove(rx_if)

    def delete_xconnects(self, count, start=0):
        """
        Delete required number of cross-connects (always two cross-connects per
        pair of packet-generator interfaces).

        :param int count: Number of cross-connects to be deleted.
        :param int start: Starting index of packet-generator interfaces. \
        (Default value = 0)
        """
        for i in range(count):
            rx_if = self.pg_interfaces[i + start]
            delta = 1 if i % 2 == 0 else -1
            tx_if = self.pg_interfaces[i + start + delta]
            self.vapi.sw_interface_set_l2_xconnect(rx_if.sw_if_index,
                                                   tx_if.sw_if_index, 0)
            self.logger.info("Cross-connect from %s to %s deleted"
                             % (tx_if.name, rx_if.name))
            if self.pg_not_in_xc.count(rx_if) == 0:
                self.pg_not_in_xc.append(rx_if)
            if self.pg_in_xc.count(rx_if) == 1:
                self.pg_in_xc.remove(rx_if)

    def create_stream(self, src_if, packet_sizes):
        """
        Create input packet stream for defined interface using hosts list.

        :param object src_if: Interface to create packet stream for.
        :param list packet_sizes: List of required packet sizes.
        :return: Stream of packets.
        """
        pkts = []
        src_hosts = self.hosts_by_pg_idx[src_if.sw_if_index]
        for dst_if in self.flows[src_if]:
            dst_hosts = self.hosts_by_pg_idx[dst_if.sw_if_index]
            n_int = len(dst_hosts)
            for i in range(0, n_int):
                dst_host = dst_hosts[i]
                src_host = random.choice(src_hosts)
                pkt_info = self.create_packet_info(src_if, dst_if)
                payload = self.info_to_payload(pkt_info)
                p = (Ether(dst=dst_host.mac, src=src_host.mac) /
                     IP(src=src_host.ip4, dst=dst_host.ip4) /
                     UDP(sport=1234, dport=1234) /
                     Raw(payload))
                pkt_info.data = p.copy()
                size = random.choice(packet_sizes)
                self.extend_packet(p, size)
                pkts.append(p)
        self.logger.debug("Input stream created for port %s. Length: %u pkt(s)"
                          % (src_if.name, len(pkts)))
        return pkts

    def verify_capture(self, pg_if, capture):
        """
        Verify captured input packet stream for defined interface.

        :param object pg_if: Interface to verify captured packet stream for.
        :param list capture: Captured packet stream.
        """
        last_info = dict()
        for i in self.pg_interfaces:
            last_info[i.sw_if_index] = None
        dst_sw_if_index = pg_if.sw_if_index
        for packet in capture:
            payload_info = self.payload_to_info(packet[Raw])
            try:
                ip = packet[IP]
                udp = packet[UDP]
                packet_index = payload_info.index
                self.assertEqual(payload_info.dst, dst_sw_if_index)
                self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
                                  (pg_if.name, payload_info.src, packet_index))
                next_info = self.get_next_packet_info_for_interface2(
                    payload_info.src, dst_sw_if_index,
                    last_info[payload_info.src])
                last_info[payload_info.src] = next_info
                self.assertTrue(next_info is not None)
                self.assertEqual(packet_index, next_info.index)
                saved_packet = next_info.data
                # Check standard fields
                self.assertEqual(ip.src, saved_packet[IP].src)
                self.assertEqual(ip.dst, saved_packet[IP].dst)
                self.assertEqual(udp.sport, saved_packet[UDP].sport)
                self.assertEqual(udp.dport, saved_packet[UDP].dport)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise
        for i in self.pg_interfaces:
            remaining_packet = self.get_next_packet_info_for_interface2(
                i, dst_sw_if_index, last_info[i.sw_if_index])
            self.assertTrue(
                remaining_packet is None,
                "Port %u: Packet expected from source %u didn't arrive" %
                (dst_sw_if_index, i.sw_if_index))

    def run_verify_test(self):
        """
        Create packet streams for all configured l2-pg interfaces, send all \
        prepared packet streams and verify that:
            - all packets received correctly on all pg-l2 interfaces assigned
              to cross-connects
            - no packet received on all pg-l2 interfaces not assigned to
              cross-connects

        :raise RuntimeError: if no packet captured on l2-pg interface assigned
                             to the cross-connect or if any packet is captured
                             on l2-pg interface not assigned to the
                             cross-connect.
        """
        # Test
        # Create incoming packet streams for packet-generator interfaces
        for pg_if in self.pg_interfaces:
            pkts = self.create_stream(pg_if, self.pg_if_packet_sizes)
            pg_if.add_stream(pkts)

        # Enable packet capture and start packet sending
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Verify
        # Verify outgoing packet streams per packet-generator interface
        for pg_if in self.pg_interfaces:
            if pg_if in self.pg_in_xc:
                capture = pg_if.get_capture(
                    remark="interface is a cross-connect sink")
                self.verify_capture(pg_if, capture)
            elif pg_if in self.pg_not_in_xc:
                pg_if.assert_nothing_captured(
                    remark="interface is not a cross-connect sink")
            else:
                raise Exception("Unexpected interface: %s" % pg_if.name)

    def test_l2xc_inst_01(self):
        """ L2XC Multi-instance test 1 - create 10 cross-connects
        """
        # Config 1
        # Create 10 cross-connects
        self.create_xconnects(10)

        # Test 1
        self.run_verify_test()

    def test_l2xc_inst_02(self):
        """ L2XC Multi-instance test 2 - delete 4 cross-connects
        """
        # Config 2
        # Delete 4 cross-connects
        self.delete_xconnects(4)

        # Test 2
        self.run_verify_test()

    def test_l2xc_inst_03(self):
        """ L2BD Multi-instance 3 - add new 4 cross-connects
        """
        # Config 3
        # Add new 4 cross-connects
        self.create_xconnects(4, start=10)

        # Test 3
        self.run_verify_test()

    def test_l2xc_inst_04(self):
        """ L2XC Multi-instance test 4 - delete 10 cross-connects
        """
        # Config 4
        # Delete 10 cross-connects
        self.delete_xconnects(10, start=4)

        # Test 4
        self.run_verify_test()


if __name__ == '__main__':
    unittest.main(testRunner=VppTestRunner)
"o">: paren--; if (is_paren_delimited && paren == 0) goto done; break; case ' ': case '\t': case '\n': case '\r': if (!is_paren_delimited) { unformat_put_input (input); goto done; } break; default: if (!is_paren_delimited && c == delimiter_character) { unformat_put_input (input); goto done; } } if (add_to_vector) vec_add1 (s, c); } done: if (string_return) { /* Match the string { END-OF-INPUT as a single brace. */ if (c == UNFORMAT_END_OF_INPUT && vec_len (s) == 0 && paren == 1) vec_add1 (s, '{'); /* Don't match null string. */ if (c == UNFORMAT_END_OF_INPUT && vec_len (s) == 0) return 0; /* Null terminate C string. */ if (format_character == 's') vec_add1 (s, 0); *string_return = s; } else vec_free (s); /* just to make sure */ return 1; } uword unformat_hex_string (unformat_input_t * input, va_list * va) { u8 **hexstring_return = va_arg (*va, u8 **); u8 *s; uword n, d, c; n = 0; d = 0; s = 0; while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT) { if (c >= '0' && c <= '9') d = 16 * d + c - '0'; else if (c >= 'a' && c <= 'f') d = 16 * d + 10 + c - 'a'; else if (c >= 'A' && c <= 'F') d = 16 * d + 10 + c - 'A'; else { unformat_put_input (input); break; } n++; if (n == 2) { vec_add1 (s, d); n = d = 0; } } /* Hex string must have even number of digits. */ if (n % 2) { vec_free (s); return 0; } /* Make sure something was processed. */ else if (s == 0) { return 0; } *hexstring_return = s; return 1; } /* unformat (input "foo%U", unformat_eof) matches terminal foo only */ uword unformat_eof (unformat_input_t * input, va_list * va) { return unformat_check_input (input) == UNFORMAT_END_OF_INPUT; } /* Parse a token containing given set of characters. */ uword unformat_token (unformat_input_t * input, va_list * va) { u8 *token_chars = va_arg (*va, u8 *); u8 **string_return = va_arg (*va, u8 **); u8 *s, map[256]; uword i, c; if (!token_chars) token_chars = (u8 *) "a-zA-Z0-9_"; memset (map, 0, sizeof (map)); for (s = token_chars; *s;) { /* Parse range. */ if (s[0] < s[2] && s[1] == '-') { for (i = s[0]; i <= s[2]; i++) map[i] = 1; s = s + 3; } else { map[s[0]] = 1; s = s + 1; } } s = 0; while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT) { if (!map[c]) { unformat_put_input (input); break; } vec_add1 (s, c); } if (vec_len (s) == 0) return 0; *string_return = s; return 1; } /* Unformat (parse) function which reads a %s string and converts it to and unformat_input_t. */ uword unformat_input (unformat_input_t * i, va_list * args) { unformat_input_t *sub_input = va_arg (*args, unformat_input_t *); u8 *s; if (unformat (i, "%v", &s)) { unformat_init_vector (sub_input, s); return 1; } return 0; } /* Parse a line ending with \n and return it. */ uword unformat_line (unformat_input_t * i, va_list * va) { u8 *line = 0, **result = va_arg (*va, u8 **); uword c; while ((c = unformat_get_input (i)) != '\n' && c != UNFORMAT_END_OF_INPUT) { vec_add1 (line, c); } *result = line; return vec_len (line); } /* Parse a line ending with \n and return it as an unformat_input_t. */ uword unformat_line_input (unformat_input_t * i, va_list * va) { unformat_input_t *result = va_arg (*va, unformat_input_t *); u8 *line; if (!unformat_user (i, unformat_line, &line)) return 0; unformat_init_vector (result, line); return 1; } /* Values for is_signed. */ #define UNFORMAT_INTEGER_SIGNED 1 #define UNFORMAT_INTEGER_UNSIGNED 0 static uword unformat_integer (unformat_input_t * input, va_list * va, uword base, uword is_signed, uword data_bytes) { uword c, digit; uword value = 0; uword n_digits = 0; uword n_input = 0; uword sign = 0; /* We only support bases <= 64. */ if (base < 2 || base > 64) goto error; while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT) { switch (c) { case '-': if (n_input == 0) { if (is_signed) { sign = 1; goto next_digit; } else /* Leading sign for unsigned number. */ goto error; } /* Sign after input (e.g. 100-200). */ goto put_input_done; case '+': if (n_input > 0) goto put_input_done; sign = 0; goto next_digit; case '0' ... '9': digit = c - '0'; break; case 'a' ... 'z': digit = 10 + (c - 'a'); break; case 'A' ... 'Z': digit = 10 + (base >= 36 ? 26 : 0) + (c - 'A'); break; case '/': digit = 62; break; case '?': digit = 63; break; default: goto put_input_done; } if (digit >= base) { put_input_done: unformat_put_input (input); goto done; } { uword new_value = base * value + digit; /* Check for overflow. */ if (new_value < value) goto error; value = new_value; } n_digits += 1; next_digit: n_input++; } done: if (sign) value = -value; if (n_digits > 0) { void *v = va_arg (*va, void *); if (data_bytes == ~0) data_bytes = sizeof (int); switch (data_bytes) { case 1: *(u8 *) v = value; break; case 2: *(u16 *) v = value; break; case 4: *(u32 *) v = value; break; case 8: *(u64 *) v = value; break; default: goto error; } return 1; } error: return 0; } /* Return x 10^n */ static f64 times_power_of_ten (f64 x, int n) { if (n >= 0) { static f64 t[8] = { 1e+0, 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, }; while (n >= 8) { x *= 1e+8; n -= 8; } return x * t[n]; } else { static f64 t[8] = { 1e-0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, }; while (n <= -8) { x *= 1e-8; n += 8; } return x * t[-n]; } } static uword unformat_float (unformat_input_t * input, va_list * va) { uword c; u64 values[3]; uword n_digits[3], value_index = 0; uword signs[2], sign_index = 0; uword n_input = 0; memset (values, 0, sizeof (values)); memset (n_digits, 0, sizeof (n_digits)); memset (signs, 0, sizeof (signs)); while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT) { switch (c) { case '-': if (value_index == 2 && n_digits[2] == 0) /* sign of exponent: it's ok. */ ; else if (value_index < 2 && n_digits[0] > 0) { /* 123- */ unformat_put_input (input); goto done; } else if (n_input > 0) goto error; signs[sign_index++] = 1; goto next_digit; case '+': if (value_index == 2 && n_digits[2] == 0) /* sign of exponent: it's ok. */ ; else if (value_index < 2 && n_digits[0] > 0) { /* 123+ */ unformat_put_input (input); goto done; } else if (n_input > 0) goto error; signs[sign_index++] = 0; goto next_digit; case 'e': case 'E': if (n_input == 0) goto error; value_index = 2; sign_index = 1; break; case '.': if (value_index > 0) goto error; value_index = 1; break; case '0' ... '9': { u64 tmp; tmp = values[value_index] * 10 + c - '0'; /* Check for overflow. */ if (tmp < values[value_index]) goto error; values[value_index] = tmp; n_digits[value_index] += 1; } break; default: unformat_put_input (input); goto done; } next_digit: n_input++; } done: { f64 f_values[2], *value_return; word expon; /* Must have either whole or fraction digits. */ if (n_digits[0] + n_digits[1] <= 0) goto error; f_values[0] = values[0]; if (signs[0]) f_values[0] = -f_values[0]; f_values[1] = values[1]; f_values[1] = times_power_of_ten (f_values[1], -n_digits[1]); f_values[0] += f_values[1]; expon = values[2]; if (signs[1]) expon = -expon; f_values[0] = times_power_of_ten (f_values[0], expon); value_return = va_arg (*va, f64 *); *value_return = f_values[0]; return 1; } error: return 0; } static const char * match_input_with_format (unformat_input_t * input, const char *f) { uword cf, ci; ASSERT (*f != 0); while (1) { cf = *f; if (cf == 0 || cf == '%' || cf == ' ') break; f++; ci = unformat_get_input (input); if (cf != ci) return 0; } return f; } static const char * do_percent (unformat_input_t * input, va_list * va, const char *f) { uword cf, n, data_bytes = ~0; cf = *f++; switch (cf) { default: break; case 'w': /* Word types. */ cf = *f++; data_bytes = sizeof (uword); break; case 'l': cf = *f++; if (cf == 'l') { cf = *f++; data_bytes = sizeof (long long); } else { data_bytes = sizeof (long); } break; case 'L': cf = *f++; data_bytes = sizeof (long long); break; } n = 0; switch (cf) { case 'D': data_bytes = va_arg (*va, int); case 'd': n = unformat_integer (input, va, 10, UNFORMAT_INTEGER_SIGNED, data_bytes); break; case 'u': n = unformat_integer (input, va, 10, UNFORMAT_INTEGER_UNSIGNED, data_bytes); break; case 'b': n = unformat_integer (input, va, 2, UNFORMAT_INTEGER_UNSIGNED, data_bytes); break; case 'o': n = unformat_integer (input, va, 8, UNFORMAT_INTEGER_UNSIGNED, data_bytes); break; case 'X': data_bytes = va_arg (*va, int); case 'x': n = unformat_integer (input, va, 16, UNFORMAT_INTEGER_UNSIGNED, data_bytes); break; case 'f': n = unformat_float (input, va); break; case 's': case 'v': n = unformat_string (input, f[0], cf, va); break; case 'U': { unformat_function_t *f = va_arg (*va, unformat_function_t *); n = f (input, va); } break; case '=': case '|': { int *var = va_arg (*va, int *); uword val = va_arg (*va, int); if (cf == '|') val |= *var; *var = val; n = 1; } break; } return n ? f : 0; } uword unformat_skip_white_space (unformat_input_t * input) { uword n = 0; uword c; while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT) { if (!is_white_space (c)) { unformat_put_input (input); break; } n++; } return n; } uword va_unformat (unformat_input_t * input, const char *fmt, va_list * va) { const char *f; uword input_matches_format; uword default_skip_input_white_space; uword n_input_white_space_skipped; uword last_non_white_space_match_percent; uword last_non_white_space_match_format; vec_add1_aligned (input->buffer_marks, input->index, sizeof (input->buffer_marks[0])); f = fmt; default_skip_input_white_space = 1; input_matches_format = 0; last_non_white_space_match_percent = 0; last_non_white_space_match_format = 0; while (1) { char cf; uword is_percent, skip_input_white_space; cf = *f; is_percent = 0; /* Always skip input white space at start of format string. Otherwise use default skip value which can be changed by %_ (see below). */ skip_input_white_space = f == fmt || default_skip_input_white_space; /* Spaces in format request skipping input white space. */ if (is_white_space (cf)) { skip_input_white_space = 1; /* Multiple format spaces are equivalent to a single white space. */ while (is_white_space (*++f)) ; } else if (cf == '%') { /* %_ toggles whether or not to skip input white space. */ switch (*++f) { case '_': default_skip_input_white_space = !default_skip_input_white_space; f++; /* For transition from skip to no-skip in middle of format string, skip input white space. For example, the following matches: fmt = "%_%d.%d%_->%_%d.%d%_" input "1.2 -> 3.4" Without this the space after -> does not get skipped. */ if (!default_skip_input_white_space && !(f == fmt + 2 || *f == 0)) unformat_skip_white_space (input); continue; /* %% means match % */ case '%': break; /* % at end of format string. */ case 0: goto parse_fail; default: is_percent = 1; break; } } n_input_white_space_skipped = 0; if (skip_input_white_space) n_input_white_space_skipped = unformat_skip_white_space (input); /* End of format string. */ if (cf == 0) { /* Force parse error when format string ends and input is not white or at end. As an example, this is to prevent format "foo" from matching input "food". The last_non_white_space_match_percent is to make "foo %d" match input "foo 10,bletch" with %d matching 10. */ if (skip_input_white_space && !last_non_white_space_match_percent && !last_non_white_space_match_format && n_input_white_space_skipped == 0 && input->index != UNFORMAT_END_OF_INPUT) goto parse_fail; break; } last_non_white_space_match_percent = is_percent; last_non_white_space_match_format = 0; /* Explicit spaces in format must match input white space. */ if (cf == ' ' && !default_skip_input_white_space) { if (n_input_white_space_skipped == 0) goto parse_fail; } else if (is_percent) { if (!(f = do_percent (input, va, f))) goto parse_fail; } else { const char *g = match_input_with_format (input, f); if (!g) goto parse_fail; last_non_white_space_match_format = g > f; f = g; } } input_matches_format = 1; parse_fail: /* Rewind buffer marks. */ { uword l = vec_len (input->buffer_marks); /* If we did not match back up buffer to last mark. */ if (!input_matches_format) input->index = input->buffer_marks[l - 1]; _vec_len (input->buffer_marks) = l - 1; } return input_matches_format; } uword unformat (unformat_input_t * input, const char *fmt, ...) { va_list va; uword result; va_start (va, fmt); result = va_unformat (input, fmt, &va); va_end (va); return result; } uword unformat_user (unformat_input_t * input, unformat_function_t * func, ...) { va_list va; uword result, l; /* Save place in input buffer in case parse fails. */ l = vec_len (input->buffer_marks); vec_add1_aligned (input->buffer_marks, input->index, sizeof (input->buffer_marks[0])); va_start (va, func); result = func (input, &va); va_end (va); if (!result && input->index != UNFORMAT_END_OF_INPUT) input->index = input->buffer_marks[l]; _vec_len (input->buffer_marks) = l; return result; } /* Setup for unformat of Unix style command line. */ void unformat_init_command_line (unformat_input_t * input, char *argv[]) { uword i; unformat_init (input, 0, 0); /* Concatenate argument strings with space in between. */ for (i = 1; argv[i]; i++) { vec_add (input->buffer, argv[i], strlen (argv[i])); if (argv[i + 1]) vec_add1 (input->buffer, ' '); } } void unformat_init_string (unformat_input_t * input, char *string, int string_len) { unformat_init (input, 0, 0); if (string_len > 0) vec_add (input->buffer, string, string_len); } void unformat_init_vector (unformat_input_t * input, u8 * vector_string) { unformat_init (input, 0, 0); input->buffer = vector_string; } #ifdef CLIB_UNIX static uword clib_file_fill_buffer (unformat_input_t * input) { int fd = pointer_to_uword (input->fill_buffer_arg); uword l, n; l = vec_len (input->buffer); vec_resize (input->buffer, 4096); n = read (fd, input->buffer + l, 4096); if (n > 0) _vec_len (input->buffer) = l + n; if (n <= 0) return UNFORMAT_END_OF_INPUT; else return input->index; } void unformat_init_clib_file (unformat_input_t * input, int file_descriptor) { unformat_init (input, clib_file_fill_buffer, uword_to_pointer (file_descriptor, void *)); } /* Take input from Unix environment variable. */ uword unformat_init_unix_env (unformat_input_t * input, char *var) { char *val = getenv (var); if (val) unformat_init_string (input, val, strlen (val)); return val != 0; } #endif /* CLIB_UNIX */ /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */