]> git.proxmox.com Git - mirror_ovs.git/blame - utilities/ovs-ofctl.c
ofp-util: New data structure for mapping between table names and numbers.
[mirror_ovs.git] / utilities / ovs-ofctl.c
CommitLineData
064af421 1/*
04f48a68 2 * Copyright (c) 2008-2017 Nicira, Inc.
064af421 3 *
a14bc59f
BP
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
064af421 7 *
a14bc59f
BP
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
064af421
BP
15 */
16
17#include <config.h>
2b07c8b1 18#include <ctype.h>
064af421
BP
19#include <errno.h>
20#include <getopt.h>
21#include <inttypes.h>
bd6b7545 22#include <sys/socket.h>
064af421 23#include <net/if.h>
064af421 24#include <signal.h>
064af421
BP
25#include <stdlib.h>
26#include <string.h>
27#include <unistd.h>
71d1b763 28#include <fcntl.h>
064af421
BP
29#include <sys/stat.h>
30#include <sys/time.h>
31
10a24935 32#include "byte-order.h"
09246b99 33#include "classifier.h"
064af421 34#include "command-line.h"
1eb85ef5 35#include "daemon.h"
ef7b593b 36#include "colors.h"
064af421
BP
37#include "compiler.h"
38#include "dirs.h"
d271907f 39#include "dp-packet.h"
8a777cf6 40#include "fatal-signal.h"
09246b99 41#include "nx-match.h"
064af421 42#include "odp-util.h"
a53a8efa 43#include "ofp-version-opt.h"
63d347ce 44#include "ofproto/ofproto.h"
064af421
BP
45#include "openflow/nicira-ext.h"
46#include "openflow/openflow.h"
d271907f
BW
47#include "openvswitch/dynamic-string.h"
48#include "openvswitch/meta-flow.h"
b598f214 49#include "openvswitch/ofp-actions.h"
d271907f
BW
50#include "openvswitch/ofp-errors.h"
51#include "openvswitch/ofp-msgs.h"
25d436fb 52#include "openvswitch/ofp-print.h"
d271907f
BW
53#include "openvswitch/ofp-util.h"
54#include "openvswitch/ofp-parse.h"
55#include "openvswitch/ofpbuf.h"
50f96b10 56#include "openvswitch/shash.h"
d271907f
BW
57#include "openvswitch/vconn.h"
58#include "openvswitch/vlog.h"
0c3d5fc8 59#include "packets.h"
14249c02 60#include "pcap-file.h"
fd016ae3 61#include "openvswitch/poll-loop.h"
064af421 62#include "random.h"
b598f214 63#include "sort.h"
fe55ad15 64#include "stream-ssl.h"
c3f25389 65#include "socket-util.h"
064af421 66#include "timeval.h"
1eb85ef5 67#include "unixctl.h"
064af421 68#include "util.h"
064af421 69
d98e6007 70VLOG_DEFINE_THIS_MODULE(ofctl);
064af421 71
06d4d4b6
JR
72/* --bundle: Use OpenFlow 1.3+ bundle for making the flow table change atomic.
73 * NOTE: If OpenFlow 1.3 or higher is not selected with the '-O' option,
74 * OpenFlow 1.4 will be implicitly selected. Also the flow mod will use
75 * OpenFlow 1.4, so the semantics may be different (see the comment in
76 * parse_options() for details).
db5076ee
JR
77 */
78static bool bundle = false;
79
20174b74
QM
80/* --color: Use color markers. */
81static bool enable_color;
82
1f4a7252
RM
83/* --read-only: Do not execute read only commands. */
84static bool read_only;
85
102ce766
EJ
86/* --strict: Use strict matching for flow mod commands? Additionally governs
87 * use of nx_pull_match() instead of nx_pull_match_loose() in parse-nx-match.
88 */
675febfa 89static bool strict;
064af421 90
88b87a36
JS
91/* --may-create: If true, the mod-group command creates a group that does not
92 * yet exist; otherwise, such a command has no effect. */
93static bool may_create;
94
96989efc 95/* --readd: If true, on replace-flows, re-add even flows that have not changed
c4ea79bf
BP
96 * (to reset flow counters). */
97static bool readd;
98
27527aa0
BP
99/* -F, --flow-format: Allowed protocols. By default, any protocol is
100 * allowed. */
101static enum ofputil_protocol allowed_protocols = OFPUTIL_P_ANY;
88ca35ee 102
54834960
EJ
103/* -P, --packet-in-format: Packet IN format to use in monitor and snoop
104 * commands. Either one of NXPIF_* to force a particular packet_in format, or
105 * -1 to let ovs-ofctl choose the default. */
106static int preferred_packet_in_format = -1;
107
4f564f8d
BP
108/* -m, --more: Additional verbosity for ofp-print functions. */
109static int verbosity;
110
0c9560b7
BP
111/* --timestamp: Print a timestamp before each received packet on "monitor" and
112 * "snoop" command? */
113static bool timestamp;
114
19945013
BP
115/* --unixctl-path: Path to use for unixctl server, for "monitor" and "snoop"
116 commands. */
117static char *unixctl_path;
118
bdcc5925
BP
119/* --sort, --rsort: Sort order. */
120enum sort_order { SORT_ASC, SORT_DESC };
121struct sort_criterion {
122 const struct mf_field *field; /* NULL means to sort by priority. */
123 enum sort_order order;
124};
125static struct sort_criterion *criteria;
126static size_t n_criteria, allocated_criteria;
127
50f96b10
BP
128/* --names, --no-names: Show port names in output and accept port numbers in
129 * input. (When neither is specified, the default is to accept port numbers
130 * but, for backward compatibility, not to show them unless this is an
131 * interactive console session.) */
132static int use_port_names = -1;
133static const struct ofputil_port_map *ports_to_accept(const char *vconn_name);
134static const struct ofputil_port_map *ports_to_show(const char *vconn_name);
135static bool should_accept_ports(void);
136static bool should_show_ports(void);
137
1b3758c3
BP
138/* --stats, --no-stats: Show statistics in flow dumps? */
139static int show_stats = 1;
140
d060b8ab
BP
141/* --pcap: Makes "compose-packet" print a pcap on stdout. */
142static int print_pcap = 0;
143
5f383751 144static const struct ovs_cmdl_command *get_all_commands(void);
064af421 145
cab50449 146OVS_NO_RETURN static void usage(void);
675febfa 147static void parse_options(int argc, char *argv[]);
064af421 148
675febfa
BP
149int
150main(int argc, char *argv[])
064af421 151{
1636c761 152 struct ovs_cmdl_context ctx = { .argc = 0, };
064af421 153 set_program_name(argv[0]);
5e3ee29d 154 service_start(&argc, &argv);
675febfa 155 parse_options(argc, argv);
8a777cf6 156 fatal_ignore_sigpipe();
1636c761
RB
157 ctx.argc = argc - optind;
158 ctx.argv = argv + optind;
e91b927d
AZ
159
160 daemon_become_new_user(false);
1f4a7252
RM
161 if (read_only) {
162 ovs_cmdl_run_command_read_only(&ctx, get_all_commands());
163 } else {
164 ovs_cmdl_run_command(&ctx, get_all_commands());
165 }
064af421
BP
166 return 0;
167}
168
bdcc5925
BP
169static void
170add_sort_criterion(enum sort_order order, const char *field)
171{
172 struct sort_criterion *sc;
173
174 if (n_criteria >= allocated_criteria) {
175 criteria = x2nrealloc(criteria, &allocated_criteria, sizeof *criteria);
176 }
177
178 sc = &criteria[n_criteria++];
179 if (!field || !strcasecmp(field, "priority")) {
180 sc->field = NULL;
181 } else {
182 sc->field = mf_from_name(field);
183 if (!sc->field) {
184 ovs_fatal(0, "%s: unknown field name", field);
185 }
186 }
187 sc->order = order;
188}
189
064af421 190static void
675febfa 191parse_options(int argc, char *argv[])
064af421
BP
192{
193 enum {
87c84891 194 OPT_STRICT = UCHAR_MAX + 1,
c4ea79bf 195 OPT_READD,
0c9560b7 196 OPT_TIMESTAMP,
bdcc5925
BP
197 OPT_SORT,
198 OPT_RSORT,
19945013 199 OPT_UNIXCTL,
db5076ee 200 OPT_BUNDLE,
20174b74 201 OPT_COLOR,
88b87a36 202 OPT_MAY_CREATE,
1f4a7252 203 OPT_READ_ONLY,
1eb85ef5 204 DAEMON_OPTION_ENUMS,
a53a8efa 205 OFP_VERSION_OPTION_ENUMS,
e18a1d08
ER
206 VLOG_OPTION_ENUMS,
207 SSL_OPTION_ENUMS,
064af421 208 };
07fc4ed3 209 static const struct option long_options[] = {
e3c17733
BP
210 {"timeout", required_argument, NULL, 't'},
211 {"strict", no_argument, NULL, OPT_STRICT},
c4ea79bf 212 {"readd", no_argument, NULL, OPT_READD},
e3c17733 213 {"flow-format", required_argument, NULL, 'F'},
54834960 214 {"packet-in-format", required_argument, NULL, 'P'},
e3c17733 215 {"more", no_argument, NULL, 'm'},
0c9560b7 216 {"timestamp", no_argument, NULL, OPT_TIMESTAMP},
bdcc5925
BP
217 {"sort", optional_argument, NULL, OPT_SORT},
218 {"rsort", optional_argument, NULL, OPT_RSORT},
50f96b10
BP
219 {"names", no_argument, &use_port_names, 1},
220 {"no-names", no_argument, &use_port_names, 0},
1b3758c3
BP
221 {"stats", no_argument, &show_stats, 1},
222 {"no-stats", no_argument, &show_stats, 0},
19945013 223 {"unixctl", required_argument, NULL, OPT_UNIXCTL},
e3c17733 224 {"help", no_argument, NULL, 'h'},
66fa2c88 225 {"option", no_argument, NULL, 'o'},
db5076ee 226 {"bundle", no_argument, NULL, OPT_BUNDLE},
20174b74 227 {"color", optional_argument, NULL, OPT_COLOR},
88b87a36 228 {"may-create", no_argument, NULL, OPT_MAY_CREATE},
d060b8ab 229 {"pcap", no_argument, &print_pcap, 1},
1f4a7252 230 {"read-only", no_argument, NULL, OPT_READ_ONLY},
1eb85ef5 231 DAEMON_LONG_OPTIONS,
a53a8efa 232 OFP_VERSION_LONG_OPTIONS,
87c84891 233 VLOG_LONG_OPTIONS,
bf8f2167 234 STREAM_SSL_LONG_OPTIONS,
e3c17733 235 {NULL, 0, NULL, 0},
064af421 236 };
5f383751 237 char *short_options = ovs_cmdl_long_options_to_short_options(long_options);
37923ac7
BP
238 uint32_t versions;
239 enum ofputil_protocol version_protocols;
064af421 240
6dc53744
BP
241 /* For now, ovs-ofctl only enables OpenFlow 1.0 by default. This is
242 * because ovs-ofctl implements command such as "add-flow" as raw OpenFlow
243 * requests, but those requests have subtly different semantics in
244 * different OpenFlow versions. For example:
245 *
246 * - In OpenFlow 1.0, a "mod-flow" operation that does not find any
247 * existing flow to modify adds a new flow.
248 *
249 * - In OpenFlow 1.1, a "mod-flow" operation that does not find any
250 * existing flow to modify adds a new flow, but only if the mod-flow
251 * did not match on the flow cookie.
252 *
253 * - In OpenFlow 1.2 and a later, a "mod-flow" operation never adds a
254 * new flow.
255 */
256 set_allowed_ofp_versions("OpenFlow10");
257
064af421
BP
258 for (;;) {
259 unsigned long int timeout;
260 int c;
261
262 c = getopt_long(argc, argv, short_options, long_options, NULL);
263 if (c == -1) {
264 break;
265 }
266
267 switch (c) {
268 case 't':
269 timeout = strtoul(optarg, NULL, 10);
270 if (timeout <= 0) {
271 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
272 optarg);
273 } else {
274 time_alarm(timeout);
275 }
276 break;
277
88ca35ee 278 case 'F':
27527aa0
BP
279 allowed_protocols = ofputil_protocols_from_string(optarg);
280 if (!allowed_protocols) {
281 ovs_fatal(0, "%s: invalid flow format(s)", optarg);
88ca35ee
BP
282 }
283 break;
284
54834960
EJ
285 case 'P':
286 preferred_packet_in_format =
287 ofputil_packet_in_format_from_string(optarg);
288 if (preferred_packet_in_format < 0) {
289 ovs_fatal(0, "unknown packet-in format `%s'", optarg);
290 }
291 break;
292
4f564f8d
BP
293 case 'm':
294 verbosity++;
295 break;
296
064af421
BP
297 case 'h':
298 usage();
299
66fa2c88 300 case 'o':
5f383751 301 ovs_cmdl_print_options(long_options);
66fa2c88
AW
302 exit(EXIT_SUCCESS);
303
db5076ee
JR
304 case OPT_BUNDLE:
305 bundle = true;
306 break;
307
064af421 308 case OPT_STRICT:
675febfa 309 strict = true;
064af421
BP
310 break;
311
1f4a7252
RM
312 case OPT_READ_ONLY:
313 read_only = true;
314 break;
315
c4ea79bf
BP
316 case OPT_READD:
317 readd = true;
318 break;
319
0c9560b7
BP
320 case OPT_TIMESTAMP:
321 timestamp = true;
322 break;
323
bdcc5925
BP
324 case OPT_SORT:
325 add_sort_criterion(SORT_ASC, optarg);
326 break;
327
328 case OPT_RSORT:
329 add_sort_criterion(SORT_DESC, optarg);
330 break;
331
19945013
BP
332 case OPT_UNIXCTL:
333 unixctl_path = optarg;
334 break;
335
20174b74
QM
336 case OPT_COLOR:
337 if (optarg) {
338 if (!strcasecmp(optarg, "always")
339 || !strcasecmp(optarg, "yes")
340 || !strcasecmp(optarg, "force")) {
341 enable_color = true;
342 } else if (!strcasecmp(optarg, "never")
343 || !strcasecmp(optarg, "no")
344 || !strcasecmp(optarg, "none")) {
345 enable_color = false;
346 } else if (!strcasecmp(optarg, "auto")
347 || !strcasecmp(optarg, "tty")
348 || !strcasecmp(optarg, "if-tty")) {
349 /* Determine whether we need colors, i.e. whether standard
350 * output is a tty. */
351 enable_color = is_stdout_a_tty();
352 } else {
353 ovs_fatal(0, "incorrect value `%s' for --color", optarg);
354 }
355 } else {
356 enable_color = is_stdout_a_tty();
357 }
358 break;
359
88b87a36
JS
360 case OPT_MAY_CREATE:
361 may_create = true;
362 break;
363
1eb85ef5 364 DAEMON_OPTION_HANDLERS
a53a8efa 365 OFP_VERSION_OPTION_HANDLERS
87c84891 366 VLOG_OPTION_HANDLERS
fe55ad15 367 STREAM_SSL_OPTION_HANDLERS
064af421
BP
368
369 case '?':
370 exit(EXIT_FAILURE);
371
50f96b10
BP
372 case 0:
373 break;
374
064af421
BP
375 default:
376 abort();
377 }
378 }
bdcc5925
BP
379
380 if (n_criteria) {
381 /* Always do a final sort pass based on priority. */
382 add_sort_criterion(SORT_DESC, "priority");
383 }
384
064af421 385 free(short_options);
37923ac7 386
db5076ee 387 /* Implicit OpenFlow 1.4 with the '--bundle' option. */
06d4d4b6
JR
388 if (bundle && !(get_allowed_ofp_versions() &
389 ofputil_protocols_to_version_bitmap(OFPUTIL_P_OF13_UP))) {
db5076ee
JR
390 /* Add implicit allowance for OpenFlow 1.4. */
391 add_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
392 OFPUTIL_P_OF14_OXM));
06d4d4b6 393 /* Remove all versions that do not support bundles. */
5f8c05ad 394 mask_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
06d4d4b6 395 OFPUTIL_P_OF13_UP));
db5076ee 396 }
37923ac7
BP
397 versions = get_allowed_ofp_versions();
398 version_protocols = ofputil_protocols_from_version_bitmap(versions);
399 if (!(allowed_protocols & version_protocols)) {
400 char *protocols = ofputil_protocols_to_string(allowed_protocols);
401 struct ds version_s = DS_EMPTY_INITIALIZER;
402
403 ofputil_format_version_bitmap_names(&version_s, versions);
404 ovs_fatal(0, "None of the enabled OpenFlow versions (%s) supports "
405 "any of the enabled flow formats (%s). (Use -O to enable "
406 "additional OpenFlow versions or -F to enable additional "
407 "flow formats.)", ds_cstr(&version_s), protocols);
408 }
409 allowed_protocols &= version_protocols;
410 mask_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
411 allowed_protocols));
ef7b593b
QM
412
413 colors_init(enable_color);
064af421
BP
414}
415
416static void
417usage(void)
418{
419 printf("%s: OpenFlow switch management utility\n"
420 "usage: %s [OPTIONS] COMMAND [ARG...]\n"
421 "\nFor OpenFlow switches:\n"
422 " show SWITCH show OpenFlow information\n"
064af421
BP
423 " dump-desc SWITCH print switch description\n"
424 " dump-tables SWITCH print table stats\n"
5deff5aa 425 " dump-table-features SWITCH print table features\n"
03c72922 426 " dump-table-desc SWITCH print table description (OF1.4+)\n"
064af421 427 " mod-port SWITCH IFACE ACT modify port behavior\n"
918f2b82 428 " mod-table SWITCH MOD modify flow table behavior\n"
82c22d34 429 " OF1.1/1.2 MOD: controller, continue, drop\n"
de7d3c07 430 " OF1.4+ MOD: evict, noevict, vacancy:low,high, novacancy\n"
7257b535
BP
431 " get-frags SWITCH print fragment handling behavior\n"
432 " set-frags SWITCH FRAG_MODE set fragment handling behavior\n"
82c22d34 433 " FRAG_MODE: normal, drop, reassemble, nx-match\n"
abaad8cf 434 " dump-ports SWITCH [PORT] print port statistics\n"
70ae4f93 435 " dump-ports-desc SWITCH [PORT] print port descriptions\n"
064af421
BP
436 " dump-flows SWITCH print all flow entries\n"
437 " dump-flows SWITCH FLOW print matching FLOWs\n"
438 " dump-aggregate SWITCH print aggregate flow statistics\n"
439 " dump-aggregate SWITCH FLOW print aggregate stats for FLOWs\n"
d2805da2 440 " queue-stats SWITCH [PORT [QUEUE]] dump queue stats\n"
064af421
BP
441 " add-flow SWITCH FLOW add flow described by FLOW\n"
442 " add-flows SWITCH FILE add flows from FILE\n"
443 " mod-flows SWITCH FLOW modify actions of matching FLOWs\n"
444 " del-flows SWITCH [FLOW] delete matching FLOWs\n"
5ff660c6 445 " replace-flows SWITCH FILE replace flows with those in FILE\n"
1dac118c 446 " diff-flows SOURCE1 SOURCE2 compare flows from two sources\n"
0c3d5fc8
BP
447 " packet-out SWITCH IN_PORT ACTIONS PACKET...\n"
448 " execute ACTIONS on PACKET\n"
2b07c8b1 449 " monitor SWITCH [MISSLEN] [invalid_ttl] [watch:[...]]\n"
1dac118c
BP
450 " print packets received from SWITCH\n"
451 " snoop SWITCH snoop on SWITCH and its controller\n"
7395c052 452 " add-group SWITCH GROUP add group described by GROUP\n"
bdcca615 453 " add-groups SWITCH FILE add group from FILE\n"
88b87a36 454 " [--may-create] mod-group SWITCH GROUP modify specific group\n"
7395c052 455 " del-groups SWITCH [GROUP] delete matching GROUPs\n"
bdbb8426
SH
456 " insert-buckets SWITCH [GROUP] add buckets to GROUP\n"
457 " remove-buckets SWITCH [GROUP] remove buckets from GROUP\n"
7395c052 458 " dump-group-features SWITCH print group features\n"
19187a71 459 " dump-groups SWITCH [GROUP] print group description\n"
7395c052 460 " dump-group-stats SWITCH [GROUP] print group statistics\n"
56085be5 461 " queue-get-config SWITCH [PORT] print queue config for PORT\n"
3200ed58
JR
462 " add-meter SWITCH METER add meter described by METER\n"
463 " mod-meter SWITCH METER modify specific METER\n"
464 " del-meter SWITCH METER delete METER\n"
465 " del-meters SWITCH delete all meters\n"
466 " dump-meter SWITCH METER print METER configuration\n"
467 " dump-meters SWITCH print all meter configuration\n"
468 " meter-stats SWITCH [METER] print meter statistics\n"
469 " meter-features SWITCH print meter features\n"
4e548ad9
ML
470 " add-tlv-map SWITCH MAP add TLV option MAPpings\n"
471 " del-tlv-map SWITCH [MAP] delete TLV option MAPpings\n"
472 " dump-tlv-map SWITCH print TLV option mappings\n"
fb8f22c1
BY
473 " dump-ipfix-bridge SWITCH print ipfix stats of bridge\n"
474 " dump-ipfix-flow SWITCH print flow ipfix of a bridge\n"
2a7c4805 475 " ct-flush-zone SWITCH ZONE flush conntrack entries in ZONE\n"
064af421 476 "\nFor OpenFlow switches and controllers:\n"
2daadadd
BP
477 " probe TARGET probe whether TARGET is up\n"
478 " ping TARGET [N] latency of N-byte echos\n"
479 " benchmark TARGET N COUNT bandwidth of COUNT N-byte echos\n"
1ac0e975
BP
480 "SWITCH or TARGET is an active OpenFlow connection method.\n"
481 "\nOther commands:\n"
f3dd1419
BP
482 " ofp-parse FILE print messages read from FILE\n"
483 " ofp-parse-pcap PCAP print OpenFlow read from PCAP\n",
064af421
BP
484 program_name, program_name);
485 vconn_usage(true, false, false);
1eb85ef5 486 daemon_usage();
a53a8efa 487 ofp_version_usage();
064af421
BP
488 vlog_usage();
489 printf("\nOther options:\n"
490 " --strict use strict match for flow commands\n"
1f4a7252 491 " --read-only do not execute read/write commands\n"
c4ea79bf 492 " --readd replace flows that haven't changed\n"
88ca35ee 493 " -F, --flow-format=FORMAT force particular flow format\n"
54834960 494 " -P, --packet-in-format=FRMT force particular packet in format\n"
4f564f8d 495 " -m, --more be more verbose printing OpenFlow\n"
0c9560b7 496 " --timestamp (monitor, snoop) print timestamps\n"
064af421 497 " -t, --timeout=SECS give up after SECS seconds\n"
bdcc5925
BP
498 " --sort[=field] sort in ascending order\n"
499 " --rsort[=field] sort in descending order\n"
50f96b10 500 " --names show port names instead of numbers\n"
19945013 501 " --unixctl=SOCKET set control socket name\n"
20174b74 502 " --color[=always|never|auto] control use of color in output\n"
064af421
BP
503 " -h, --help display this help message\n"
504 " -V, --version display version information\n");
505 exit(EXIT_SUCCESS);
506}
507
1eb85ef5
EJ
508static void
509ofctl_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
510 const char *argv[] OVS_UNUSED, void *exiting_)
511{
512 bool *exiting = exiting_;
513 *exiting = true;
bde9f75d 514 unixctl_command_reply(conn, NULL);
1eb85ef5
EJ
515}
516
064af421 517static void run(int retval, const char *message, ...)
cab50449 518 OVS_PRINTF_FORMAT(2, 3);
064af421 519
473f65a2
BP
520static void
521run(int retval, const char *message, ...)
064af421
BP
522{
523 if (retval) {
524 va_list args;
525
064af421 526 va_start(args, message);
fcaddd4d 527 ovs_fatal_valist(retval, message, args);
064af421
BP
528 }
529}
530\f
531/* Generic commands. */
532
c3f25389 533static int
1a6f1e2a
JG
534open_vconn_socket(const char *name, struct vconn **vconnp)
535{
536 char *vconn_name = xasprintf("unix:%s", name);
c3f25389
EJ
537 int error;
538
82c8c53c
BP
539 error = vconn_open(vconn_name, get_allowed_ofp_versions(), DSCP_DEFAULT,
540 vconnp);
c3f25389
EJ
541 if (error && error != ENOENT) {
542 ovs_fatal(0, "%s: failed to open socket (%s)", name,
10a89ef0 543 ovs_strerror(error));
c3f25389 544 }
1a6f1e2a 545 free(vconn_name);
c3f25389
EJ
546
547 return error;
1a6f1e2a
JG
548}
549
4766ce7a
BP
550enum open_target { MGMT, SNOOP };
551
27527aa0 552static enum ofputil_protocol
4766ce7a 553open_vconn__(const char *name, enum open_target target,
0caf6bde 554 struct vconn **vconnp)
064af421 555{
4766ce7a 556 const char *suffix = target == MGMT ? "mgmt" : "snoop";
63d347ce 557 char *datapath_name, *datapath_type, *socket_name;
27527aa0 558 enum ofputil_protocol protocol;
63d347ce 559 char *bridge_path;
27527aa0 560 int ofp_version;
c3f25389 561 int error;
1a6f1e2a 562
4766ce7a 563 bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, suffix);
63d347ce
BP
564
565 ofproto_parse_name(name, &datapath_name, &datapath_type);
4766ce7a 566 socket_name = xasprintf("%s/%s.%s", ovs_rundir(), datapath_name, suffix);
63d347ce
BP
567 free(datapath_name);
568 free(datapath_type);
064af421 569
3a27375e 570 if (strchr(name, ':')) {
539b741f 571 run(vconn_open(name, get_allowed_ofp_versions(), DSCP_DEFAULT, vconnp),
a53a8efa 572 "connecting to %s", name);
c3f25389
EJ
573 } else if (!open_vconn_socket(name, vconnp)) {
574 /* Fall Through. */
575 } else if (!open_vconn_socket(bridge_path, vconnp)) {
576 /* Fall Through. */
577 } else if (!open_vconn_socket(socket_name, vconnp)) {
578 /* Fall Through. */
064af421 579 } else {
2c0e6eb4 580 ovs_fatal(0, "%s is not a bridge or a socket", name);
064af421 581 }
1a6f1e2a 582
4766ce7a
BP
583 if (target == SNOOP) {
584 vconn_set_recv_any_version(*vconnp);
585 }
586
1a6f1e2a 587 free(bridge_path);
63d347ce 588 free(socket_name);
27527aa0 589
c3f25389
EJ
590 VLOG_DBG("connecting to %s", vconn_get_name(*vconnp));
591 error = vconn_connect_block(*vconnp);
592 if (error) {
593 ovs_fatal(0, "%s: failed to connect to socket (%s)", name,
10a89ef0 594 ovs_strerror(error));
c3f25389
EJ
595 }
596
27527aa0
BP
597 ofp_version = vconn_get_version(*vconnp);
598 protocol = ofputil_protocol_from_ofp_version(ofp_version);
599 if (!protocol) {
600 ovs_fatal(0, "%s: unsupported OpenFlow version 0x%02x",
601 name, ofp_version);
602 }
603 return protocol;
064af421
BP
604}
605
27527aa0 606static enum ofputil_protocol
0caf6bde
BP
607open_vconn(const char *name, struct vconn **vconnp)
608{
4766ce7a 609 return open_vconn__(name, MGMT, vconnp);
0caf6bde
BP
610}
611
064af421
BP
612static void
613send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
614{
064af421
BP
615 run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
616}
617
618static void
a53a8efa 619dump_transaction(struct vconn *vconn, struct ofpbuf *request)
064af421 620{
182b2eef
BP
621 const struct ofp_header *oh = request->data;
622 if (ofpmsg_is_stat_request(oh)) {
623 ovs_be32 send_xid = oh->xid;
624 enum ofpraw request_raw;
625 enum ofpraw reply_raw;
626 bool done = false;
064af421 627
182b2eef
BP
628 ofpraw_decode_partial(&request_raw, request->data, request->size);
629 reply_raw = ofpraw_stats_request_to_reply(request_raw, oh->version);
982697a4 630
182b2eef
BP
631 send_openflow_buffer(vconn, request);
632 while (!done) {
633 ovs_be32 recv_xid;
634 struct ofpbuf *reply;
064af421 635
182b2eef
BP
636 run(vconn_recv_block(vconn, &reply),
637 "OpenFlow packet receive failed");
638 recv_xid = ((struct ofp_header *) reply->data)->xid;
639 if (send_xid == recv_xid) {
640 enum ofpraw raw;
064af421 641
50f96b10
BP
642 ofp_print(stdout, reply->data, reply->size,
643 ports_to_show(vconn_get_name(vconn)), verbosity + 1);
064af421 644
182b2eef
BP
645 ofpraw_decode(&raw, reply->data);
646 if (ofptype_from_ofpraw(raw) == OFPTYPE_ERROR) {
647 done = true;
648 } else if (raw == reply_raw) {
649 done = !ofpmp_more(reply->data);
650 } else {
651 ovs_fatal(0, "received bad reply: %s",
50f96b10
BP
652 ofp_to_string(
653 reply->data, reply->size,
654 ports_to_show(vconn_get_name(vconn)),
655 verbosity + 1));
182b2eef 656 }
a76150b1 657 } else {
182b2eef
BP
658 VLOG_DBG("received reply with xid %08"PRIx32" "
659 "!= expected %08"PRIx32, recv_xid, send_xid);
a76150b1 660 }
182b2eef 661 ofpbuf_delete(reply);
064af421 662 }
182b2eef
BP
663 } else {
664 struct ofpbuf *reply;
665
666 run(vconn_transact(vconn, request, &reply), "talking to %s",
667 vconn_get_name(vconn));
50f96b10
BP
668 ofp_print(stdout, reply->data, reply->size,
669 ports_to_show(vconn_get_name(vconn)), verbosity + 1);
064af421
BP
670 ofpbuf_delete(reply);
671 }
9abfe557
BP
672}
673
674static void
182b2eef 675dump_trivial_transaction(const char *vconn_name, enum ofpraw raw)
9abfe557 676{
53514387 677 struct ofpbuf *request;
9abfe557
BP
678 struct vconn *vconn;
679
680 open_vconn(vconn_name, &vconn);
53514387 681 request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
182b2eef 682 dump_transaction(vconn, request);
064af421
BP
683 vconn_close(vconn);
684}
685
a8eebd48
BP
686/* Sends all of the 'requests', which should be requests that only have replies
687 * if an error occurs, and waits for them to succeed or fail. If an error does
688 * occur, prints it and exits with an error.
7257b535
BP
689 *
690 * Destroys all of the 'requests'. */
d12513f7 691static void
ca6ba700 692transact_multiple_noreply(struct vconn *vconn, struct ovs_list *requests)
d12513f7 693{
db5076ee 694 struct ofpbuf *reply;
88ca35ee
BP
695
696 run(vconn_transact_multiple_noreply(vconn, requests, &reply),
d12513f7
BP
697 "talking to %s", vconn_get_name(vconn));
698 if (reply) {
50f96b10
BP
699 ofp_print(stderr, reply->data, reply->size,
700 ports_to_show(vconn_get_name(vconn)), verbosity + 2);
d12513f7
BP
701 exit(1);
702 }
703 ofpbuf_delete(reply);
704}
705
506c1ddb 706/* Frees the error messages as they are printed. */
db5076ee 707static void
50f96b10
BP
708bundle_print_errors(struct ovs_list *errors, struct ovs_list *requests,
709 const char *vconn_name)
db5076ee 710{
209aa4ad 711 struct ofpbuf *error, *next;
506c1ddb
JR
712 struct ofpbuf *bmsg;
713
714 INIT_CONTAINER(bmsg, requests, list_node);
715
716 LIST_FOR_EACH_SAFE (error, next, list_node, errors) {
209aa4ad
BP
717 const struct ofp_header *error_oh = error->data;
718 ovs_be32 error_xid = error_oh->xid;
506c1ddb
JR
719 enum ofperr ofperr;
720 struct ofpbuf payload;
721
209aa4ad 722 ofperr = ofperr_decode_msg(error_oh, &payload);
506c1ddb
JR
723 if (!ofperr) {
724 fprintf(stderr, "***decode error***");
725 } else {
726 /* Default to the likely truncated message. */
727 const struct ofp_header *ofp_msg = payload.data;
728 size_t msg_len = payload.size;
729
730 /* Find the failing message from the requests list to be able to
731 * dump the whole message. We assume the errors are returned in
732 * the same order as in which the messages are sent to get O(n)
733 * rather than O(n^2) processing here. If this heuristics fails we
734 * may print the truncated hexdumps instead. */
735 LIST_FOR_EACH_CONTINUE (bmsg, list_node, requests) {
736 const struct ofp_header *oh = bmsg->data;
737
209aa4ad 738 if (oh->xid == error_xid) {
506c1ddb
JR
739 ofp_msg = oh;
740 msg_len = bmsg->size;
741 break;
742 }
743 }
744 fprintf(stderr, "Error %s for: ", ofperr_get_name(ofperr));
50f96b10
BP
745 ofp_print(stderr, ofp_msg, msg_len, ports_to_show(vconn_name),
746 verbosity + 1);
506c1ddb 747 }
a4b2c64f 748 ofpbuf_uninit(&payload);
209aa4ad 749 ofpbuf_delete(error);
506c1ddb 750 }
db5076ee
JR
751 fflush(stderr);
752}
753
754static void
755bundle_transact(struct vconn *vconn, struct ovs_list *requests, uint16_t flags)
756{
506c1ddb
JR
757 struct ovs_list errors;
758 int retval = vconn_bundle_transact(vconn, requests, flags, &errors);
759
50f96b10 760 bundle_print_errors(&errors, requests, vconn_get_name(vconn));
506c1ddb
JR
761
762 if (retval) {
763 ovs_fatal(retval, "talking to %s", vconn_get_name(vconn));
764 }
db5076ee
JR
765}
766
88ca35ee
BP
767/* Sends 'request', which should be a request that only has a reply if an error
768 * occurs, and waits for it to succeed or fail. If an error does occur, prints
7257b535
BP
769 * it and exits with an error.
770 *
771 * Destroys 'request'. */
88ca35ee
BP
772static void
773transact_noreply(struct vconn *vconn, struct ofpbuf *request)
774{
ca6ba700 775 struct ovs_list requests;
88ca35ee 776
417e7e66
BW
777 ovs_list_init(&requests);
778 ovs_list_push_back(&requests, &request->list_node);
88ca35ee
BP
779 transact_multiple_noreply(vconn, &requests);
780}
781
7257b535 782static void
ad99e2ed 783fetch_switch_config(struct vconn *vconn, struct ofputil_switch_config *config)
7257b535 784{
7257b535
BP
785 struct ofpbuf *request;
786 struct ofpbuf *reply;
982697a4 787 enum ofptype type;
7257b535 788
a53a8efa
SH
789 request = ofpraw_alloc(OFPRAW_OFPT_GET_CONFIG_REQUEST,
790 vconn_get_version(vconn), 0);
7257b535
BP
791 run(vconn_transact(vconn, request, &reply),
792 "talking to %s", vconn_get_name(vconn));
793
ad99e2ed
BP
794 if (ofptype_decode(&type, reply->data)
795 || type != OFPTYPE_GET_CONFIG_REPLY) {
7257b535
BP
796 ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
797 }
ad99e2ed 798 ofputil_decode_get_config_reply(reply->data, config);
828c72d0 799 ofpbuf_delete(reply);
7257b535
BP
800}
801
802static void
ad99e2ed
BP
803set_switch_config(struct vconn *vconn,
804 const struct ofputil_switch_config *config)
7257b535 805{
ad99e2ed
BP
806 enum ofp_version version = vconn_get_version(vconn);
807 transact_noreply(vconn, ofputil_encode_set_config(config, version));
7257b535
BP
808}
809
064af421 810static void
1636c761 811ofctl_show(struct ovs_cmdl_context *ctx)
064af421 812{
1636c761 813 const char *vconn_name = ctx->argv[1];
fca6d553 814 enum ofp_version version;
ae0e7009
JP
815 struct vconn *vconn;
816 struct ofpbuf *request;
817 struct ofpbuf *reply;
fca6d553 818 bool has_ports;
ae0e7009 819
ae0e7009 820 open_vconn(vconn_name, &vconn);
fca6d553
BP
821 version = vconn_get_version(vconn);
822 request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST, version, 0);
ae0e7009
JP
823 run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
824
fca6d553 825 has_ports = ofputil_switch_features_has_ports(reply);
50f96b10 826 ofp_print(stdout, reply->data, reply->size, NULL, verbosity + 1);
ae0e7009 827 ofpbuf_delete(reply);
ae0e7009 828
fca6d553 829 if (!has_ports) {
70ae4f93 830 request = ofputil_encode_port_desc_stats_request(version, OFPP_ANY);
182b2eef 831 dump_transaction(vconn, request);
ae0e7009 832 }
982697a4 833 dump_trivial_transaction(vconn_name, OFPRAW_OFPT_GET_CONFIG_REQUEST);
a53a8efa 834 vconn_close(vconn);
064af421
BP
835}
836
064af421 837static void
1636c761 838ofctl_dump_desc(struct ovs_cmdl_context *ctx)
064af421 839{
182b2eef 840 dump_trivial_transaction(ctx->argv[1], OFPRAW_OFPST_DESC_REQUEST);
064af421
BP
841}
842
843static void
1636c761 844ofctl_dump_tables(struct ovs_cmdl_context *ctx)
064af421 845{
182b2eef 846 dump_trivial_transaction(ctx->argv[1], OFPRAW_OFPST_TABLE_REQUEST);
064af421
BP
847}
848
5deff5aa 849static void
1636c761 850ofctl_dump_table_features(struct ovs_cmdl_context *ctx)
5deff5aa
AW
851{
852 struct ofpbuf *request;
853 struct vconn *vconn;
854
1636c761 855 open_vconn(ctx->argv[1], &vconn);
5deff5aa 856 request = ofputil_encode_table_features_request(vconn_get_version(vconn));
8811fc0a 857
182b2eef 858 /* The following is similar to dump_trivial_transaction(), but it
8811fc0a
BP
859 * maintains the previous 'ofputil_table_features' from one stats reply
860 * message to the next, which allows duplication to be eliminated in the
861 * output across messages. Otherwise the output is much larger and harder
862 * to read, because only 17 or so ofputil_table_features elements fit in a
863 * single 64 kB OpenFlow message and therefore you get a ton of repetition
864 * (every 17th element is printed in full instead of abbreviated). */
865
866 const struct ofp_header *request_oh = request->data;
867 ovs_be32 send_xid = request_oh->xid;
868 bool done = false;
869
870 struct ofputil_table_features prev;
871 int n = 0;
872
873 send_openflow_buffer(vconn, request);
874 while (!done) {
875 ovs_be32 recv_xid;
876 struct ofpbuf *reply;
877
878 run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
879 recv_xid = ((struct ofp_header *) reply->data)->xid;
880 if (send_xid == recv_xid) {
881 enum ofptype type;
882 enum ofperr error;
883 error = ofptype_decode(&type, reply->data);
884 if (error) {
885 ovs_fatal(0, "decode error: %s", ofperr_get_name(error));
886 } else if (type == OFPTYPE_ERROR) {
50f96b10
BP
887 ofp_print(stdout, reply->data, reply->size, NULL,
888 verbosity + 1);
8811fc0a
BP
889 done = true;
890 } else if (type == OFPTYPE_TABLE_FEATURES_STATS_REPLY) {
891 done = !ofpmp_more(reply->data);
892 for (;;) {
893 struct ofputil_table_features tf;
894 int retval;
895
896 retval = ofputil_decode_table_features(reply, &tf, true);
897 if (retval) {
898 if (retval != EOF) {
899 ovs_fatal(0, "decode error: %s",
900 ofperr_get_name(retval));
901 }
902 break;
903 }
904
905 struct ds s = DS_EMPTY_INITIALIZER;
906 ofp_print_table_features(&s, &tf, n ? &prev : NULL,
907 NULL, NULL);
908 puts(ds_cstr(&s));
909 ds_destroy(&s);
910
911 prev = tf;
912 n++;
913 }
914 } else {
915 ovs_fatal(0, "received bad reply: %s",
916 ofp_to_string(reply->data, reply->size,
50f96b10 917 ports_to_show(ctx->argv[1]),
8811fc0a
BP
918 verbosity + 1));
919 }
920 } else {
921 VLOG_DBG("received reply with xid %08"PRIx32" "
922 "!= expected %08"PRIx32, recv_xid, send_xid);
923 }
924 ofpbuf_delete(reply);
5deff5aa
AW
925 }
926
927 vconn_close(vconn);
928}
929
03c72922
BP
930static void
931ofctl_dump_table_desc(struct ovs_cmdl_context *ctx)
932{
933 struct ofpbuf *request;
934 struct vconn *vconn;
935
936 open_vconn(ctx->argv[1], &vconn);
937 request = ofputil_encode_table_desc_request(vconn_get_version(vconn));
938 if (request) {
182b2eef 939 dump_transaction(vconn, request);
03c72922
BP
940 }
941
942 vconn_close(vconn);
943}
944
945
da91750f 946static bool
5f4c5ff1 947str_to_ofp(const char *s, ofp_port_t *ofp_port)
abaad8cf 948{
5f4c5ff1
BP
949 bool ret;
950 uint32_t port_;
951
952 ret = str_to_uint(s, 10, &port_);
953 *ofp_port = u16_to_ofp(port_);
954 return ret;
955}
956
957struct port_iterator {
958 struct vconn *vconn;
959
960 enum { PI_FEATURES, PI_PORT_DESC } variant;
961 struct ofpbuf *reply;
962 ovs_be32 send_xid;
963 bool more;
964};
965
966static void
967port_iterator_fetch_port_desc(struct port_iterator *pi)
968{
969 pi->variant = PI_PORT_DESC;
970 pi->more = true;
971
972 struct ofpbuf *rq = ofputil_encode_port_desc_stats_request(
973 vconn_get_version(pi->vconn), OFPP_ANY);
974 pi->send_xid = ((struct ofp_header *) rq->data)->xid;
975 send_openflow_buffer(pi->vconn, rq);
976}
977
978static void
979port_iterator_fetch_features(struct port_iterator *pi)
980{
981 pi->variant = PI_FEATURES;
abaad8cf 982
0df0e81d 983 /* Fetch the switch's ofp_switch_features. */
5f4c5ff1
BP
984 enum ofp_version version = vconn_get_version(pi->vconn);
985 struct ofpbuf *rq = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST, version, 0);
986 run(vconn_transact(pi->vconn, rq, &pi->reply),
987 "talking to %s", vconn_get_name(pi->vconn));
abaad8cf 988
5f4c5ff1
BP
989 enum ofptype type;
990 if (ofptype_decode(&type, pi->reply->data)
982697a4 991 || type != OFPTYPE_FEATURES_REPLY) {
5f4c5ff1
BP
992 ovs_fatal(0, "%s: received bad features reply",
993 vconn_get_name(pi->vconn));
0df0e81d 994 }
5f4c5ff1 995 if (!ofputil_switch_features_has_ports(pi->reply)) {
fca6d553
BP
996 /* The switch features reply does not contain a complete list of ports.
997 * Probably, there are more ports than will fit into a single 64 kB
998 * OpenFlow message. Use OFPST_PORT_DESC to get a complete list of
999 * ports. */
5f4c5ff1
BP
1000 ofpbuf_delete(pi->reply);
1001 pi->reply = NULL;
1002 port_iterator_fetch_port_desc(pi);
1003 return;
da91750f
JP
1004 }
1005
5f4c5ff1 1006 struct ofputil_switch_features features;
667bb1fb 1007 enum ofperr error = ofputil_pull_switch_features(pi->reply, &features);
9e1fd49b
BP
1008 if (error) {
1009 ovs_fatal(0, "%s: failed to decode features reply (%s)",
5f4c5ff1 1010 vconn_get_name(pi->vconn), ofperr_to_string(error));
9e1fd49b 1011 }
5f4c5ff1 1012}
0df0e81d 1013
5f4c5ff1
BP
1014/* Initializes 'pi' to prepare for iterating through all of the ports on the
1015 * OpenFlow switch to which 'vconn' is connected.
1016 *
1017 * During iteration, the client should not make other use of 'vconn', because
1018 * that can cause other messages to be interleaved with the replies used by the
1019 * iterator and thus some ports may be missed or a hang can occur. */
1020static void
1021port_iterator_init(struct port_iterator *pi, struct vconn *vconn)
1022{
1023 memset(pi, 0, sizeof *pi);
1024 pi->vconn = vconn;
1025 if (vconn_get_version(vconn) < OFP13_VERSION) {
1026 port_iterator_fetch_features(pi);
1027 } else {
1028 port_iterator_fetch_port_desc(pi);
abaad8cf 1029 }
da91750f
JP
1030}
1031
5f4c5ff1
BP
1032/* Obtains the next port from 'pi'. On success, initializes '*pp' with the
1033 * port's details and returns true, otherwise (if all the ports have already
1034 * been seen), returns false. */
da91750f 1035static bool
5f4c5ff1 1036port_iterator_next(struct port_iterator *pi, struct ofputil_phy_port *pp)
da91750f 1037{
5f4c5ff1
BP
1038 for (;;) {
1039 if (pi->reply) {
1040 int retval = ofputil_pull_phy_port(vconn_get_version(pi->vconn),
1041 pi->reply, pp);
1042 if (!retval) {
1043 return true;
1044 } else if (retval != EOF) {
da91750f 1045 ovs_fatal(0, "received bad reply: %s",
5f4c5ff1 1046 ofp_to_string(pi->reply->data, pi->reply->size,
50f96b10 1047 NULL, verbosity + 1));
da91750f 1048 }
5f4c5ff1 1049 }
da91750f 1050
5f4c5ff1
BP
1051 if (pi->variant == PI_FEATURES || !pi->more) {
1052 return false;
1053 }
da91750f 1054
5f4c5ff1
BP
1055 ovs_be32 recv_xid;
1056 do {
1057 ofpbuf_delete(pi->reply);
1058 run(vconn_recv_block(pi->vconn, &pi->reply),
1059 "OpenFlow receive failed");
1060 recv_xid = ((struct ofp_header *) pi->reply->data)->xid;
1061 } while (pi->send_xid != recv_xid);
1062
1063 struct ofp_header *oh = pi->reply->data;
1064 enum ofptype type;
1065 if (ofptype_pull(&type, pi->reply)
1066 || type != OFPTYPE_PORT_DESC_STATS_REPLY) {
1067 ovs_fatal(0, "received bad reply: %s",
50f96b10 1068 ofp_to_string(pi->reply->data, pi->reply->size, NULL,
5f4c5ff1 1069 verbosity + 1));
da91750f 1070 }
da91750f 1071
5f4c5ff1
BP
1072 pi->more = (ofpmp_flags(oh) & OFPSF_REPLY_MORE) != 0;
1073 }
da91750f
JP
1074}
1075
5f4c5ff1
BP
1076/* Destroys iterator 'pi'. */
1077static void
1078port_iterator_destroy(struct port_iterator *pi)
4e022ec0 1079{
5f4c5ff1
BP
1080 if (pi) {
1081 while (pi->variant == PI_PORT_DESC && pi->more) {
1082 /* Drain vconn's queue of any other replies for this request. */
1083 struct ofputil_phy_port pp;
1084 port_iterator_next(pi, &pp);
1085 }
4e022ec0 1086
5f4c5ff1
BP
1087 ofpbuf_delete(pi->reply);
1088 }
4e022ec0 1089}
da91750f
JP
1090
1091/* Opens a connection to 'vconn_name', fetches the port structure for
1092 * 'port_name' (which may be a port name or number), and copies it into
1093 * '*pp'. */
1094static void
1095fetch_ofputil_phy_port(const char *vconn_name, const char *port_name,
1096 struct ofputil_phy_port *pp)
1097{
fca6d553 1098 struct vconn *vconn;
4e022ec0 1099 ofp_port_t port_no;
5f4c5ff1 1100 bool found = false;
da91750f
JP
1101
1102 /* Try to interpret the argument as a port number. */
4e022ec0
AW
1103 if (!str_to_ofp(port_name, &port_no)) {
1104 port_no = OFPP_NONE;
da91750f
JP
1105 }
1106
fca6d553
BP
1107 /* OpenFlow 1.0, 1.1, and 1.2 put the list of ports in the
1108 * OFPT_FEATURES_REPLY message. OpenFlow 1.3 and later versions put it
1109 * into the OFPST_PORT_DESC reply. Try it the correct way. */
1110 open_vconn(vconn_name, &vconn);
5f4c5ff1
BP
1111 struct port_iterator pi;
1112 for (port_iterator_init(&pi, vconn); port_iterator_next(&pi, pp); ) {
1113 if (port_no != OFPP_NONE
1114 ? port_no == pp->port_no
1115 : !strcmp(pp->name, port_name)) {
1116 found = true;
1117 break;
1118 }
1119 }
1120 port_iterator_destroy(&pi);
fca6d553 1121 vconn_close(vconn);
da91750f
JP
1122
1123 if (!found) {
1124 ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
1125 }
0df0e81d 1126}
abaad8cf 1127
50f96b10
BP
1128static const struct ofputil_port_map *
1129get_port_map(const char *vconn_name)
1130{
1131 static struct shash port_maps = SHASH_INITIALIZER(&port_maps);
1132 struct ofputil_port_map *map = shash_find_data(&port_maps, vconn_name);
1133 if (!map) {
1134 map = xmalloc(sizeof *map);
1135 ofputil_port_map_init(map);
1136 shash_add(&port_maps, vconn_name, map);
1137
1138 if (!strchr(vconn_name, ':') || !vconn_verify_name(vconn_name)) {
1139 /* For an active vconn (which includes a vconn constructed from a
1140 * bridge name), connect to it and pull down the port name-number
1141 * mapping. */
1142 struct vconn *vconn;
1143 open_vconn(vconn_name, &vconn);
1144
1145 struct port_iterator pi;
1146 struct ofputil_phy_port pp;
1147 for (port_iterator_init(&pi, vconn);
1148 port_iterator_next(&pi, &pp); ) {
1149 ofputil_port_map_put(map, pp.port_no, pp.name);
1150 }
1151 port_iterator_destroy(&pi);
1152
1153 vconn_close(vconn);
1154 } else {
1155 /* Don't bother with passive vconns, since it could take a long
1156 * time for the remote to try to connect to us. Don't bother with
1157 * invalid vconn names either. */
1158 }
1159 }
1160 return map;
1161}
1162
1163static const struct ofputil_port_map *
1164ports_to_accept(const char *vconn_name)
1165{
1166 return should_accept_ports() ? get_port_map(vconn_name) : NULL;
1167}
1168
1169static const struct ofputil_port_map *
1170ports_to_show(const char *vconn_name)
1171{
1172 return should_show_ports() ? get_port_map(vconn_name) : NULL;
1173}
1174
1175/* We accept port names unless the feature is turned off explicitly. */
1176static bool
1177should_accept_ports(void)
1178{
1179 return use_port_names != 0;
1180}
1181
1182/* We show port names only if the feature is turned on explicitly, or if we're
1183 * interacting with a user on the console. */
1184static bool
1185should_show_ports(void)
1186{
1187 static int interactive = -1;
1188 if (interactive == -1) {
1189 interactive = isatty(STDOUT_FILENO);
1190 }
1191
1192 return use_port_names > 0 || (use_port_names == -1 && interactive);
1193}
1194
0df0e81d
BP
1195/* Returns the port number corresponding to 'port_name' (which may be a port
1196 * name or number) within the switch 'vconn_name'. */
4e022ec0 1197static ofp_port_t
0df0e81d
BP
1198str_to_port_no(const char *vconn_name, const char *port_name)
1199{
4e022ec0 1200 ofp_port_t port_no;
50f96b10
BP
1201 if (ofputil_port_from_string(port_name, NULL, &port_no) ||
1202 ofputil_port_from_string(port_name, ports_to_accept(vconn_name),
1203 &port_no)) {
0df0e81d 1204 return port_no;
0df0e81d 1205 }
50f96b10 1206 ovs_fatal(0, "%s: unknown port `%s'", vconn_name, port_name);
abaad8cf
JP
1207}
1208
88ca35ee 1209static bool
27527aa0
BP
1210try_set_protocol(struct vconn *vconn, enum ofputil_protocol want,
1211 enum ofputil_protocol *cur)
88ca35ee 1212{
27527aa0
BP
1213 for (;;) {
1214 struct ofpbuf *request, *reply;
1215 enum ofputil_protocol next;
88ca35ee 1216
27527aa0
BP
1217 request = ofputil_encode_set_protocol(*cur, want, &next);
1218 if (!request) {
e43928f2 1219 return *cur == want;
27527aa0
BP
1220 }
1221
1222 run(vconn_transact_noreply(vconn, request, &reply),
1223 "talking to %s", vconn_get_name(vconn));
1224 if (reply) {
50f96b10 1225 char *s = ofp_to_string(reply->data, reply->size, NULL, 2);
27527aa0
BP
1226 VLOG_DBG("%s: failed to set protocol, switch replied: %s",
1227 vconn_get_name(vconn), s);
1228 free(s);
1229 ofpbuf_delete(reply);
1230 return false;
1231 }
1232
1233 *cur = next;
88ca35ee 1234 }
88ca35ee
BP
1235}
1236
27527aa0
BP
1237static enum ofputil_protocol
1238set_protocol_for_flow_dump(struct vconn *vconn,
1239 enum ofputil_protocol cur_protocol,
1240 enum ofputil_protocol usable_protocols)
064af421 1241{
27527aa0
BP
1242 char *usable_s;
1243 int i;
064af421 1244
27527aa0
BP
1245 for (i = 0; i < ofputil_n_flow_dump_protocols; i++) {
1246 enum ofputil_protocol f = ofputil_flow_dump_protocols[i];
1247 if (f & usable_protocols & allowed_protocols
1248 && try_set_protocol(vconn, f, &cur_protocol)) {
1249 return f;
f9cbfbe4 1250 }
27527aa0 1251 }
f9cbfbe4 1252
27527aa0
BP
1253 usable_s = ofputil_protocols_to_string(usable_protocols);
1254 if (usable_protocols & allowed_protocols) {
1255 ovs_fatal(0, "switch does not support any of the usable flow "
1256 "formats (%s)", usable_s);
50f96b10 1257} else {
27527aa0
BP
1258 char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
1259 ovs_fatal(0, "none of the usable flow formats (%s) is among the "
1260 "allowed flow formats (%s)", usable_s, allowed_s);
88ca35ee 1261 }
064af421
BP
1262}
1263
bdcc5925
BP
1264static struct vconn *
1265prepare_dump_flows(int argc, char *argv[], bool aggregate,
d444a914
BP
1266 struct ofputil_flow_stats_request *fsr,
1267 enum ofputil_protocol *protocolp)
064af421 1268{
50f96b10 1269 const char *vconn_name = argv[1];
27527aa0 1270 enum ofputil_protocol usable_protocols, protocol;
88ca35ee 1271 struct vconn *vconn;
bdda5aca
BP
1272 char *error;
1273
50f96b10
BP
1274 const char *match = argc > 2 ? argv[2] : "";
1275 const struct ofputil_port_map *port_map
1276 = *match ? ports_to_accept(vconn_name) : NULL;
1277 error = parse_ofp_flow_stats_request_str(fsr, aggregate, match,
1278 port_map, &usable_protocols);
bdda5aca
BP
1279 if (error) {
1280 ovs_fatal(0, "%s", error);
1281 }
064af421 1282
50f96b10 1283 protocol = open_vconn(vconn_name, &vconn);
d444a914 1284 *protocolp = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
bdcc5925
BP
1285 return vconn;
1286}
1287
1288static void
1289ofctl_dump_flows__(int argc, char *argv[], bool aggregate)
1290{
d444a914
BP
1291 struct ofputil_flow_stats_request fsr;
1292 enum ofputil_protocol protocol;
bdcc5925
BP
1293 struct vconn *vconn;
1294
d444a914
BP
1295 vconn = prepare_dump_flows(argc, argv, aggregate, &fsr, &protocol);
1296 dump_transaction(vconn, ofputil_encode_flow_stats_request(&fsr, protocol));
88ca35ee
BP
1297 vconn_close(vconn);
1298}
1299
5bc39e9a
JG
1300static void
1301get_match_field(const struct mf_field *field, const struct match *match,
1302 union mf_value *value)
1303{
1304 if (!match->tun_md.valid || (field->id < MFF_TUN_METADATA0 ||
1305 field->id >= MFF_TUN_METADATA0 +
1306 TUN_METADATA_NUM_OPTS)) {
1307 mf_get_value(field, &match->flow, value);
1308 } else {
1309 const struct tun_metadata_loc *loc = &match->tun_md.entry[field->id -
1310 MFF_TUN_METADATA0].loc;
1311
1312 /* Since we don't have a tunnel mapping table, extract the value
1313 * from the locally allocated location in the match. */
1314 memset(value, 0, field->n_bytes - loc->len);
1315 memcpy(value->tun_metadata + field->n_bytes - loc->len,
1316 match->flow.tunnel.metadata.opts.u8 + loc->c.offset, loc->len);
1317 }
1318}
1319
bdcc5925
BP
1320static int
1321compare_flows(const void *afs_, const void *bfs_)
1322{
1323 const struct ofputil_flow_stats *afs = afs_;
1324 const struct ofputil_flow_stats *bfs = bfs_;
81a76618
BP
1325 const struct match *a = &afs->match;
1326 const struct match *b = &bfs->match;
bdcc5925
BP
1327 const struct sort_criterion *sc;
1328
1329 for (sc = criteria; sc < &criteria[n_criteria]; sc++) {
1330 const struct mf_field *f = sc->field;
1331 int ret;
1332
1333 if (!f) {
eb391b76
BP
1334 int a_pri = afs->priority;
1335 int b_pri = bfs->priority;
81a76618 1336 ret = a_pri < b_pri ? -1 : a_pri > b_pri;
bdcc5925
BP
1337 } else {
1338 bool ina, inb;
1339
aff49b8c
JR
1340 ina = mf_are_prereqs_ok(f, &a->flow, NULL)
1341 && !mf_is_all_wild(f, &a->wc);
1342 inb = mf_are_prereqs_ok(f, &b->flow, NULL)
1343 && !mf_is_all_wild(f, &b->wc);
bdcc5925
BP
1344 if (ina != inb) {
1345 /* Skip the test for sc->order, so that missing fields always
1346 * sort to the end whether we're sorting in ascending or
1347 * descending order. */
1348 return ina ? -1 : 1;
1349 } else {
1350 union mf_value aval, bval;
1351
5bc39e9a
JG
1352 get_match_field(f, a, &aval);
1353 get_match_field(f, b, &bval);
bdcc5925
BP
1354 ret = memcmp(&aval, &bval, f->n_bytes);
1355 }
1356 }
1357
1358 if (ret) {
1359 return sc->order == SORT_ASC ? ret : -ret;
1360 }
1361 }
1362
1363 return 0;
1364}
1365
88ca35ee 1366static void
1636c761 1367ofctl_dump_flows(struct ovs_cmdl_context *ctx)
88ca35ee 1368{
1b3758c3 1369 if (!n_criteria && !should_show_ports() && show_stats) {
1636c761 1370 ofctl_dump_flows__(ctx->argc, ctx->argv, false);
2f4aba0b 1371 return;
bdcc5925 1372 } else {
d444a914
BP
1373 struct ofputil_flow_stats_request fsr;
1374 enum ofputil_protocol protocol;
bdcc5925 1375 struct vconn *vconn;
bdcc5925 1376
d444a914
BP
1377 vconn = prepare_dump_flows(ctx->argc, ctx->argv, false,
1378 &fsr, &protocol);
bdcc5925 1379
d444a914
BP
1380 struct ofputil_flow_stats *fses;
1381 size_t n_fses;
1382 run(vconn_dump_flows(vconn, &fsr, protocol, &fses, &n_fses),
1383 "dump flows");
bdcc5925
BP
1384
1385 qsort(fses, n_fses, sizeof *fses, compare_flows);
1386
d444a914
BP
1387 struct ds s = DS_EMPTY_INITIALIZER;
1388 for (size_t i = 0; i < n_fses; i++) {
bdcc5925 1389 ds_clear(&s);
1b3758c3
BP
1390 ofp_print_flow_stats(&s, &fses[i], ports_to_show(ctx->argv[1]),
1391 show_stats);
1392 printf(" %s\n", ds_cstr(&s));
bdcc5925
BP
1393 }
1394 ds_destroy(&s);
1395
d444a914 1396 for (size_t i = 0; i < n_fses; i++) {
dc723c44 1397 free(CONST_CAST(struct ofpact *, fses[i].ofpacts));
bdcc5925
BP
1398 }
1399 free(fses);
1400
1401 vconn_close(vconn);
1402 }
88ca35ee
BP
1403}
1404
1405static void
1636c761 1406ofctl_dump_aggregate(struct ovs_cmdl_context *ctx)
88ca35ee 1407{
1636c761 1408 ofctl_dump_flows__(ctx->argc, ctx->argv, true);
064af421
BP
1409}
1410
d2805da2 1411static void
1636c761 1412ofctl_queue_stats(struct ovs_cmdl_context *ctx)
d2805da2 1413{
d2805da2 1414 struct ofpbuf *request;
53514387 1415 struct vconn *vconn;
64626975 1416 struct ofputil_queue_stats_request oqs;
d2805da2 1417
1636c761 1418 open_vconn(ctx->argv[1], &vconn);
d2805da2 1419
1636c761
RB
1420 if (ctx->argc > 2 && ctx->argv[2][0] && strcasecmp(ctx->argv[2], "all")) {
1421 oqs.port_no = str_to_port_no(ctx->argv[1], ctx->argv[2]);
d2805da2 1422 } else {
7f05e7ab 1423 oqs.port_no = OFPP_ANY;
d2805da2 1424 }
1636c761
RB
1425 if (ctx->argc > 3 && ctx->argv[3][0] && strcasecmp(ctx->argv[3], "all")) {
1426 oqs.queue_id = atoi(ctx->argv[3]);
d2805da2 1427 } else {
64626975 1428 oqs.queue_id = OFPQ_ALL;
d2805da2
BP
1429 }
1430
64626975 1431 request = ofputil_encode_queue_stats_request(vconn_get_version(vconn), &oqs);
182b2eef 1432 dump_transaction(vconn, request);
53514387 1433 vconn_close(vconn);
d2805da2
BP
1434}
1435
e8f9a7bb 1436static void
1636c761 1437ofctl_queue_get_config(struct ovs_cmdl_context *ctx)
e8f9a7bb 1438{
1636c761 1439 const char *vconn_name = ctx->argv[1];
e016fb63
BP
1440 const char *port_name = ctx->argc > 2 ? ctx->argv[2] : "any";
1441 ofp_port_t port = str_to_port_no(vconn_name, port_name);
1442 const char *queue_name = ctx->argc > 3 ? ctx->argv[3] : "all";
1443 uint32_t queue = (!strcasecmp(queue_name, "all")
1444 ? OFPQ_ALL
1445 : atoi(queue_name));
56085be5 1446 struct vconn *vconn;
e016fb63 1447
56085be5
BP
1448 enum ofputil_protocol protocol = open_vconn(vconn_name, &vconn);
1449 enum ofp_version version = ofputil_protocol_to_ofp_version(protocol);
1450 if (port == OFPP_ANY && version == OFP10_VERSION) {
1451 /* The user requested all queues on all ports. OpenFlow 1.0 only
1452 * supports getting queues for an individual port, so to implement the
1453 * user's request we have to get a list of all the ports.
1454 *
1455 * We use a second vconn to avoid having to accumulate a list of all of
1456 * the ports. */
1457 struct vconn *vconn2;
1458 enum ofputil_protocol protocol2 = open_vconn(vconn_name, &vconn2);
1459 enum ofp_version version2 = ofputil_protocol_to_ofp_version(protocol2);
1460
1461 struct port_iterator pi;
1462 struct ofputil_phy_port pp;
1463 for (port_iterator_init(&pi, vconn); port_iterator_next(&pi, &pp); ) {
1464 if (ofp_to_u16(pp.port_no) < ofp_to_u16(OFPP_MAX)) {
1465 dump_transaction(vconn2,
1466 ofputil_encode_queue_get_config_request(
e016fb63 1467 version2, pp.port_no, queue));
56085be5
BP
1468 }
1469 }
1470 port_iterator_destroy(&pi);
1471 vconn_close(vconn2);
1472 } else {
1473 dump_transaction(vconn, ofputil_encode_queue_get_config_request(
e016fb63 1474 version, port, queue));
56085be5 1475 }
e8f9a7bb
VG
1476 vconn_close(vconn);
1477}
1478
27527aa0 1479static enum ofputil_protocol
db0b6c29
JR
1480open_vconn_for_flow_mod(const char *remote, struct vconn **vconnp,
1481 enum ofputil_protocol usable_protocols)
0fbc9f11 1482{
27527aa0
BP
1483 enum ofputil_protocol cur_protocol;
1484 char *usable_s;
1485 int i;
0fbc9f11 1486
27527aa0
BP
1487 if (!(usable_protocols & allowed_protocols)) {
1488 char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
1489 usable_s = ofputil_protocols_to_string(usable_protocols);
1490 ovs_fatal(0, "none of the usable flow formats (%s) is among the "
1491 "allowed flow formats (%s)", usable_s, allowed_s);
0fbc9f11 1492 }
0fbc9f11 1493
27527aa0
BP
1494 /* If the initial flow format is allowed and usable, keep it. */
1495 cur_protocol = open_vconn(remote, vconnp);
1496 if (usable_protocols & allowed_protocols & cur_protocol) {
1497 return cur_protocol;
1498 }
1499
1500 /* Otherwise try each flow format in turn. */
1501 for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1502 enum ofputil_protocol f = 1 << i;
1503
1504 if (f != cur_protocol
1505 && f & usable_protocols & allowed_protocols
1506 && try_set_protocol(*vconnp, f, &cur_protocol)) {
1507 return f;
1508 }
0fbc9f11 1509 }
27527aa0
BP
1510
1511 usable_s = ofputil_protocols_to_string(usable_protocols);
1512 ovs_fatal(0, "switch does not support any of the usable flow "
1513 "formats (%s)", usable_s);
0fbc9f11
BP
1514}
1515
db5076ee
JR
1516static void
1517bundle_flow_mod__(const char *remote, struct ofputil_flow_mod *fms,
1518 size_t n_fms, enum ofputil_protocol usable_protocols)
1519{
1520 enum ofputil_protocol protocol;
1521 struct vconn *vconn;
1522 struct ovs_list requests;
1523 size_t i;
1524
417e7e66 1525 ovs_list_init(&requests);
db5076ee 1526
06d4d4b6
JR
1527 /* Bundles need OpenFlow 1.3+. */
1528 usable_protocols &= OFPUTIL_P_OF13_UP;
db5076ee
JR
1529 protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
1530
1531 for (i = 0; i < n_fms; i++) {
1532 struct ofputil_flow_mod *fm = &fms[i];
1533 struct ofpbuf *request = ofputil_encode_flow_mod(fm, protocol);
1534
417e7e66 1535 ovs_list_push_back(&requests, &request->list_node);
db5076ee
JR
1536 free(CONST_CAST(struct ofpact *, fm->ofpacts));
1537 }
1538
39c94593 1539 bundle_transact(vconn, &requests, OFPBF_ORDERED | OFPBF_ATOMIC);
74cb32e3 1540 ofpbuf_list_delete(&requests);
db5076ee
JR
1541 vconn_close(vconn);
1542}
1543
064af421 1544static void
e1fef0f9 1545ofctl_flow_mod__(const char *remote, struct ofputil_flow_mod *fms,
db0b6c29 1546 size_t n_fms, enum ofputil_protocol usable_protocols)
064af421 1547{
27527aa0 1548 enum ofputil_protocol protocol;
064af421 1549 struct vconn *vconn;
27527aa0 1550 size_t i;
4989c59f 1551
db5076ee
JR
1552 if (bundle) {
1553 bundle_flow_mod__(remote, fms, n_fms, usable_protocols);
1554 return;
1555 }
1556
db0b6c29 1557 protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
049c8dc2 1558
27527aa0
BP
1559 for (i = 0; i < n_fms; i++) {
1560 struct ofputil_flow_mod *fm = &fms[i];
0fbc9f11 1561
27527aa0 1562 transact_noreply(vconn, ofputil_encode_flow_mod(fm, protocol));
dc723c44 1563 free(CONST_CAST(struct ofpact *, fm->ofpacts));
4989c59f 1564 }
064af421 1565 vconn_close(vconn);
88ca35ee
BP
1566}
1567
064af421 1568static void
db5076ee 1569ofctl_flow_mod_file(int argc OVS_UNUSED, char *argv[], int command)
064af421 1570{
db0b6c29 1571 enum ofputil_protocol usable_protocols;
27527aa0
BP
1572 struct ofputil_flow_mod *fms = NULL;
1573 size_t n_fms = 0;
bdda5aca 1574 char *error;
064af421 1575
db5076ee
JR
1576 if (command == OFPFC_ADD) {
1577 /* Allow the file to specify a mix of commands. If none specified at
1578 * the beginning of any given line, then the default is OFPFC_ADD, so
1579 * this is backwards compatible. */
1580 command = -2;
1581 }
50f96b10
BP
1582 error = parse_ofp_flow_mod_file(argv[2], ports_to_accept(argv[1]), command,
1583 &fms, &n_fms, &usable_protocols);
bdda5aca
BP
1584 if (error) {
1585 ovs_fatal(0, "%s", error);
1586 }
db0b6c29 1587 ofctl_flow_mod__(argv[1], fms, n_fms, usable_protocols);
27527aa0
BP
1588 free(fms);
1589}
1590
1591static void
e1fef0f9 1592ofctl_flow_mod(int argc, char *argv[], uint16_t command)
27527aa0 1593{
4989c59f 1594 if (argc > 2 && !strcmp(argv[2], "-")) {
e1fef0f9 1595 ofctl_flow_mod_file(argc, argv, command);
27527aa0
BP
1596 } else {
1597 struct ofputil_flow_mod fm;
bdda5aca 1598 char *error;
3200ed58 1599 enum ofputil_protocol usable_protocols;
bdda5aca 1600
50f96b10
BP
1601 error = parse_ofp_flow_mod_str(&fm, argc > 2 ? argv[2] : "",
1602 ports_to_accept(argv[1]), command,
ba2fe8e9 1603 &usable_protocols);
bdda5aca
BP
1604 if (error) {
1605 ovs_fatal(0, "%s", error);
1606 }
db0b6c29 1607 ofctl_flow_mod__(argv[1], &fm, 1, usable_protocols);
064af421 1608 }
4989c59f 1609}
88ca35ee 1610
4989c59f 1611static void
1636c761 1612ofctl_add_flow(struct ovs_cmdl_context *ctx)
4989c59f 1613{
1636c761 1614 ofctl_flow_mod(ctx->argc, ctx->argv, OFPFC_ADD);
4989c59f
BP
1615}
1616
1617static void
1636c761 1618ofctl_add_flows(struct ovs_cmdl_context *ctx)
4989c59f 1619{
1636c761 1620 ofctl_flow_mod_file(ctx->argc, ctx->argv, OFPFC_ADD);
064af421
BP
1621}
1622
1623static void
1636c761 1624ofctl_mod_flows(struct ovs_cmdl_context *ctx)
064af421 1625{
1636c761 1626 ofctl_flow_mod(ctx->argc, ctx->argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
064af421
BP
1627}
1628
88ca35ee 1629static void
1636c761 1630ofctl_del_flows(struct ovs_cmdl_context *ctx)
064af421 1631{
1636c761 1632 ofctl_flow_mod(ctx->argc, ctx->argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
064af421
BP
1633}
1634
6409e008 1635static bool
54834960 1636set_packet_in_format(struct vconn *vconn,
6409e008
BP
1637 enum nx_packet_in_format packet_in_format,
1638 bool must_succeed)
54834960 1639{
3f4a1939
SH
1640 struct ofpbuf *spif;
1641
1642 spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1643 packet_in_format);
6409e008
BP
1644 if (must_succeed) {
1645 transact_noreply(vconn, spif);
1646 } else {
1647 struct ofpbuf *reply;
1648
1649 run(vconn_transact_noreply(vconn, spif, &reply),
1650 "talking to %s", vconn_get_name(vconn));
1651 if (reply) {
50f96b10 1652 char *s = ofp_to_string(reply->data, reply->size, NULL, 2);
6409e008
BP
1653 VLOG_DBG("%s: failed to set packet in format to nx_packet_in, "
1654 "controller replied: %s.",
1655 vconn_get_name(vconn), s);
1656 free(s);
1657 ofpbuf_delete(reply);
1658
1659 return false;
1660 } else {
1661 VLOG_DBG("%s: using user-specified packet in format %s",
1662 vconn_get_name(vconn),
1663 ofputil_packet_in_format_to_string(packet_in_format));
1664 }
1665 }
1666 return true;
54834960
EJ
1667}
1668
f0fd1a17
PS
1669static int
1670monitor_set_invalid_ttl_to_controller(struct vconn *vconn)
1671{
ad99e2ed 1672 struct ofputil_switch_config config;
f0fd1a17
PS
1673
1674 fetch_switch_config(vconn, &config);
ad99e2ed
BP
1675 if (!config.invalid_ttl_to_controller) {
1676 config.invalid_ttl_to_controller = 1;
f0fd1a17
PS
1677 set_switch_config(vconn, &config);
1678
1679 /* Then retrieve the configuration to see if it really took. OpenFlow
ad99e2ed
BP
1680 * has ill-defined error reporting for bad flags, so this is about the
1681 * best we can do. */
f0fd1a17 1682 fetch_switch_config(vconn, &config);
ad99e2ed 1683 if (!config.invalid_ttl_to_controller) {
f0fd1a17 1684 ovs_fatal(0, "setting invalid_ttl_to_controller failed (this "
ad99e2ed 1685 "switch probably doesn't support this flag)");
f0fd1a17
PS
1686 }
1687 }
1688 return 0;
1689}
1690
96761f58
BP
1691/* Converts hex digits in 'hex' to an OpenFlow message in '*msgp'. The
1692 * caller must free '*msgp'. On success, returns NULL. On failure, returns
1693 * an error message and stores NULL in '*msgp'. */
1694static const char *
1695openflow_from_hex(const char *hex, struct ofpbuf **msgp)
1696{
1697 struct ofp_header *oh;
1698 struct ofpbuf *msg;
1699
1700 msg = ofpbuf_new(strlen(hex) / 2);
1701 *msgp = NULL;
1702
1703 if (ofpbuf_put_hex(msg, hex, NULL)[0] != '\0') {
1704 ofpbuf_delete(msg);
1705 return "Trailing garbage in hex data";
1706 }
1707
6fd6ed71 1708 if (msg->size < sizeof(struct ofp_header)) {
96761f58
BP
1709 ofpbuf_delete(msg);
1710 return "Message too short for OpenFlow";
1711 }
1712
6fd6ed71
PS
1713 oh = msg->data;
1714 if (msg->size != ntohs(oh->length)) {
96761f58
BP
1715 ofpbuf_delete(msg);
1716 return "Message size does not match length in OpenFlow header";
1717 }
1718
1719 *msgp = msg;
1720 return NULL;
1721}
1722
1723static void
1724ofctl_send(struct unixctl_conn *conn, int argc,
1725 const char *argv[], void *vconn_)
1726{
1727 struct vconn *vconn = vconn_;
1728 struct ds reply;
1729 bool ok;
1730 int i;
1731
1732 ok = true;
1733 ds_init(&reply);
1734 for (i = 1; i < argc; i++) {
1735 const char *error_msg;
1736 struct ofpbuf *msg;
1737 int error;
1738
1739 error_msg = openflow_from_hex(argv[i], &msg);
1740 if (error_msg) {
1741 ds_put_format(&reply, "%s\n", error_msg);
1742 ok = false;
1743 continue;
1744 }
1745
1746 fprintf(stderr, "send: ");
50f96b10
BP
1747 ofp_print(stderr, msg->data, msg->size,
1748 ports_to_show(vconn_get_name(vconn)), verbosity);
96761f58
BP
1749
1750 error = vconn_send_block(vconn, msg);
1751 if (error) {
1752 ofpbuf_delete(msg);
10a89ef0 1753 ds_put_format(&reply, "%s\n", ovs_strerror(error));
96761f58
BP
1754 ok = false;
1755 } else {
1756 ds_put_cstr(&reply, "sent\n");
1757 }
1758 }
bde9f75d
EJ
1759
1760 if (ok) {
1761 unixctl_command_reply(conn, ds_cstr(&reply));
1762 } else {
1763 unixctl_command_reply_error(conn, ds_cstr(&reply));
1764 }
96761f58
BP
1765 ds_destroy(&reply);
1766}
1767
6dd3c787
JR
1768static void
1769unixctl_packet_out(struct unixctl_conn *conn, int OVS_UNUSED argc,
1770 const char *argv[], void *vconn_)
1771{
1772 struct vconn *vconn = vconn_;
1773 enum ofputil_protocol protocol
1774 = ofputil_protocol_from_ofp_version(vconn_get_version(vconn));
1775 struct ds reply = DS_EMPTY_INITIALIZER;
1776 bool ok = true;
1777
1778 enum ofputil_protocol usable_protocols;
1779 struct ofputil_packet_out po;
1780 char *error_msg;
1781
50f96b10
BP
1782 error_msg = parse_ofp_packet_out_str(
1783 &po, argv[1], ports_to_accept(vconn_get_name(vconn)),
1784 &usable_protocols);
6dd3c787
JR
1785 if (error_msg) {
1786 ds_put_format(&reply, "%s\n", error_msg);
1787 free(error_msg);
1788 ok = false;
1789 }
1790
1791 if (ok && !(usable_protocols & protocol)) {
1792 ds_put_format(&reply, "PACKET_OUT actions are incompatible with the OpenFlow connection.\n");
1793 ok = false;
1794 }
1795
1796 if (ok) {
1797 struct ofpbuf *msg = ofputil_encode_packet_out(&po, protocol);
1798
50f96b10
BP
1799 ofp_print(stderr, msg->data, msg->size,
1800 ports_to_show(vconn_get_name(vconn)), verbosity);
6dd3c787
JR
1801
1802 int error = vconn_send_block(vconn, msg);
1803 if (error) {
1804 ofpbuf_delete(msg);
1805 ds_put_format(&reply, "%s\n", ovs_strerror(error));
1806 ok = false;
1807 }
1808 }
1809
1810 if (ok) {
1811 unixctl_command_reply(conn, ds_cstr(&reply));
1812 } else {
1813 unixctl_command_reply_error(conn, ds_cstr(&reply));
1814 }
1815 ds_destroy(&reply);
1816
1817 if (!error_msg) {
1818 free(CONST_CAST(void *, po.packet));
1819 free(po.ofpacts);
1820 }
1821}
1822
bb638b9a
BP
1823struct barrier_aux {
1824 struct vconn *vconn; /* OpenFlow connection for sending barrier. */
1825 struct unixctl_conn *conn; /* Connection waiting for barrier response. */
1826};
1827
1828static void
1829ofctl_barrier(struct unixctl_conn *conn, int argc OVS_UNUSED,
1830 const char *argv[] OVS_UNUSED, void *aux_)
1831{
1832 struct barrier_aux *aux = aux_;
1833 struct ofpbuf *msg;
1834 int error;
1835
1836 if (aux->conn) {
bde9f75d 1837 unixctl_command_reply_error(conn, "already waiting for barrier reply");
bb638b9a
BP
1838 return;
1839 }
1840
a0ae0b6e 1841 msg = ofputil_encode_barrier_request(vconn_get_version(aux->vconn));
bb638b9a
BP
1842 error = vconn_send_block(aux->vconn, msg);
1843 if (error) {
1844 ofpbuf_delete(msg);
10a89ef0 1845 unixctl_command_reply_error(conn, ovs_strerror(error));
bb638b9a
BP
1846 } else {
1847 aux->conn = conn;
1848 }
1849}
1850
1e1d00a5
BP
1851static void
1852ofctl_set_output_file(struct unixctl_conn *conn, int argc OVS_UNUSED,
1853 const char *argv[], void *aux OVS_UNUSED)
1854{
1855 int fd;
1856
1857 fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
1858 if (fd < 0) {
10a89ef0 1859 unixctl_command_reply_error(conn, ovs_strerror(errno));
1e1d00a5
BP
1860 return;
1861 }
1862
1863 fflush(stderr);
1864 dup2(fd, STDERR_FILENO);
1865 close(fd);
bde9f75d 1866 unixctl_command_reply(conn, NULL);
1e1d00a5
BP
1867}
1868
2b07c8b1
BP
1869static void
1870ofctl_block(struct unixctl_conn *conn, int argc OVS_UNUSED,
4f8f2439 1871 const char *argv[] OVS_UNUSED, void *blocked_)
2b07c8b1 1872{
4f8f2439 1873 bool *blocked = blocked_;
2b07c8b1 1874
4f8f2439
BP
1875 if (!*blocked) {
1876 *blocked = true;
1877 unixctl_command_reply(conn, NULL);
1878 } else {
2b07c8b1 1879 unixctl_command_reply(conn, "already blocking");
2b07c8b1
BP
1880 }
1881}
1882
1883static void
1884ofctl_unblock(struct unixctl_conn *conn, int argc OVS_UNUSED,
4f8f2439 1885 const char *argv[] OVS_UNUSED, void *blocked_)
2b07c8b1 1886{
4f8f2439 1887 bool *blocked = blocked_;
2b07c8b1 1888
4f8f2439
BP
1889 if (*blocked) {
1890 *blocked = false;
2b07c8b1 1891 unixctl_command_reply(conn, NULL);
4f8f2439
BP
1892 } else {
1893 unixctl_command_reply(conn, "already unblocked");
2b07c8b1
BP
1894 }
1895}
1896
140f36ba 1897/* Prints to stderr all of the messages received on 'vconn'.
05f453a8
BP
1898 *
1899 * Iff 'reply_to_echo_requests' is true, sends a reply to any echo request
77ab5fd2
BP
1900 * received on 'vconn'.
1901 *
1902 * If 'resume_continuations' is true, sends an NXT_RESUME in reply to any
1903 * NXT_PACKET_IN2 that includes a continuation. */
064af421 1904static void
77ab5fd2
BP
1905monitor_vconn(struct vconn *vconn, bool reply_to_echo_requests,
1906 bool resume_continuations)
0caf6bde 1907{
bb638b9a 1908 struct barrier_aux barrier_aux = { vconn, NULL };
1eb85ef5
EJ
1909 struct unixctl_server *server;
1910 bool exiting = false;
4f8f2439 1911 bool blocked = false;
7d0c5973 1912 int error;
1eb85ef5 1913
7d0c5973 1914 daemon_save_fd(STDERR_FILENO);
e91b927d 1915 daemonize_start(false);
19945013 1916 error = unixctl_server_create(unixctl_path, &server);
1eb85ef5
EJ
1917 if (error) {
1918 ovs_fatal(error, "failed to create unixctl server");
1919 }
1920 unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
96761f58
BP
1921 unixctl_command_register("ofctl/send", "OFMSG...", 1, INT_MAX,
1922 ofctl_send, vconn);
6dd3c787
JR
1923 unixctl_command_register("ofctl/packet-out", "\"in_port=<port> packet=<hex data> actions=...\"", 1, 1,
1924 unixctl_packet_out, vconn);
bb638b9a
BP
1925 unixctl_command_register("ofctl/barrier", "", 0, 0,
1926 ofctl_barrier, &barrier_aux);
1e1d00a5
BP
1927 unixctl_command_register("ofctl/set-output-file", "FILE", 1, 1,
1928 ofctl_set_output_file, NULL);
2b07c8b1 1929
4f8f2439
BP
1930 unixctl_command_register("ofctl/block", "", 0, 0, ofctl_block, &blocked);
1931 unixctl_command_register("ofctl/unblock", "", 0, 0, ofctl_unblock,
1932 &blocked);
2b07c8b1 1933
1eb85ef5
EJ
1934 daemonize_complete();
1935
77ab5fd2
BP
1936 enum ofp_version version = vconn_get_version(vconn);
1937 enum ofputil_protocol protocol
1938 = ofputil_protocol_from_ofp_version(version);
1939
0caf6bde
BP
1940 for (;;) {
1941 struct ofpbuf *b;
1eb85ef5
EJ
1942 int retval;
1943
1944 unixctl_server_run(server);
982697a4 1945
4f8f2439 1946 while (!blocked) {
982697a4 1947 enum ofptype type;
bb638b9a 1948
1eb85ef5
EJ
1949 retval = vconn_recv(vconn, &b);
1950 if (retval == EAGAIN) {
1951 break;
1952 }
1eb85ef5 1953 run(retval, "vconn_recv");
31c6fcd7 1954
0c9560b7 1955 if (timestamp) {
2b31d8e7
PI
1956 char *s = xastrftime_msec("%Y-%m-%d %H:%M:%S.###: ",
1957 time_wall_msec(), true);
0c9560b7 1958 fputs(s, stderr);
3e78870d 1959 free(s);
0c9560b7 1960 }
31c6fcd7 1961
6fd6ed71 1962 ofptype_decode(&type, b->data);
50f96b10
BP
1963 ofp_print(stderr, b->data, b->size,
1964 ports_to_show(vconn_get_name(vconn)), verbosity + 2);
eafa7af8 1965 fflush(stderr);
bb638b9a 1966
05f453a8
BP
1967 switch ((int) type) {
1968 case OFPTYPE_BARRIER_REPLY:
1969 if (barrier_aux.conn) {
1970 unixctl_command_reply(barrier_aux.conn, NULL);
1971 barrier_aux.conn = NULL;
1972 }
1973 break;
1974
1975 case OFPTYPE_ECHO_REQUEST:
1976 if (reply_to_echo_requests) {
1977 struct ofpbuf *reply;
1978
6fd6ed71 1979 reply = make_echo_reply(b->data);
05f453a8
BP
1980 retval = vconn_send_block(vconn, reply);
1981 if (retval) {
1982 ovs_fatal(retval, "failed to send echo reply");
1983 }
1984 }
1985 break;
77ab5fd2
BP
1986
1987 case OFPTYPE_PACKET_IN:
1988 if (resume_continuations) {
1989 struct ofputil_packet_in pin;
1990 struct ofpbuf continuation;
1991
3cddeff0
YHW
1992 error = ofputil_decode_packet_in(b->data, true, NULL, NULL,
1993 &pin, NULL, NULL,
77ab5fd2
BP
1994 &continuation);
1995 if (error) {
1996 fprintf(stderr, "decoding packet-in failed: %s",
1997 ofperr_to_string(error));
1998 } else if (continuation.size) {
1999 struct ofpbuf *reply;
2000
2001 reply = ofputil_encode_resume(&pin, &continuation,
2002 protocol);
2003
2004 fprintf(stderr, "send: ");
2005 ofp_print(stderr, reply->data, reply->size,
50f96b10 2006 ports_to_show(vconn_get_name(vconn)),
77ab5fd2
BP
2007 verbosity + 2);
2008 fflush(stderr);
2009
2010 retval = vconn_send_block(vconn, reply);
2011 if (retval) {
2012 ovs_fatal(retval, "failed to send NXT_RESUME");
2013 }
2014 }
2015 }
2016 break;
bb638b9a 2017 }
05f453a8 2018 ofpbuf_delete(b);
1eb85ef5
EJ
2019 }
2020
2021 if (exiting) {
2022 break;
2023 }
2024
2025 vconn_run(vconn);
2026 vconn_run_wait(vconn);
4f8f2439
BP
2027 if (!blocked) {
2028 vconn_recv_wait(vconn);
2029 }
1eb85ef5
EJ
2030 unixctl_server_wait(server);
2031 poll_block();
0caf6bde 2032 }
828c72d0
BP
2033 vconn_close(vconn);
2034 unixctl_server_destroy(server);
0caf6bde
BP
2035}
2036
2037static void
1636c761 2038ofctl_monitor(struct ovs_cmdl_context *ctx)
064af421
BP
2039{
2040 struct vconn *vconn;
2b07c8b1 2041 int i;
db0b6c29 2042 enum ofputil_protocol usable_protocols;
064af421 2043
ad99e2ed
BP
2044 /* If the user wants the invalid_ttl_to_controller feature, limit the
2045 * OpenFlow versions to those that support that feature. (Support in
2046 * OpenFlow 1.0 is an Open vSwitch extension.) */
2047 for (i = 2; i < ctx->argc; i++) {
2048 if (!strcmp(ctx->argv[i], "invalid_ttl")) {
2049 uint32_t usable_versions = ((1u << OFP10_VERSION) |
2050 (1u << OFP11_VERSION) |
2051 (1u << OFP12_VERSION));
2052 uint32_t allowed_versions = get_allowed_ofp_versions();
2053 if (!(allowed_versions & usable_versions)) {
2054 struct ds versions = DS_EMPTY_INITIALIZER;
2055 ofputil_format_version_bitmap_names(&versions,
2056 usable_versions);
2057 ovs_fatal(0, "invalid_ttl requires one of the OpenFlow "
2058 "versions %s but none is enabled (use -O)",
2059 ds_cstr(&versions));
2060 }
2061 mask_allowed_ofp_versions(usable_versions);
2062 break;
2063 }
2064 }
2065
1636c761 2066 open_vconn(ctx->argv[1], &vconn);
77ab5fd2 2067 bool resume_continuations = false;
1636c761
RB
2068 for (i = 2; i < ctx->argc; i++) {
2069 const char *arg = ctx->argv[i];
064af421 2070
2b07c8b1 2071 if (isdigit((unsigned char) *arg)) {
ad99e2ed 2072 struct ofputil_switch_config config;
2b07c8b1
BP
2073
2074 fetch_switch_config(vconn, &config);
ad99e2ed 2075 config.miss_send_len = atoi(arg);
2b07c8b1
BP
2076 set_switch_config(vconn, &config);
2077 } else if (!strcmp(arg, "invalid_ttl")) {
f0fd1a17 2078 monitor_set_invalid_ttl_to_controller(vconn);
2b07c8b1
BP
2079 } else if (!strncmp(arg, "watch:", 6)) {
2080 struct ofputil_flow_monitor_request fmr;
2081 struct ofpbuf *msg;
bdda5aca 2082 char *error;
2b07c8b1 2083
db0b6c29 2084 error = parse_flow_monitor_request(&fmr, arg + 6,
50f96b10 2085 ports_to_accept(ctx->argv[1]),
db0b6c29 2086 &usable_protocols);
bdda5aca
BP
2087 if (error) {
2088 ovs_fatal(0, "%s", error);
2089 }
2b07c8b1
BP
2090
2091 msg = ofpbuf_new(0);
2092 ofputil_append_flow_monitor_request(&fmr, msg);
182b2eef 2093 dump_transaction(vconn, msg);
eafa7af8 2094 fflush(stdout);
77ab5fd2
BP
2095 } else if (!strcmp(arg, "resume")) {
2096 /* This option is intentionally undocumented because it is meant
2097 * only for testing. */
2098 resume_continuations = true;
2099
2100 /* Set miss_send_len to ensure that we get packet-ins. */
2101 struct ofputil_switch_config config;
2102 fetch_switch_config(vconn, &config);
2103 config.miss_send_len = UINT16_MAX;
2104 set_switch_config(vconn, &config);
2b07c8b1
BP
2105 } else {
2106 ovs_fatal(0, "%s: unsupported \"monitor\" argument", arg);
f0fd1a17
PS
2107 }
2108 }
2b07c8b1 2109
ca8526e0 2110 if (preferred_packet_in_format >= 0) {
6409e008
BP
2111 /* A particular packet-in format was requested, so we must set it. */
2112 set_packet_in_format(vconn, preferred_packet_in_format, true);
ca8526e0 2113 } else {
6409e008
BP
2114 /* Otherwise, we always prefer NXT_PACKET_IN2. */
2115 if (!set_packet_in_format(vconn, NXPIF_NXT_PACKET_IN2, false)) {
2116 /* We can't get NXT_PACKET_IN2. For OpenFlow 1.0 only, request
2117 * NXT_PACKET_IN. (Before 2.6, Open vSwitch will accept a request
2118 * for NXT_PACKET_IN with OF1.1+, but even after that it still
2119 * sends packet-ins in the OpenFlow native format.) */
2120 if (vconn_get_version(vconn) == OFP10_VERSION) {
2121 set_packet_in_format(vconn, NXPIF_NXT_PACKET_IN, false);
f02b12c4 2122 }
ca8526e0
BP
2123 }
2124 }
2125
77ab5fd2 2126 monitor_vconn(vconn, true, resume_continuations);
0caf6bde
BP
2127}
2128
2129static void
1636c761 2130ofctl_snoop(struct ovs_cmdl_context *ctx)
0caf6bde
BP
2131{
2132 struct vconn *vconn;
2133
1636c761 2134 open_vconn__(ctx->argv[1], SNOOP, &vconn);
77ab5fd2 2135 monitor_vconn(vconn, false, false);
064af421
BP
2136}
2137
2138static void
1636c761 2139ofctl_dump_ports(struct ovs_cmdl_context *ctx)
064af421 2140{
abaad8cf 2141 struct ofpbuf *request;
53514387 2142 struct vconn *vconn;
4e022ec0 2143 ofp_port_t port;
abaad8cf 2144
1636c761
RB
2145 open_vconn(ctx->argv[1], &vconn);
2146 port = ctx->argc > 2 ? str_to_port_no(ctx->argv[1], ctx->argv[2]) : OFPP_ANY;
f8e4867e 2147 request = ofputil_encode_dump_ports_request(vconn_get_version(vconn), port);
182b2eef 2148 dump_transaction(vconn, request);
53514387 2149 vconn_close(vconn);
064af421
BP
2150}
2151
2be393ed 2152static void
1636c761 2153ofctl_dump_ports_desc(struct ovs_cmdl_context *ctx)
2be393ed 2154{
70ae4f93
BP
2155 struct ofpbuf *request;
2156 struct vconn *vconn;
2157 ofp_port_t port;
2158
1636c761
RB
2159 open_vconn(ctx->argv[1], &vconn);
2160 port = ctx->argc > 2 ? str_to_port_no(ctx->argv[1], ctx->argv[2]) : OFPP_ANY;
70ae4f93
BP
2161 request = ofputil_encode_port_desc_stats_request(vconn_get_version(vconn),
2162 port);
182b2eef 2163 dump_transaction(vconn, request);
70ae4f93 2164 vconn_close(vconn);
2be393ed
JP
2165}
2166
064af421 2167static void
1636c761 2168ofctl_probe(struct ovs_cmdl_context *ctx)
064af421
BP
2169{
2170 struct ofpbuf *request;
2171 struct vconn *vconn;
2172 struct ofpbuf *reply;
2173
1636c761 2174 open_vconn(ctx->argv[1], &vconn);
1a126c0c 2175 request = make_echo_request(vconn_get_version(vconn));
1636c761 2176 run(vconn_transact(vconn, request, &reply), "talking to %s", ctx->argv[1]);
6fd6ed71 2177 if (reply->size != sizeof(struct ofp_header)) {
064af421
BP
2178 ovs_fatal(0, "reply does not match request");
2179 }
2180 ofpbuf_delete(reply);
2181 vconn_close(vconn);
2182}
2183
0c3d5fc8 2184static void
1636c761 2185ofctl_packet_out(struct ovs_cmdl_context *ctx)
0c3d5fc8 2186{
6dd3c787 2187 enum ofputil_protocol usable_protocols;
de0f3156 2188 enum ofputil_protocol protocol;
0c3d5fc8 2189 struct ofputil_packet_out po;
0c3d5fc8 2190 struct vconn *vconn;
6dd3c787 2191 struct ofpbuf *opo;
bdda5aca 2192 char *error;
0c3d5fc8 2193
35eb6326 2194 match_init_catchall(&po.flow_metadata);
6dd3c787
JR
2195 /* Use the old syntax when more than 4 arguments are given. */
2196 if (ctx->argc > 4) {
2197 struct ofpbuf ofpacts;
2198 int i;
0c3d5fc8 2199
6dd3c787 2200 ofpbuf_init(&ofpacts, 64);
efefbcae
BP
2201 struct ofpact_parse_params pp = {
2202 .port_map = ports_to_accept(ctx->argv[1]),
2203 .ofpacts = &ofpacts,
2204 .usable_protocols = &usable_protocols
2205 };
2206 error = ofpacts_parse_actions(ctx->argv[3], &pp);
6dd3c787
JR
2207 if (error) {
2208 ovs_fatal(0, "%s", error);
2209 }
0c3d5fc8 2210
6dd3c787 2211 po.buffer_id = UINT32_MAX;
35eb6326
YHW
2212 match_set_in_port(&po.flow_metadata,
2213 str_to_port_no(ctx->argv[1], ctx->argv[2]));
6dd3c787
JR
2214 po.ofpacts = ofpacts.data;
2215 po.ofpacts_len = ofpacts.size;
cb1145d1 2216 po.flow_metadata.flow.packet_type = htonl(PT_ETH);
0c3d5fc8 2217
6dd3c787
JR
2218 protocol = open_vconn_for_flow_mod(ctx->argv[1], &vconn,
2219 usable_protocols);
2220 for (i = 4; i < ctx->argc; i++) {
2221 struct dp_packet *packet;
2222 const char *error_msg;
2223
2224 error_msg = eth_from_hex(ctx->argv[i], &packet);
2225 if (error_msg) {
2226 ovs_fatal(0, "%s", error_msg);
2227 }
0c3d5fc8 2228
6dd3c787
JR
2229 po.packet = dp_packet_data(packet);
2230 po.packet_len = dp_packet_size(packet);
2231 opo = ofputil_encode_packet_out(&po, protocol);
2232 transact_noreply(vconn, opo);
2233 dp_packet_delete(packet);
2234 }
2235 vconn_close(vconn);
2236 ofpbuf_uninit(&ofpacts);
2237 } else if (ctx->argc == 3) {
50f96b10
BP
2238 error = parse_ofp_packet_out_str(&po, ctx->argv[2],
2239 ports_to_accept(ctx->argv[1]),
2240 &usable_protocols);
6dd3c787
JR
2241 if (error) {
2242 ovs_fatal(0, "%s", error);
2243 }
2244 protocol = open_vconn_for_flow_mod(ctx->argv[1], &vconn,
2245 usable_protocols);
de0f3156 2246 opo = ofputil_encode_packet_out(&po, protocol);
0c3d5fc8 2247 transact_noreply(vconn, opo);
5a329e85 2248 vconn_close(vconn);
6dd3c787
JR
2249 free(CONST_CAST(void *, po.packet));
2250 free(po.ofpacts);
2251 } else {
2252 ovs_fatal(0, "Too many arguments (%d)", ctx->argc);
0c3d5fc8 2253 }
0c3d5fc8
BP
2254}
2255
064af421 2256static void
1636c761 2257ofctl_mod_port(struct ovs_cmdl_context *ctx)
064af421 2258{
28124950
BP
2259 struct ofp_config_flag {
2260 const char *name; /* The flag's name. */
2261 enum ofputil_port_config bit; /* Bit to turn on or off. */
2262 bool on; /* Value to set the bit to. */
2263 };
2264 static const struct ofp_config_flag flags[] = {
2265 { "up", OFPUTIL_PC_PORT_DOWN, false },
2266 { "down", OFPUTIL_PC_PORT_DOWN, true },
2267 { "stp", OFPUTIL_PC_NO_STP, false },
2268 { "receive", OFPUTIL_PC_NO_RECV, false },
2269 { "receive-stp", OFPUTIL_PC_NO_RECV_STP, false },
2270 { "flood", OFPUTIL_PC_NO_FLOOD, false },
2271 { "forward", OFPUTIL_PC_NO_FWD, false },
2272 { "packet-in", OFPUTIL_PC_NO_PACKET_IN, false },
2273 };
2274
2275 const struct ofp_config_flag *flag;
9e1fd49b
BP
2276 enum ofputil_protocol protocol;
2277 struct ofputil_port_mod pm;
2278 struct ofputil_phy_port pp;
064af421 2279 struct vconn *vconn;
28124950
BP
2280 const char *command;
2281 bool not;
064af421 2282
1636c761 2283 fetch_ofputil_phy_port(ctx->argv[1], ctx->argv[2], &pp);
064af421 2284
9e1fd49b 2285 pm.port_no = pp.port_no;
74ff3298 2286 pm.hw_addr = pp.hw_addr;
2f2b904f 2287 pm.hw_addr64 = pp.hw_addr64;
9e1fd49b
BP
2288 pm.config = 0;
2289 pm.mask = 0;
2290 pm.advertise = 0;
064af421 2291
1636c761
RB
2292 if (!strncasecmp(ctx->argv[3], "no-", 3)) {
2293 command = ctx->argv[3] + 3;
28124950 2294 not = true;
1636c761
RB
2295 } else if (!strncasecmp(ctx->argv[3], "no", 2)) {
2296 command = ctx->argv[3] + 2;
28124950 2297 not = true;
064af421 2298 } else {
1636c761 2299 command = ctx->argv[3];
28124950
BP
2300 not = false;
2301 }
2302 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
2303 if (!strcasecmp(command, flag->name)) {
2304 pm.mask = flag->bit;
2305 pm.config = flag->on ^ not ? flag->bit : 0;
2306 goto found;
2307 }
064af421 2308 }
1636c761 2309 ovs_fatal(0, "unknown mod-port command '%s'", ctx->argv[3]);
064af421 2310
28124950 2311found:
1636c761 2312 protocol = open_vconn(ctx->argv[1], &vconn);
9e1fd49b 2313 transact_noreply(vconn, ofputil_encode_port_mod(&pm, protocol));
064af421
BP
2314 vconn_close(vconn);
2315}
2316
de7d3c07
SJ
2317/* This function uses OFPMP14_TABLE_DESC request to get the current
2318 * table configuration from switch. The function then modifies
2319 * only that table-config property, which has been requested. */
2320static void
2321fetch_table_desc(struct vconn *vconn, struct ofputil_table_mod *tm,
2322 struct ofputil_table_desc *td)
2323{
2324 struct ofpbuf *request;
2325 ovs_be32 send_xid;
2326 bool done = false;
2327 bool found = false;
2328
2329 request = ofputil_encode_table_desc_request(vconn_get_version(vconn));
2330 send_xid = ((struct ofp_header *) request->data)->xid;
2331 send_openflow_buffer(vconn, request);
2332 while (!done) {
2333 ovs_be32 recv_xid;
2334 struct ofpbuf *reply;
2335
2336 run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
2337 recv_xid = ((struct ofp_header *) reply->data)->xid;
2338 if (send_xid == recv_xid) {
2339 struct ofp_header *oh = reply->data;
0a2869d5 2340 struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
de7d3c07 2341
0a2869d5 2342 enum ofptype type;
de7d3c07
SJ
2343 if (ofptype_pull(&type, &b)
2344 || type != OFPTYPE_TABLE_DESC_REPLY) {
2345 ovs_fatal(0, "received bad reply: %s",
50f96b10 2346 ofp_to_string(reply->data, reply->size, NULL,
de7d3c07
SJ
2347 verbosity + 1));
2348 }
0a2869d5 2349 uint16_t flags = ofpmp_flags(oh);
de7d3c07
SJ
2350 done = !(flags & OFPSF_REPLY_MORE);
2351 if (found) {
2352 /* We've already found the table desc consisting of current
2353 * table configuration, but we need to drain the queue of
2354 * any other replies for this request. */
2355 continue;
2356 }
2357 while (!ofputil_decode_table_desc(&b, td, oh->version)) {
2358 if (td->table_id == tm->table_id) {
2359 found = true;
2360 break;
2361 }
2362 }
2363 } else {
2364 VLOG_DBG("received reply with xid %08"PRIx32" "
2365 "!= expected %08"PRIx32, recv_xid, send_xid);
2366 }
2367 ofpbuf_delete(reply);
2368 }
2369 if (tm->eviction != OFPUTIL_TABLE_EVICTION_DEFAULT) {
2370 tm->vacancy = td->vacancy;
2371 tm->table_vacancy.vacancy_down = td->table_vacancy.vacancy_down;
2372 tm->table_vacancy.vacancy_up = td->table_vacancy.vacancy_up;
2373 } else if (tm->vacancy != OFPUTIL_TABLE_VACANCY_DEFAULT) {
2374 tm->eviction = td->eviction;
2375 tm->eviction_flags = td->eviction_flags;
2376 }
2377}
2378
918f2b82 2379static void
1636c761 2380ofctl_mod_table(struct ovs_cmdl_context *ctx)
918f2b82 2381{
82c22d34 2382 uint32_t usable_versions;
918f2b82
AZ
2383 struct ofputil_table_mod tm;
2384 struct vconn *vconn;
2385 char *error;
de7d3c07 2386 int i;
918f2b82 2387
82c22d34
BP
2388 error = parse_ofp_table_mod(&tm, ctx->argv[2], ctx->argv[3],
2389 &usable_versions);
918f2b82
AZ
2390 if (error) {
2391 ovs_fatal(0, "%s", error);
2392 }
2393
82c22d34
BP
2394 uint32_t allowed_versions = get_allowed_ofp_versions();
2395 if (!(allowed_versions & usable_versions)) {
2396 struct ds versions = DS_EMPTY_INITIALIZER;
de7d3c07 2397 ofputil_format_version_bitmap_names(&versions, usable_versions);
82c22d34 2398 ovs_fatal(0, "table_mod '%s' requires one of the OpenFlow "
de7d3c07 2399 "versions %s",
82c22d34 2400 ctx->argv[3], ds_cstr(&versions));
918f2b82 2401 }
82c22d34 2402 mask_allowed_ofp_versions(usable_versions);
82c22d34 2403 enum ofputil_protocol protocol = open_vconn(ctx->argv[1], &vconn);
de7d3c07
SJ
2404
2405 /* For OpenFlow 1.4+, ovs-ofctl mod-table should not affect table-config
2406 * properties that the user didn't ask to change, so it is necessary to
2407 * restore the current configuration of table-config parameters using
2408 * OFPMP14_TABLE_DESC request. */
2409 if ((allowed_versions & (1u << OFP14_VERSION)) ||
2410 (allowed_versions & (1u << OFP15_VERSION))) {
2411 struct ofputil_table_desc td;
2412
2413 if (tm.table_id == OFPTT_ALL) {
2414 for (i = 0; i < OFPTT_MAX; i++) {
2415 tm.table_id = i;
2416 fetch_table_desc(vconn, &tm, &td);
2417 transact_noreply(vconn,
2418 ofputil_encode_table_mod(&tm, protocol));
2419 }
2420 } else {
2421 fetch_table_desc(vconn, &tm, &td);
2422 transact_noreply(vconn, ofputil_encode_table_mod(&tm, protocol));
2423 }
2424 } else {
2425 transact_noreply(vconn, ofputil_encode_table_mod(&tm, protocol));
2426 }
918f2b82
AZ
2427 vconn_close(vconn);
2428}
2429
7257b535 2430static void
1636c761 2431ofctl_get_frags(struct ovs_cmdl_context *ctx)
7257b535 2432{
ad99e2ed 2433 struct ofputil_switch_config config;
7257b535
BP
2434 struct vconn *vconn;
2435
1636c761 2436 open_vconn(ctx->argv[1], &vconn);
7257b535 2437 fetch_switch_config(vconn, &config);
ad99e2ed 2438 puts(ofputil_frag_handling_to_string(config.frag));
7257b535
BP
2439 vconn_close(vconn);
2440}
2441
2442static void
1636c761 2443ofctl_set_frags(struct ovs_cmdl_context *ctx)
7257b535 2444{
ad99e2ed
BP
2445 struct ofputil_switch_config config;
2446 enum ofputil_frag_handling frag;
7257b535 2447 struct vconn *vconn;
7257b535 2448
ad99e2ed 2449 if (!ofputil_frag_handling_from_string(ctx->argv[2], &frag)) {
1636c761 2450 ovs_fatal(0, "%s: unknown fragment handling mode", ctx->argv[2]);
7257b535
BP
2451 }
2452
1636c761 2453 open_vconn(ctx->argv[1], &vconn);
7257b535 2454 fetch_switch_config(vconn, &config);
ad99e2ed 2455 if (frag != config.frag) {
7257b535 2456 /* Set the configuration. */
ad99e2ed 2457 config.frag = frag;
7257b535
BP
2458 set_switch_config(vconn, &config);
2459
2460 /* Then retrieve the configuration to see if it really took. OpenFlow
ad99e2ed
BP
2461 * has ill-defined error reporting for bad flags, so this is about the
2462 * best we can do. */
7257b535 2463 fetch_switch_config(vconn, &config);
ad99e2ed 2464 if (frag != config.frag) {
7257b535
BP
2465 ovs_fatal(0, "%s: setting fragment handling mode failed (this "
2466 "switch probably doesn't support mode \"%s\")",
ad99e2ed 2467 ctx->argv[1], ofputil_frag_handling_to_string(frag));
7257b535
BP
2468 }
2469 }
2470 vconn_close(vconn);
2471}
2472
1ac0e975 2473static void
1636c761 2474ofctl_ofp_parse(struct ovs_cmdl_context *ctx)
1ac0e975 2475{
1636c761 2476 const char *filename = ctx->argv[1];
1ac0e975
BP
2477 struct ofpbuf b;
2478 FILE *file;
2479
2480 file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
2481 if (file == NULL) {
2482 ovs_fatal(errno, "%s: open", filename);
2483 }
2484
2485 ofpbuf_init(&b, 65536);
2486 for (;;) {
2487 struct ofp_header *oh;
2488 size_t length, tail_len;
2489 void *tail;
2490 size_t n;
2491
2492 ofpbuf_clear(&b);
2493 oh = ofpbuf_put_uninit(&b, sizeof *oh);
2494 n = fread(oh, 1, sizeof *oh, file);
2495 if (n == 0) {
2496 break;
2497 } else if (n < sizeof *oh) {
2498 ovs_fatal(0, "%s: unexpected end of file mid-message", filename);
2499 }
2500
2501 length = ntohs(oh->length);
2502 if (length < sizeof *oh) {
34582733 2503 ovs_fatal(0, "%s: %"PRIuSIZE"-byte message is too short for OpenFlow",
1ac0e975
BP
2504 filename, length);
2505 }
2506
2507 tail_len = length - sizeof *oh;
2508 tail = ofpbuf_put_uninit(&b, tail_len);
2509 n = fread(tail, 1, tail_len, file);
2510 if (n < tail_len) {
2511 ovs_fatal(0, "%s: unexpected end of file mid-message", filename);
2512 }
2513
50f96b10 2514 ofp_print(stdout, b.data, b.size, NULL, verbosity + 2);
1ac0e975
BP
2515 }
2516 ofpbuf_uninit(&b);
2517
2518 if (file != stdin) {
2519 fclose(file);
2520 }
2521}
2522
f3dd1419
BP
2523static bool
2524is_openflow_port(ovs_be16 port_, char *ports[])
2525{
2526 uint16_t port = ntohs(port_);
2527 if (ports[0]) {
2528 int i;
2529
2530 for (i = 0; ports[i]; i++) {
2531 if (port == atoi(ports[i])) {
2532 return true;
2533 }
2534 }
2535 return false;
2536 } else {
2537 return port == OFP_PORT || port == OFP_OLD_PORT;
2538 }
2539}
2540
2541static void
1636c761 2542ofctl_ofp_parse_pcap(struct ovs_cmdl_context *ctx)
f3dd1419
BP
2543{
2544 struct tcp_reader *reader;
2545 FILE *file;
2546 int error;
2547 bool first;
2548
1636c761 2549 file = ovs_pcap_open(ctx->argv[1], "rb");
f3dd1419 2550 if (!file) {
1636c761 2551 ovs_fatal(errno, "%s: open failed", ctx->argv[1]);
f3dd1419
BP
2552 }
2553
2554 reader = tcp_reader_open();
2555 first = true;
2556 for (;;) {
cf62fa4c 2557 struct dp_packet *packet;
f3dd1419
BP
2558 long long int when;
2559 struct flow flow;
2560
50aa0364 2561 error = ovs_pcap_read(file, &packet, &when);
f3dd1419
BP
2562 if (error) {
2563 break;
2564 }
35303d71 2565 pkt_metadata_init(&packet->md, ODPP_NONE);
cf62fa4c 2566 flow_extract(packet, &flow);
f3dd1419
BP
2567 if (flow.dl_type == htons(ETH_TYPE_IP)
2568 && flow.nw_proto == IPPROTO_TCP
1636c761
RB
2569 && (is_openflow_port(flow.tp_src, ctx->argv + 2) ||
2570 is_openflow_port(flow.tp_dst, ctx->argv + 2))) {
cf62fa4c 2571 struct dp_packet *payload = tcp_reader_run(reader, &flow, packet);
f3dd1419 2572 if (payload) {
cf62fa4c 2573 while (dp_packet_size(payload) >= sizeof(struct ofp_header)) {
f3dd1419 2574 const struct ofp_header *oh;
cf62fa4c 2575 void *data = dp_packet_data(payload);
f3dd1419
BP
2576 int length;
2577
2578 /* Align OpenFlow on 8-byte boundary for safe access. */
cf62fa4c 2579 dp_packet_shift(payload, -((intptr_t) data & 7));
f3dd1419 2580
cf62fa4c 2581 oh = dp_packet_data(payload);
f3dd1419 2582 length = ntohs(oh->length);
cf62fa4c 2583 if (dp_packet_size(payload) < length) {
f3dd1419
BP
2584 break;
2585 }
2586
2587 if (!first) {
2588 putchar('\n');
2589 }
2590 first = false;
2591
2592 if (timestamp) {
2593 char *s = xastrftime_msec("%H:%M:%S.### ", when, true);
2594 fputs(s, stdout);
2595 free(s);
2596 }
2597
2598 printf(IP_FMT".%"PRIu16" > "IP_FMT".%"PRIu16":\n",
2599 IP_ARGS(flow.nw_src), ntohs(flow.tp_src),
2600 IP_ARGS(flow.nw_dst), ntohs(flow.tp_dst));
50f96b10
BP
2601 ofp_print(stdout, dp_packet_data(payload), length,
2602 NULL, verbosity + 1);
cf62fa4c 2603 dp_packet_pull(payload, length);
f3dd1419
BP
2604 }
2605 }
2606 }
cf62fa4c 2607 dp_packet_delete(packet);
f3dd1419
BP
2608 }
2609 tcp_reader_close(reader);
63ae068e 2610 fclose(file);
f3dd1419
BP
2611}
2612
064af421 2613static void
1636c761 2614ofctl_ping(struct ovs_cmdl_context *ctx)
064af421
BP
2615{
2616 size_t max_payload = 65535 - sizeof(struct ofp_header);
2617 unsigned int payload;
2618 struct vconn *vconn;
2619 int i;
2620
1636c761 2621 payload = ctx->argc > 2 ? atoi(ctx->argv[2]) : 64;
064af421 2622 if (payload > max_payload) {
34582733 2623 ovs_fatal(0, "payload must be between 0 and %"PRIuSIZE" bytes", max_payload);
064af421
BP
2624 }
2625
1636c761 2626 open_vconn(ctx->argv[1], &vconn);
064af421
BP
2627 for (i = 0; i < 10; i++) {
2628 struct timeval start, end;
2629 struct ofpbuf *request, *reply;
982697a4
BP
2630 const struct ofp_header *rpy_hdr;
2631 enum ofptype type;
064af421 2632
a53a8efa
SH
2633 request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
2634 vconn_get_version(vconn), payload);
982697a4 2635 random_bytes(ofpbuf_put_uninit(request, payload), payload);
064af421 2636
279c9e03 2637 xgettimeofday(&start);
064af421 2638 run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
279c9e03 2639 xgettimeofday(&end);
064af421 2640
6fd6ed71 2641 rpy_hdr = reply->data;
982697a4
BP
2642 if (ofptype_pull(&type, reply)
2643 || type != OFPTYPE_ECHO_REPLY
6fd6ed71
PS
2644 || reply->size != payload
2645 || memcmp(request->msg, reply->msg, payload)) {
064af421 2646 printf("Reply does not match request. Request:\n");
50f96b10 2647 ofp_print(stdout, request, request->size, NULL, verbosity + 2);
064af421 2648 printf("Reply:\n");
50f96b10 2649 ofp_print(stdout, reply, reply->size, NULL, verbosity + 2);
064af421 2650 }
437d0d22 2651 printf("%"PRIu32" bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1636c761 2652 reply->size, ctx->argv[1], ntohl(rpy_hdr->xid),
064af421
BP
2653 (1000*(double)(end.tv_sec - start.tv_sec))
2654 + (.001*(end.tv_usec - start.tv_usec)));
2655 ofpbuf_delete(request);
2656 ofpbuf_delete(reply);
2657 }
2658 vconn_close(vconn);
2659}
2660
2661static void
1636c761 2662ofctl_benchmark(struct ovs_cmdl_context *ctx)
064af421
BP
2663{
2664 size_t max_payload = 65535 - sizeof(struct ofp_header);
2665 struct timeval start, end;
2666 unsigned int payload_size, message_size;
2667 struct vconn *vconn;
2668 double duration;
2669 int count;
2670 int i;
2671
1636c761 2672 payload_size = atoi(ctx->argv[2]);
064af421 2673 if (payload_size > max_payload) {
34582733 2674 ovs_fatal(0, "payload must be between 0 and %"PRIuSIZE" bytes", max_payload);
064af421
BP
2675 }
2676 message_size = sizeof(struct ofp_header) + payload_size;
2677
1636c761 2678 count = atoi(ctx->argv[3]);
064af421
BP
2679
2680 printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
2681 count, message_size, count * message_size);
2682
1636c761 2683 open_vconn(ctx->argv[1], &vconn);
279c9e03 2684 xgettimeofday(&start);
064af421
BP
2685 for (i = 0; i < count; i++) {
2686 struct ofpbuf *request, *reply;
064af421 2687
a53a8efa
SH
2688 request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
2689 vconn_get_version(vconn), payload_size);
982697a4 2690 ofpbuf_put_zeros(request, payload_size);
064af421
BP
2691 run(vconn_transact(vconn, request, &reply), "transact");
2692 ofpbuf_delete(reply);
2693 }
279c9e03 2694 xgettimeofday(&end);
064af421
BP
2695 vconn_close(vconn);
2696
2697 duration = ((1000*(double)(end.tv_sec - start.tv_sec))
2698 + (.001*(end.tv_usec - start.tv_usec)));
2699 printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
2700 duration, count / (duration / 1000.0),
2701 count * message_size / (duration / 1000.0));
2702}
2703
fb8f22c1
BY
2704static void
2705ofctl_dump_ipfix_bridge(struct ovs_cmdl_context *ctx)
2706{
2707 dump_trivial_transaction(ctx->argv[1], OFPRAW_NXST_IPFIX_BRIDGE_REQUEST);
2708}
2709
2a7c4805
JP
2710static void
2711ofctl_ct_flush_zone(struct ovs_cmdl_context *ctx)
2712{
2713 uint16_t zone_id;
2714 char *error = str_to_u16(ctx->argv[2], "zone_id", &zone_id);
2715 if (error) {
2716 ovs_fatal(0, "%s", error);
2717 }
2718
2719 struct vconn *vconn;
2720 open_vconn(ctx->argv[1], &vconn);
2721 enum ofp_version version = vconn_get_version(vconn);
2722
2723 struct ofpbuf *msg = ofpraw_alloc(OFPRAW_NXT_CT_FLUSH_ZONE, version, 0);
2724 struct nx_zone_id *nzi = ofpbuf_put_zeros(msg, sizeof *nzi);
2725 nzi->zone_id = htons(zone_id);
2726
2727 transact_noreply(vconn, msg);
2728 vconn_close(vconn);
2729}
2730
fb8f22c1
BY
2731static void
2732ofctl_dump_ipfix_flow(struct ovs_cmdl_context *ctx)
2733{
2734 dump_trivial_transaction(ctx->argv[1], OFPRAW_NXST_IPFIX_FLOW_REQUEST);
2735}
2736
25070e04
JR
2737static void
2738bundle_group_mod__(const char *remote, struct ofputil_group_mod *gms,
2739 size_t n_gms, enum ofputil_protocol usable_protocols)
2740{
2741 enum ofputil_protocol protocol;
2742 enum ofp_version version;
2743 struct vconn *vconn;
2744 struct ovs_list requests;
2745 size_t i;
2746
2747 ovs_list_init(&requests);
2748
2749 /* Bundles need OpenFlow 1.3+. */
2750 usable_protocols &= OFPUTIL_P_OF13_UP;
2751 protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
2752 version = ofputil_protocol_to_ofp_version(protocol);
2753
2754 for (i = 0; i < n_gms; i++) {
2755 struct ofputil_group_mod *gm = &gms[i];
2756 struct ofpbuf *request = ofputil_encode_group_mod(version, gm);
2757
2758 ovs_list_push_back(&requests, &request->list_node);
2759 ofputil_uninit_group_mod(gm);
2760 }
2761
2762 bundle_transact(vconn, &requests, OFPBF_ORDERED | OFPBF_ATOMIC);
2763 ofpbuf_list_delete(&requests);
2764 vconn_close(vconn);
2765}
2766
7395c052
NZ
2767static void
2768ofctl_group_mod__(const char *remote, struct ofputil_group_mod *gms,
69185eb2 2769 size_t n_gms, enum ofputil_protocol usable_protocols)
7395c052 2770{
69185eb2 2771 enum ofputil_protocol protocol;
7395c052 2772 struct ofputil_group_mod *gm;
69185eb2 2773 enum ofp_version version;
7395c052
NZ
2774 struct ofpbuf *request;
2775
2776 struct vconn *vconn;
2777 size_t i;
2778
25070e04
JR
2779 if (bundle) {
2780 bundle_group_mod__(remote, gms, n_gms, usable_protocols);
2781 return;
2782 }
2783
69185eb2
SH
2784 protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
2785 version = ofputil_protocol_to_ofp_version(protocol);
7395c052
NZ
2786
2787 for (i = 0; i < n_gms; i++) {
2788 gm = &gms[i];
69185eb2 2789 request = ofputil_encode_group_mod(version, gm);
25070e04 2790 transact_noreply(vconn, request);
75868d0e 2791 ofputil_uninit_group_mod(gm);
7395c052
NZ
2792 }
2793
2794 vconn_close(vconn);
7395c052
NZ
2795}
2796
7395c052 2797static void
25070e04 2798ofctl_group_mod_file(int argc OVS_UNUSED, char *argv[], int command)
7395c052
NZ
2799{
2800 struct ofputil_group_mod *gms = NULL;
2801 enum ofputil_protocol usable_protocols;
2802 size_t n_gms = 0;
2803 char *error;
2804
25070e04
JR
2805 if (command == OFPGC11_ADD) {
2806 /* Allow the file to specify a mix of commands. If none specified at
2807 * the beginning of any given line, then the default is OFPGC11_ADD, so
2808 * this is backwards compatible. */
2809 command = -2;
2810 }
50f96b10
BP
2811 error = parse_ofp_group_mod_file(argv[2], ports_to_accept(argv[1]),
2812 command, &gms, &n_gms, &usable_protocols);
7395c052
NZ
2813 if (error) {
2814 ovs_fatal(0, "%s", error);
2815 }
69185eb2 2816 ofctl_group_mod__(argv[1], gms, n_gms, usable_protocols);
7395c052
NZ
2817 free(gms);
2818}
2819
2820static void
2821ofctl_group_mod(int argc, char *argv[], uint16_t command)
2822{
2823 if (argc > 2 && !strcmp(argv[2], "-")) {
2824 ofctl_group_mod_file(argc, argv, command);
2825 } else {
2826 enum ofputil_protocol usable_protocols;
2827 struct ofputil_group_mod gm;
2828 char *error;
2829
2830 error = parse_ofp_group_mod_str(&gm, command, argc > 2 ? argv[2] : "",
50f96b10 2831 ports_to_accept(argv[1]),
7395c052
NZ
2832 &usable_protocols);
2833 if (error) {
2834 ovs_fatal(0, "%s", error);
2835 }
69185eb2 2836 ofctl_group_mod__(argv[1], &gm, 1, usable_protocols);
7395c052
NZ
2837 }
2838}
2839
2840static void
1636c761 2841ofctl_add_group(struct ovs_cmdl_context *ctx)
7395c052 2842{
1636c761 2843 ofctl_group_mod(ctx->argc, ctx->argv, OFPGC11_ADD);
7395c052
NZ
2844}
2845
2846static void
1636c761 2847ofctl_add_groups(struct ovs_cmdl_context *ctx)
7395c052 2848{
1636c761 2849 ofctl_group_mod_file(ctx->argc, ctx->argv, OFPGC11_ADD);
7395c052
NZ
2850}
2851
2852static void
1636c761 2853ofctl_mod_group(struct ovs_cmdl_context *ctx)
7395c052 2854{
88b87a36
JS
2855 ofctl_group_mod(ctx->argc, ctx->argv,
2856 may_create ? OFPGC11_ADD_OR_MOD : OFPGC11_MODIFY);
7395c052
NZ
2857}
2858
2859static void
1636c761 2860ofctl_del_groups(struct ovs_cmdl_context *ctx)
7395c052 2861{
1636c761 2862 ofctl_group_mod(ctx->argc, ctx->argv, OFPGC11_DELETE);
7395c052
NZ
2863}
2864
bdbb8426 2865static void
1636c761 2866ofctl_insert_bucket(struct ovs_cmdl_context *ctx)
bdbb8426 2867{
1636c761 2868 ofctl_group_mod(ctx->argc, ctx->argv, OFPGC15_INSERT_BUCKET);
bdbb8426
SH
2869}
2870
2871static void
1636c761 2872ofctl_remove_bucket(struct ovs_cmdl_context *ctx)
bdbb8426 2873{
1636c761 2874 ofctl_group_mod(ctx->argc, ctx->argv, OFPGC15_REMOVE_BUCKET);
bdbb8426
SH
2875}
2876
7395c052 2877static void
1636c761 2878ofctl_dump_group_stats(struct ovs_cmdl_context *ctx)
7395c052
NZ
2879{
2880 enum ofputil_protocol usable_protocols;
2881 struct ofputil_group_mod gm;
2882 struct ofpbuf *request;
2883 struct vconn *vconn;
2884 uint32_t group_id;
2885 char *error;
2886
2887 memset(&gm, 0, sizeof gm);
2888
2889 error = parse_ofp_group_mod_str(&gm, OFPGC11_DELETE,
1636c761 2890 ctx->argc > 2 ? ctx->argv[2] : "",
50f96b10 2891 ports_to_accept(ctx->argv[1]),
7395c052
NZ
2892 &usable_protocols);
2893 if (error) {
2894 ovs_fatal(0, "%s", error);
2895 }
2896
2897 group_id = gm.group_id;
2898
1636c761 2899 open_vconn(ctx->argv[1], &vconn);
7395c052
NZ
2900 request = ofputil_encode_group_stats_request(vconn_get_version(vconn),
2901 group_id);
2902 if (request) {
182b2eef 2903 dump_transaction(vconn, request);
7395c052
NZ
2904 }
2905
2906 vconn_close(vconn);
2907}
2908
2909static void
1636c761 2910ofctl_dump_group_desc(struct ovs_cmdl_context *ctx)
7395c052
NZ
2911{
2912 struct ofpbuf *request;
2913 struct vconn *vconn;
19187a71 2914 uint32_t group_id;
7395c052 2915
1636c761 2916 open_vconn(ctx->argv[1], &vconn);
7395c052 2917
1636c761 2918 if (ctx->argc < 3 || !ofputil_group_from_string(ctx->argv[2], &group_id)) {
30ef36c6 2919 group_id = OFPG_ALL;
19187a71
BP
2920 }
2921
2922 request = ofputil_encode_group_desc_request(vconn_get_version(vconn),
2923 group_id);
7395c052 2924 if (request) {
182b2eef 2925 dump_transaction(vconn, request);
7395c052
NZ
2926 }
2927
2928 vconn_close(vconn);
2929}
2930
2931static void
1636c761 2932ofctl_dump_group_features(struct ovs_cmdl_context *ctx)
7395c052
NZ
2933{
2934 struct ofpbuf *request;
2935 struct vconn *vconn;
2936
1636c761 2937 open_vconn(ctx->argv[1], &vconn);
7395c052
NZ
2938 request = ofputil_encode_group_features_request(vconn_get_version(vconn));
2939 if (request) {
182b2eef 2940 dump_transaction(vconn, request);
7395c052
NZ
2941 }
2942
2943 vconn_close(vconn);
2944}
2945
25070e04
JR
2946static void
2947ofctl_bundle(struct ovs_cmdl_context *ctx)
2948{
2949 enum ofputil_protocol protocol, usable_protocols;
2950 struct ofputil_bundle_msg *bms;
2951 struct ovs_list requests;
2952 struct vconn *vconn;
2953 size_t n_bms;
2954 char *error;
2955
50f96b10
BP
2956 error = parse_ofp_bundle_file(ctx->argv[2], ports_to_accept(ctx->argv[1]),
2957 &bms, &n_bms, &usable_protocols);
25070e04
JR
2958 if (error) {
2959 ovs_fatal(0, "%s", error);
2960 }
2961
2962 /* Implicit OpenFlow 1.4. */
2963 if (!(get_allowed_ofp_versions() &
2964 ofputil_protocols_to_version_bitmap(OFPUTIL_P_OF13_UP))) {
2965
2966 /* Add implicit allowance for OpenFlow 1.4. */
2967 add_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
2968 OFPUTIL_P_OF14_OXM));
2969 /* Remove all versions that do not support bundles. */
2970 mask_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
2971 OFPUTIL_P_OF13_UP));
2972 allowed_protocols = ofputil_protocols_from_version_bitmap(
2973 get_allowed_ofp_versions());
2974 }
2975
2976 /* Bundles need OpenFlow 1.3+. */
2977 usable_protocols &= OFPUTIL_P_OF13_UP;
2978 protocol = open_vconn_for_flow_mod(ctx->argv[1], &vconn, usable_protocols);
2979
2980 ovs_list_init(&requests);
2981 ofputil_encode_bundle_msgs(bms, n_bms, &requests, protocol);
6dd3c787 2982 ofputil_free_bundle_msgs(bms, n_bms);
25070e04
JR
2983 bundle_transact(vconn, &requests, OFPBF_ORDERED | OFPBF_ATOMIC);
2984 ofpbuf_list_delete(&requests);
2985
2986 vconn_close(vconn);
2987}
2988
6159c531 2989static void
4e548ad9 2990ofctl_tlv_mod(struct ovs_cmdl_context *ctx, uint16_t command)
6159c531
JG
2991{
2992 enum ofputil_protocol usable_protocols;
2993 enum ofputil_protocol protocol;
4e548ad9 2994 struct ofputil_tlv_table_mod ttm;
6159c531
JG
2995 char *error;
2996 enum ofp_version version;
2997 struct ofpbuf *request;
2998 struct vconn *vconn;
2999
4e548ad9 3000 error = parse_ofp_tlv_table_mod_str(&ttm, command, ctx->argc > 2 ?
6159c531
JG
3001 ctx->argv[2] : "",
3002 &usable_protocols);
3003 if (error) {
3004 ovs_fatal(0, "%s", error);
3005 }
3006
3007 protocol = open_vconn_for_flow_mod(ctx->argv[1], &vconn, usable_protocols);
3008 version = ofputil_protocol_to_ofp_version(protocol);
3009
4e548ad9 3010 request = ofputil_encode_tlv_table_mod(version, &ttm);
6159c531
JG
3011 if (request) {
3012 transact_noreply(vconn, request);
3013 }
3014
3015 vconn_close(vconn);
4e548ad9 3016 ofputil_uninit_tlv_table(&ttm.mappings);
6159c531
JG
3017}
3018
3019static void
4e548ad9 3020ofctl_add_tlv_map(struct ovs_cmdl_context *ctx)
6159c531 3021{
4e548ad9 3022 ofctl_tlv_mod(ctx, NXTTMC_ADD);
6159c531
JG
3023}
3024
3025static void
4e548ad9 3026ofctl_del_tlv_map(struct ovs_cmdl_context *ctx)
6159c531 3027{
4e548ad9 3028 ofctl_tlv_mod(ctx, ctx->argc > 2 ? NXTTMC_DELETE : NXTTMC_CLEAR);
6159c531
JG
3029}
3030
3031static void
4e548ad9 3032ofctl_dump_tlv_map(struct ovs_cmdl_context *ctx)
6159c531 3033{
4e548ad9 3034 dump_trivial_transaction(ctx->argv[1], OFPRAW_NXT_TLV_TABLE_REQUEST);
6159c531
JG
3035}
3036
09246b99 3037static void
1636c761 3038ofctl_help(struct ovs_cmdl_context *ctx OVS_UNUSED)
09246b99
BP
3039{
3040 usage();
3041}
451de37e
AW
3042
3043static void
1636c761 3044ofctl_list_commands(struct ovs_cmdl_context *ctx OVS_UNUSED)
451de37e 3045{
5f383751 3046 ovs_cmdl_print_commands(get_all_commands());
451de37e 3047}
09246b99 3048\f
0199c526
BP
3049/* replace-flows and diff-flows commands. */
3050
00da1ac5
JR
3051struct flow_tables {
3052 struct classifier tables[OFPTT_MAX + 1];
3053};
3054
3055#define FOR_EACH_TABLE(CLS, TABLES) \
3056 for ((CLS) = (TABLES)->tables; \
3057 (CLS) < &(TABLES)->tables[ARRAY_SIZE((TABLES)->tables)]; \
3058 (CLS)++)
3059
3060static void
3061flow_tables_init(struct flow_tables *tables)
3062{
3063 struct classifier *cls;
3064
3065 FOR_EACH_TABLE (cls, tables) {
3066 classifier_init(cls, NULL);
3067 }
3068}
3069
3070static void
3071flow_tables_defer(struct flow_tables *tables)
3072{
3073 struct classifier *cls;
3074
3075 FOR_EACH_TABLE (cls, tables) {
3076 classifier_defer(cls);
3077 }
3078}
3079
3080static void
3081flow_tables_publish(struct flow_tables *tables)
3082{
3083 struct classifier *cls;
3084
3085 FOR_EACH_TABLE (cls, tables) {
3086 classifier_publish(cls);
3087 }
3088}
3089
0199c526
BP
3090/* A flow table entry, possibly with two different versions. */
3091struct fte {
3092 struct cls_rule rule; /* Within a "struct classifier". */
3093 struct fte_version *versions[2];
3094};
3095
3096/* One version of a Flow Table Entry. */
3097struct fte_version {
3098 ovs_be64 cookie;
3099 uint16_t idle_timeout;
3100 uint16_t hard_timeout;
ca26eb44 3101 uint16_t importance;
0199c526 3102 uint16_t flags;
f25d0cf3
BP
3103 struct ofpact *ofpacts;
3104 size_t ofpacts_len;
00da1ac5 3105 uint8_t table_id;
0199c526
BP
3106};
3107
8d8ab6c2
JG
3108/* A FTE entry that has been queued for later insertion after all
3109 * flows have been scanned to correctly allocation tunnel metadata. */
3110struct fte_pending {
3111 struct match *match;
3112 int priority;
3113 struct fte_version *version;
3114 int index;
3115
3116 struct ovs_list list_node;
3117};
3118
3119/* Processing state during two stage processing of flow table entries.
3120 * Tracks the maximum size seen for each tunnel metadata entry as well
3121 * as a list of the pending FTE entries. */
3122struct fte_state {
3123 int tun_metadata_size[TUN_METADATA_NUM_OPTS];
3124 struct ovs_list fte_pending_list;
3125
3126 /* The final metadata table that we have constructed. */
3127 struct tun_table *tun_tab;
50f96b10
BP
3128
3129 /* Port map. There is only one port map, not one per source, because it
3130 * only makes sense to display a single name for a given port number. */
3131 const struct ofputil_port_map *port_map;
8d8ab6c2
JG
3132};
3133
0199c526
BP
3134/* Frees 'version' and the data that it owns. */
3135static void
3136fte_version_free(struct fte_version *version)
3137{
3138 if (version) {
dc723c44 3139 free(CONST_CAST(struct ofpact *, version->ofpacts));
0199c526
BP
3140 free(version);
3141 }
3142}
3143
3144/* Returns true if 'a' and 'b' are the same, false if they differ.
3145 *
3146 * Ignores differences in 'flags' because there's no way to retrieve flags from
3147 * an OpenFlow switch. We have to assume that they are the same. */
3148static bool
3149fte_version_equals(const struct fte_version *a, const struct fte_version *b)
3150{
3151 return (a->cookie == b->cookie
3152 && a->idle_timeout == b->idle_timeout
3153 && a->hard_timeout == b->hard_timeout
ca26eb44 3154 && a->importance == b->importance
00da1ac5 3155 && a->table_id == b->table_id
6cc9d77c
BP
3156 && ofpacts_equal_stringwise(a->ofpacts, a->ofpacts_len,
3157 b->ofpacts, b->ofpacts_len));
0199c526
BP
3158}
3159
98f7f427
BP
3160/* Clears 's', then if 's' has a version 'index', formats 'fte' and version
3161 * 'index' into 's', followed by a new-line. */
0199c526 3162static void
8d8ab6c2
JG
3163fte_version_format(const struct fte_state *fte_state, const struct fte *fte,
3164 int index, struct ds *s)
0199c526 3165{
98f7f427 3166 const struct fte_version *version = fte->versions[index];
0199c526 3167
98f7f427
BP
3168 ds_clear(s);
3169 if (!version) {
3170 return;
3171 }
3172
00da1ac5
JR
3173 if (version->table_id) {
3174 ds_put_format(s, "table=%"PRIu8" ", version->table_id);
3175 }
50f96b10 3176 cls_rule_format(&fte->rule, fte_state->tun_tab, fte_state->port_map, s);
0199c526 3177 if (version->cookie != htonll(0)) {
98f7f427 3178 ds_put_format(s, " cookie=0x%"PRIx64, ntohll(version->cookie));
0199c526
BP
3179 }
3180 if (version->idle_timeout != OFP_FLOW_PERMANENT) {
98f7f427 3181 ds_put_format(s, " idle_timeout=%"PRIu16, version->idle_timeout);
0199c526
BP
3182 }
3183 if (version->hard_timeout != OFP_FLOW_PERMANENT) {
98f7f427 3184 ds_put_format(s, " hard_timeout=%"PRIu16, version->hard_timeout);
0199c526 3185 }
ca26eb44
RB
3186 if (version->importance != 0) {
3187 ds_put_format(s, " importance=%"PRIu16, version->importance);
3188 }
0199c526 3189
455ecd77 3190 ds_put_cstr(s, " actions=");
efefbcae
BP
3191 struct ofpact_format_params fp = {
3192 .port_map = fte_state->port_map,
3193 .s = s,
3194 };
3195 ofpacts_format(version->ofpacts, version->ofpacts_len, &fp);
98f7f427
BP
3196
3197 ds_put_char(s, '\n');
0199c526
BP
3198}
3199
3200static struct fte *
3201fte_from_cls_rule(const struct cls_rule *cls_rule)
3202{
3203 return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
3204}
3205
3206/* Frees 'fte' and its versions. */
3207static void
3208fte_free(struct fte *fte)
3209{
3210 if (fte) {
3211 fte_version_free(fte->versions[0]);
3212 fte_version_free(fte->versions[1]);
48d28ac1 3213 cls_rule_destroy(&fte->rule);
0199c526
BP
3214 free(fte);
3215 }
3216}
3217
00da1ac5 3218/* Frees all of the FTEs within 'tables'. */
0199c526 3219static void
00da1ac5 3220fte_free_all(struct flow_tables *tables)
0199c526 3221{
00da1ac5
JR
3222 struct classifier *cls;
3223
3224 FOR_EACH_TABLE (cls, tables) {
3225 struct fte *fte;
0199c526 3226
00da1ac5
JR
3227 classifier_defer(cls);
3228 CLS_FOR_EACH (fte, rule, cls) {
46ab60bf 3229 classifier_remove_assert(cls, &fte->rule);
00da1ac5
JR
3230 ovsrcu_postpone(fte_free, fte);
3231 }
3232 classifier_destroy(cls);
0199c526
BP
3233 }
3234}
3235
00da1ac5 3236/* Searches 'tables' for an FTE matching 'rule', inserting a new one if
0199c526
BP
3237 * necessary. Sets 'version' as the version of that rule with the given
3238 * 'index', replacing any existing version, if any.
3239 *
3240 * Takes ownership of 'version'. */
3241static void
00da1ac5 3242fte_insert(struct flow_tables *tables, const struct match *match,
eb391b76 3243 int priority, struct fte_version *version, int index)
0199c526 3244{
00da1ac5 3245 struct classifier *cls = &tables->tables[version->table_id];
0199c526
BP
3246 struct fte *old, *fte;
3247
3248 fte = xzalloc(sizeof *fte);
bd53aa17 3249 cls_rule_init(&fte->rule, match, priority);
0199c526
BP
3250 fte->versions[index] = version;
3251
bd53aa17 3252 old = fte_from_cls_rule(classifier_replace(cls, &fte->rule,
44e0c35d 3253 OVS_VERSION_MIN, NULL, 0));
0199c526 3254 if (old) {
0199c526 3255 fte->versions[!index] = old->versions[!index];
de4ad4a2
JR
3256 old->versions[!index] = NULL;
3257
3258 ovsrcu_postpone(fte_free, old);
0199c526
BP
3259 }
3260}
3261
f6812140
JG
3262/* Given a list of the field sizes for each tunnel metadata entry, install
3263 * a mapping table for later operations. */
3264static void
3265generate_tun_metadata(struct fte_state *state)
3266{
3267 struct ofputil_tlv_table_mod ttm;
3268 int i;
3269
3270 ttm.command = NXTTMC_ADD;
3271 ovs_list_init(&ttm.mappings);
3272
3273 for (i = 0; i < TUN_METADATA_NUM_OPTS; i++) {
3274 if (state->tun_metadata_size[i] != -1) {
3275 struct ofputil_tlv_map *map = xmalloc(sizeof *map);
3276
3277 ovs_list_push_back(&ttm.mappings, &map->list_node);
3278
3279 /* We don't care about the actual option class and type since there
3280 * won't be any lookup. We just need to make them unique. */
3281 map->option_class = i / UINT8_MAX;
3282 map->option_type = i;
3283 map->option_len = ROUND_UP(state->tun_metadata_size[i], 4);
3284 map->index = i;
3285 }
3286 }
3287
8d8ab6c2 3288 tun_metadata_table_mod(&ttm, NULL, &state->tun_tab);
f6812140
JG
3289 ofputil_uninit_tlv_table(&ttm.mappings);
3290}
3291
3292/* Once we have created a tunnel mapping table with a consistent overall
3293 * allocation, we need to remap each flow to use this table from its own
3294 * allocation. Since the mapping table has already been installed, we
3295 * can just read the data from the match and rewrite it. On rewrite, it
3296 * will use the new table. */
3297static void
8d8ab6c2 3298remap_match(struct fte_state *state, struct match *match)
f6812140
JG
3299{
3300 int i;
3301
3302 if (!match->tun_md.valid) {
3303 return;
3304 }
3305
3306 struct tun_metadata flow = match->flow.tunnel.metadata;
3307 struct tun_metadata flow_mask = match->wc.masks.tunnel.metadata;
3308 memset(&match->flow.tunnel.metadata, 0, sizeof match->flow.tunnel.metadata);
3309 memset(&match->wc.masks.tunnel.metadata, 0,
3310 sizeof match->wc.masks.tunnel.metadata);
3311 match->tun_md.valid = false;
3312
8d8ab6c2
JG
3313 match->flow.tunnel.metadata.tab = state->tun_tab;
3314 match->wc.masks.tunnel.metadata.tab = match->flow.tunnel.metadata.tab;
3315
f6812140
JG
3316 ULLONG_FOR_EACH_1 (i, flow_mask.present.map) {
3317 const struct mf_field *field = mf_from_id(MFF_TUN_METADATA0 + i);
3318 int offset = match->tun_md.entry[i].loc.c.offset;
3319 int len = match->tun_md.entry[i].loc.len;
3320 union mf_value value, mask;
3321
3322 memset(&value, 0, field->n_bytes - len);
3323 memset(&mask, match->tun_md.entry[i].masked ? 0 : 0xff,
3324 field->n_bytes - len);
3325
3326 memcpy(value.tun_metadata + field->n_bytes - len,
3327 flow.opts.u8 + offset, len);
3328 memcpy(mask.tun_metadata + field->n_bytes - len,
3329 flow_mask.opts.u8 + offset, len);
3330 mf_set(field, &value, &mask, match, NULL);
3331 }
3332}
3333
3334/* In order to correctly handle tunnel metadata, we need to have
3335 * two passes over the flows. This happens because tunnel metadata
3336 * doesn't have fixed locations in a flow entry but is instead dynamically
3337 * allocated space. In the case of flows coming from a file, we don't
3338 * even know the size of each field when we need to do the allocation.
3339 * When the flows come in, each flow has an individual allocation based
3340 * on its own fields. However, this allocation is not the same across
3341 * different flows and therefore fields are not directly comparable.
3342 *
3343 * In the first pass, we record the maximum size of each tunnel metadata
3344 * field as well as queue FTE entries for later processing.
3345 *
3346 * In the second pass, we use the metadata size information to create a
3347 * tunnel mapping table and set that through the tunnel metadata processing
3348 * code. We then remap all individual flows to use this common allocation
3349 * scheme. Finally, we load the queued entries into the classifier for
3350 * comparison.
3351 *
3352 * fte_state_init() should be called before processing any flows. */
3353static void
3354fte_state_init(struct fte_state *state)
3355{
3356 int i;
3357
3358 for (i = 0; i < TUN_METADATA_NUM_OPTS; i++) {
3359 state->tun_metadata_size[i] = -1;
3360 }
3361
3362 ovs_list_init(&state->fte_pending_list);
8d8ab6c2 3363 state->tun_tab = NULL;
50f96b10 3364 state->port_map = NULL;
8d8ab6c2
JG
3365}
3366
3367static void
3368fte_state_destroy(struct fte_state *state)
3369{
3370 tun_metadata_free(state->tun_tab);
f6812140
JG
3371}
3372
3373/* The first pass of the processing described in the comment about
3374 * fte_state_init(). fte_queue() is the first pass to be called as each
3375 * flow is read from its source. */
3376static void
3377fte_queue(struct fte_state *state, const struct match *match,
3378 int priority, struct fte_version *version, int index)
3379{
3380 struct fte_pending *pending = xmalloc(sizeof *pending);
3381 int i;
3382
3383 pending->match = xmemdup(match, sizeof *match);
3384 pending->priority = priority;
3385 pending->version = version;
3386 pending->index = index;
3387 ovs_list_push_back(&state->fte_pending_list, &pending->list_node);
3388
3389 if (!match->tun_md.valid) {
3390 return;
3391 }
3392
3393 ULLONG_FOR_EACH_1 (i, match->wc.masks.tunnel.metadata.present.map) {
3394 if (match->tun_md.entry[i].loc.len > state->tun_metadata_size[i]) {
3395 state->tun_metadata_size[i] = match->tun_md.entry[i].loc.len;
3396 }
3397 }
3398}
3399
3400/* The second pass of the processing described in the comment about
3401 * fte_state_init(). This should be called once all flows (from both
3402 * sides of the comparison) have been added through fte_queue(). */
3403static void
3404fte_fill(struct fte_state *state, struct flow_tables *tables)
3405{
3406 struct fte_pending *pending;
3407
3408 generate_tun_metadata(state);
3409
3410 flow_tables_init(tables);
3411 flow_tables_defer(tables);
3412
3413 LIST_FOR_EACH_POP(pending, list_node, &state->fte_pending_list) {
8d8ab6c2 3414 remap_match(state, pending->match);
f6812140
JG
3415 fte_insert(tables, pending->match, pending->priority, pending->version,
3416 pending->index);
3417 free(pending->match);
3418 free(pending);
3419 }
3420
3421 flow_tables_publish(tables);
3422}
3423
00da1ac5
JR
3424/* Reads the flows in 'filename' as flow table entries in 'tables' for the
3425 * version with the specified 'index'. Returns the flow formats able to
3426 * represent the flows that were read. */
27527aa0 3427static enum ofputil_protocol
f6812140 3428read_flows_from_file(const char *filename, struct fte_state *state, int index)
0199c526 3429{
27527aa0 3430 enum ofputil_protocol usable_protocols;
bdda5aca 3431 int line_number;
0199c526
BP
3432 struct ds s;
3433 FILE *file;
3434
3435 file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
3436 if (file == NULL) {
3437 ovs_fatal(errno, "%s: open", filename);
3438 }
3439
3440 ds_init(&s);
27527aa0 3441 usable_protocols = OFPUTIL_P_ANY;
bdda5aca
BP
3442 line_number = 0;
3443 while (!ds_get_preprocessed_line(&s, file, &line_number)) {
0199c526 3444 struct fte_version *version;
a9a2da38 3445 struct ofputil_flow_mod fm;
bdda5aca 3446 char *error;
db0b6c29 3447 enum ofputil_protocol usable;
0199c526 3448
50f96b10
BP
3449 error = parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), state->port_map,
3450 &usable);
bdda5aca
BP
3451 if (error) {
3452 ovs_fatal(0, "%s:%d: %s", filename, line_number, error);
3453 }
db0b6c29 3454 usable_protocols &= usable;
0199c526
BP
3455
3456 version = xmalloc(sizeof *version);
623e1caf 3457 version->cookie = fm.new_cookie;
0199c526
BP
3458 version->idle_timeout = fm.idle_timeout;
3459 version->hard_timeout = fm.hard_timeout;
ca26eb44 3460 version->importance = fm.importance;
0fb88c18
BP
3461 version->flags = fm.flags & (OFPUTIL_FF_SEND_FLOW_REM
3462 | OFPUTIL_FF_EMERG);
f25d0cf3
BP
3463 version->ofpacts = fm.ofpacts;
3464 version->ofpacts_len = fm.ofpacts_len;
00da1ac5 3465 version->table_id = fm.table_id != OFPTT_ALL ? fm.table_id : 0;
0199c526 3466
f6812140 3467 fte_queue(state, &fm.match, fm.priority, version, index);
0199c526
BP
3468 }
3469 ds_destroy(&s);
3470
3471 if (file != stdin) {
3472 fclose(file);
3473 }
3474
27527aa0 3475 return usable_protocols;
0199c526
BP
3476}
3477
3478/* Reads the OpenFlow flow table from 'vconn', which has currently active flow
00da1ac5 3479 * format 'protocol', and adds them as flow table entries in 'tables' for the
0199c526
BP
3480 * version with the specified 'index'. */
3481static void
27527aa0
BP
3482read_flows_from_switch(struct vconn *vconn,
3483 enum ofputil_protocol protocol,
f6812140 3484 struct fte_state *state, int index)
0199c526 3485{
81d1ea94 3486 struct ofputil_flow_stats_request fsr;
0199c526
BP
3487
3488 fsr.aggregate = false;
81a76618 3489 match_init_catchall(&fsr.match);
7f05e7ab 3490 fsr.out_port = OFPP_ANY;
4b69263d 3491 fsr.out_group = OFPG_ANY;
0199c526 3492 fsr.table_id = 0xff;
ecc798ab 3493 fsr.cookie = fsr.cookie_mask = htonll(0);
0199c526 3494
d444a914
BP
3495 struct ofputil_flow_stats *fses;
3496 size_t n_fses;
3497 run(vconn_dump_flows(vconn, &fsr, protocol, &fses, &n_fses),
3498 "dump flows");
3499 for (size_t i = 0; i < n_fses; i++) {
3500 const struct ofputil_flow_stats *fs = &fses[i];
4ce9c315 3501 struct fte_version *version;
0199c526 3502
4ce9c315 3503 version = xmalloc(sizeof *version);
d444a914
BP
3504 version->cookie = fs->cookie;
3505 version->idle_timeout = fs->idle_timeout;
3506 version->hard_timeout = fs->hard_timeout;
3507 version->importance = fs->importance;
4ce9c315 3508 version->flags = 0;
d444a914
BP
3509 version->ofpacts_len = fs->ofpacts_len;
3510 version->ofpacts = xmemdup(fs->ofpacts, fs->ofpacts_len);
3511 version->table_id = fs->table_id;
4ce9c315 3512
d444a914 3513 fte_queue(state, &fs->match, fs->priority, version, index);
0199c526 3514 }
edb417cc
WT
3515
3516 for (size_t i = 0; i < n_fses; i++) {
3517 free(CONST_CAST(struct ofpact *, fses[i].ofpacts));
3518 }
3519 free(fses);
0199c526
BP
3520}
3521
3522static void
3523fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
ca6ba700 3524 enum ofputil_protocol protocol, struct ovs_list *packets)
0199c526
BP
3525{
3526 const struct fte_version *version = fte->versions[index];
0199c526
BP
3527 struct ofpbuf *ofm;
3528
39cc5c4a
BP
3529 struct ofputil_flow_mod fm = {
3530 .priority = fte->rule.priority,
3531 .new_cookie = version->cookie,
3532 .modify_cookie = true,
3533 .table_id = version->table_id,
3534 .command = command,
3535 .idle_timeout = version->idle_timeout,
3536 .hard_timeout = version->hard_timeout,
3537 .importance = version->importance,
3538 .buffer_id = UINT32_MAX,
3539 .out_port = OFPP_ANY,
3540 .out_group = OFPG_ANY,
3541 .flags = version->flags,
39cc5c4a 3542 };
5cb7a798 3543 minimatch_expand(&fte->rule.match, &fm.match);
0199c526
BP
3544 if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
3545 command == OFPFC_MODIFY_STRICT) {
f25d0cf3
BP
3546 fm.ofpacts = version->ofpacts;
3547 fm.ofpacts_len = version->ofpacts_len;
0199c526 3548 } else {
f25d0cf3
BP
3549 fm.ofpacts = NULL;
3550 fm.ofpacts_len = 0;
0199c526
BP
3551 }
3552
27527aa0 3553 ofm = ofputil_encode_flow_mod(&fm, protocol);
417e7e66 3554 ovs_list_push_back(packets, &ofm->list_node);
0199c526
BP
3555}
3556
3557static void
1636c761 3558ofctl_replace_flows(struct ovs_cmdl_context *ctx)
0199c526 3559{
50f96b10 3560 enum { FILE_IDX = 0, SWITCH_IDX = 1 };
27527aa0 3561 enum ofputil_protocol usable_protocols, protocol;
f6812140 3562 struct fte_state fte_state;
00da1ac5
JR
3563 struct flow_tables tables;
3564 struct classifier *cls;
ca6ba700 3565 struct ovs_list requests;
0199c526
BP
3566 struct vconn *vconn;
3567 struct fte *fte;
3568
f6812140 3569 fte_state_init(&fte_state);
50f96b10 3570 fte_state.port_map = ports_to_accept(ctx->argv[1]);
f6812140 3571 usable_protocols = read_flows_from_file(ctx->argv[2], &fte_state, FILE_IDX);
0199c526 3572
1636c761 3573 protocol = open_vconn(ctx->argv[1], &vconn);
27527aa0
BP
3574 protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
3575
f6812140
JG
3576 read_flows_from_switch(vconn, protocol, &fte_state, SWITCH_IDX);
3577
3578 fte_fill(&fte_state, &tables);
0199c526 3579
417e7e66 3580 ovs_list_init(&requests);
0199c526 3581
00da1ac5
JR
3582 FOR_EACH_TABLE (cls, &tables) {
3583 /* Delete flows that exist on the switch but not in the file. */
3584 CLS_FOR_EACH (fte, rule, cls) {
3585 struct fte_version *file_ver = fte->versions[FILE_IDX];
3586 struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
0199c526 3587
00da1ac5
JR
3588 if (sw_ver && !file_ver) {
3589 fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
3590 protocol, &requests);
3591 }
0199c526 3592 }
0199c526 3593
00da1ac5
JR
3594 /* Add flows that exist in the file but not on the switch.
3595 * Update flows that exist in both places but differ. */
3596 CLS_FOR_EACH (fte, rule, cls) {
3597 struct fte_version *file_ver = fte->versions[FILE_IDX];
3598 struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
0199c526 3599
00da1ac5
JR
3600 if (file_ver &&
3601 (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
3602 fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, protocol,
3603 &requests);
3604 }
0199c526
BP
3605 }
3606 }
db5076ee 3607 if (bundle) {
39c94593 3608 bundle_transact(vconn, &requests, OFPBF_ORDERED | OFPBF_ATOMIC);
db5076ee
JR
3609 } else {
3610 transact_multiple_noreply(vconn, &requests);
3611 }
74cb32e3
WT
3612
3613 ofpbuf_list_delete(&requests);
0199c526
BP
3614 vconn_close(vconn);
3615
00da1ac5 3616 fte_free_all(&tables);
8d8ab6c2 3617 fte_state_destroy(&fte_state);
0199c526
BP
3618}
3619
3620static void
f6812140 3621read_flows_from_source(const char *source, struct fte_state *state, int index)
0199c526
BP
3622{
3623 struct stat s;
3624
3625 if (source[0] == '/' || source[0] == '.'
3626 || (!strchr(source, ':') && !stat(source, &s))) {
f6812140 3627 read_flows_from_file(source, state, index);
0199c526 3628 } else {
27527aa0 3629 enum ofputil_protocol protocol;
0199c526
BP
3630 struct vconn *vconn;
3631
27527aa0
BP
3632 protocol = open_vconn(source, &vconn);
3633 protocol = set_protocol_for_flow_dump(vconn, protocol, OFPUTIL_P_ANY);
f6812140 3634 read_flows_from_switch(vconn, protocol, state, index);
0199c526 3635 vconn_close(vconn);
50f96b10
BP
3636
3637 if (!state->port_map) {
3638 state->port_map = ports_to_show(source);
3639 }
0199c526
BP
3640 }
3641}
3642
3643static void
1636c761 3644ofctl_diff_flows(struct ovs_cmdl_context *ctx)
0199c526
BP
3645{
3646 bool differences = false;
f6812140 3647 struct fte_state fte_state;
00da1ac5
JR
3648 struct flow_tables tables;
3649 struct classifier *cls;
98f7f427 3650 struct ds a_s, b_s;
0199c526
BP
3651 struct fte *fte;
3652
f6812140
JG
3653 fte_state_init(&fte_state);
3654 read_flows_from_source(ctx->argv[1], &fte_state, 0);
3655 read_flows_from_source(ctx->argv[2], &fte_state, 1);
3656 fte_fill(&fte_state, &tables);
0199c526 3657
98f7f427
BP
3658 ds_init(&a_s);
3659 ds_init(&b_s);
3660
00da1ac5
JR
3661 FOR_EACH_TABLE (cls, &tables) {
3662 CLS_FOR_EACH (fte, rule, cls) {
3663 struct fte_version *a = fte->versions[0];
3664 struct fte_version *b = fte->versions[1];
3665
3666 if (!a || !b || !fte_version_equals(a, b)) {
8d8ab6c2
JG
3667 fte_version_format(&fte_state, fte, 0, &a_s);
3668 fte_version_format(&fte_state, fte, 1, &b_s);
6cc9d77c
BP
3669 if (a_s.length) {
3670 printf("-%s", ds_cstr(&a_s));
3671 }
3672 if (b_s.length) {
3673 printf("+%s", ds_cstr(&b_s));
98f7f427 3674 }
6cc9d77c 3675 differences = true;
0199c526 3676 }
0199c526
BP
3677 }
3678 }
3679
98f7f427
BP
3680 ds_destroy(&a_s);
3681 ds_destroy(&b_s);
3682
00da1ac5 3683 fte_free_all(&tables);
8d8ab6c2 3684 fte_state_destroy(&fte_state);
0199c526
BP
3685
3686 if (differences) {
3687 exit(2);
3688 }
3689}
3200ed58
JR
3690
3691static void
3692ofctl_meter_mod__(const char *bridge, const char *str, int command)
3693{
3694 struct ofputil_meter_mod mm;
3695 struct vconn *vconn;
3696 enum ofputil_protocol protocol;
3697 enum ofputil_protocol usable_protocols;
3698 enum ofp_version version;
3699
3700 if (str) {
3701 char *error;
3702 error = parse_ofp_meter_mod_str(&mm, str, command, &usable_protocols);
3703 if (error) {
3704 ovs_fatal(0, "%s", error);
3705 }
3706 } else {
3707 usable_protocols = OFPUTIL_P_OF13_UP;
3708 mm.command = command;
3709 mm.meter.meter_id = OFPM13_ALL;
2f0b69ac 3710 mm.meter.bands = NULL;
3200ed58
JR
3711 }
3712
3713 protocol = open_vconn_for_flow_mod(bridge, &vconn, usable_protocols);
3714 version = ofputil_protocol_to_ofp_version(protocol);
3715 transact_noreply(vconn, ofputil_encode_meter_mod(version, &mm));
2f0b69ac 3716 free(mm.meter.bands);
3200ed58
JR
3717 vconn_close(vconn);
3718}
3719
3720static void
3721ofctl_meter_request__(const char *bridge, const char *str,
3722 enum ofputil_meter_request_type type)
3723{
3724 struct ofputil_meter_mod mm;
3725 struct vconn *vconn;
3726 enum ofputil_protocol usable_protocols;
3727 enum ofputil_protocol protocol;
3728 enum ofp_version version;
3729
3730 if (str) {
3731 char *error;
3732 error = parse_ofp_meter_mod_str(&mm, str, -1, &usable_protocols);
3733 if (error) {
3734 ovs_fatal(0, "%s", error);
3735 }
3736 } else {
3737 usable_protocols = OFPUTIL_P_OF13_UP;
3738 mm.meter.meter_id = OFPM13_ALL;
2f0b69ac 3739 mm.meter.bands = NULL;
3200ed58
JR
3740 }
3741
3742 protocol = open_vconn_for_flow_mod(bridge, &vconn, usable_protocols);
3743 version = ofputil_protocol_to_ofp_version(protocol);
182b2eef
BP
3744 dump_transaction(vconn, ofputil_encode_meter_request(version, type,
3745 mm.meter.meter_id));
2f0b69ac 3746 free(mm.meter.bands);
3200ed58
JR
3747 vconn_close(vconn);
3748}
3749
3750
3751static void
1636c761 3752ofctl_add_meter(struct ovs_cmdl_context *ctx)
3200ed58 3753{
1636c761 3754 ofctl_meter_mod__(ctx->argv[1], ctx->argv[2], OFPMC13_ADD);
3200ed58
JR
3755}
3756
3757static void
1636c761 3758ofctl_mod_meter(struct ovs_cmdl_context *ctx)
3200ed58 3759{
1636c761 3760 ofctl_meter_mod__(ctx->argv[1], ctx->argv[2], OFPMC13_MODIFY);
3200ed58
JR
3761}
3762
3763static void
1636c761 3764ofctl_del_meters(struct ovs_cmdl_context *ctx)
3200ed58 3765{
1636c761 3766 ofctl_meter_mod__(ctx->argv[1], ctx->argc > 2 ? ctx->argv[2] : NULL, OFPMC13_DELETE);
3200ed58
JR
3767}
3768
3769static void
1636c761 3770ofctl_dump_meters(struct ovs_cmdl_context *ctx)
3200ed58 3771{
1636c761 3772 ofctl_meter_request__(ctx->argv[1], ctx->argc > 2 ? ctx->argv[2] : NULL,
3200ed58
JR
3773 OFPUTIL_METER_CONFIG);
3774}
3775
3776static void
1636c761 3777ofctl_meter_stats(struct ovs_cmdl_context *ctx)
3200ed58 3778{
1636c761 3779 ofctl_meter_request__(ctx->argv[1], ctx->argc > 2 ? ctx->argv[2] : NULL,
3200ed58
JR
3780 OFPUTIL_METER_STATS);
3781}
3782
3783static void
1636c761 3784ofctl_meter_features(struct ovs_cmdl_context *ctx)
3200ed58 3785{
1636c761 3786 ofctl_meter_request__(ctx->argv[1], NULL, OFPUTIL_METER_FEATURES);
3200ed58
JR
3787}
3788
0199c526 3789\f
09246b99
BP
3790/* Undocumented commands for unit testing. */
3791
770f1f66 3792static void
db0b6c29
JR
3793ofctl_parse_flows__(struct ofputil_flow_mod *fms, size_t n_fms,
3794 enum ofputil_protocol usable_protocols)
770f1f66 3795{
27527aa0
BP
3796 enum ofputil_protocol protocol = 0;
3797 char *usable_s;
3798 size_t i;
770f1f66 3799
27527aa0
BP
3800 usable_s = ofputil_protocols_to_string(usable_protocols);
3801 printf("usable protocols: %s\n", usable_s);
3802 free(usable_s);
3803
3804 if (!(usable_protocols & allowed_protocols)) {
3805 ovs_fatal(0, "no usable protocol");
3806 }
3807 for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
3808 protocol = 1 << i;
3809 if (protocol & usable_protocols & allowed_protocols) {
3810 break;
3811 }
3812 }
cc2862a9 3813 ovs_assert(is_pow2(protocol));
27527aa0
BP
3814
3815 printf("chosen protocol: %s\n", ofputil_protocol_to_string(protocol));
3816
3817 for (i = 0; i < n_fms; i++) {
3818 struct ofputil_flow_mod *fm = &fms[i];
3819 struct ofpbuf *msg;
3820
3821 msg = ofputil_encode_flow_mod(fm, protocol);
50f96b10 3822 ofp_print(stdout, msg->data, msg->size, NULL, verbosity);
27527aa0
BP
3823 ofpbuf_delete(msg);
3824
dc723c44 3825 free(CONST_CAST(struct ofpact *, fm->ofpacts));
770f1f66
BP
3826 }
3827}
3828
3829/* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
3830 * it back to stdout. */
3831static void
1636c761 3832ofctl_parse_flow(struct ovs_cmdl_context *ctx)
770f1f66 3833{
db0b6c29 3834 enum ofputil_protocol usable_protocols;
27527aa0 3835 struct ofputil_flow_mod fm;
bdda5aca 3836 char *error;
770f1f66 3837
50f96b10
BP
3838 error = parse_ofp_flow_mod_str(&fm, ctx->argv[1], NULL,
3839 OFPFC_ADD, &usable_protocols);
bdda5aca
BP
3840 if (error) {
3841 ovs_fatal(0, "%s", error);
3842 }
db0b6c29 3843 ofctl_parse_flows__(&fm, 1, usable_protocols);
770f1f66
BP
3844}
3845
fec00620
BP
3846/* "parse-flows FILENAME": reads the named file as a sequence of flows (like
3847 * add-flows) and prints each of the flows back to stdout. */
0e581146 3848static void
1636c761 3849ofctl_parse_flows(struct ovs_cmdl_context *ctx)
0e581146 3850{
db0b6c29 3851 enum ofputil_protocol usable_protocols;
27527aa0
BP
3852 struct ofputil_flow_mod *fms = NULL;
3853 size_t n_fms = 0;
bdda5aca 3854 char *error;
0e581146 3855
50f96b10
BP
3856 error = parse_ofp_flow_mod_file(ctx->argv[1], NULL, OFPFC_ADD,
3857 &fms, &n_fms, &usable_protocols);
bdda5aca
BP
3858 if (error) {
3859 ovs_fatal(0, "%s", error);
3860 }
db0b6c29 3861 ofctl_parse_flows__(fms, n_fms, usable_protocols);
27527aa0 3862 free(fms);
0e581146
BP
3863}
3864
064af421 3865static void
9d84066c 3866ofctl_parse_nxm__(bool oxm, enum ofp_version version)
09246b99
BP
3867{
3868 struct ds in;
3869
3870 ds_init(&in);
06d7ae7d 3871 while (!ds_get_test_line(&in, stdin)) {
09246b99 3872 struct ofpbuf nx_match;
81a76618 3873 struct match match;
e729e793 3874 ovs_be64 cookie, cookie_mask;
90bf1e07 3875 enum ofperr error;
09246b99 3876 int match_len;
09246b99
BP
3877
3878 /* Convert string to nx_match. */
3879 ofpbuf_init(&nx_match, 0);
7623f4dd
SH
3880 if (oxm) {
3881 match_len = oxm_match_from_string(ds_cstr(&in), &nx_match);
3882 } else {
3883 match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
3884 }
09246b99 3885
81a76618 3886 /* Convert nx_match to match. */
102ce766 3887 if (strict) {
7623f4dd 3888 if (oxm) {
d7892c81 3889 error = oxm_pull_match(&nx_match, false, NULL, NULL, &match);
7623f4dd 3890 } else {
d7892c81
YHW
3891 error = nx_pull_match(&nx_match, match_len, &match, &cookie,
3892 &cookie_mask, false, NULL, NULL);
7623f4dd 3893 }
102ce766 3894 } else {
7623f4dd 3895 if (oxm) {
d7892c81 3896 error = oxm_pull_match_loose(&nx_match, false, NULL, &match);
7623f4dd 3897 } else {
81a76618 3898 error = nx_pull_match_loose(&nx_match, match_len, &match,
d7892c81
YHW
3899 &cookie, &cookie_mask, false,
3900 NULL);
7623f4dd 3901 }
102ce766
EJ
3902 }
3903
7623f4dd 3904
09246b99
BP
3905 if (!error) {
3906 char *out;
3907
81a76618 3908 /* Convert match back to nx_match. */
09246b99
BP
3909 ofpbuf_uninit(&nx_match);
3910 ofpbuf_init(&nx_match, 0);
7623f4dd 3911 if (oxm) {
9d84066c 3912 match_len = oxm_put_match(&nx_match, &match, version);
db5a1019 3913 out = oxm_match_to_string(&nx_match, match_len);
7623f4dd 3914 } else {
81a76618 3915 match_len = nx_put_match(&nx_match, &match,
7623f4dd 3916 cookie, cookie_mask);
6fd6ed71 3917 out = nx_match_to_string(nx_match.data, match_len);
7623f4dd 3918 }
09246b99 3919
09246b99
BP
3920 puts(out);
3921 free(out);
508a9338
BP
3922
3923 if (verbosity > 0) {
6fd6ed71 3924 ovs_hex_dump(stdout, nx_match.data, nx_match.size, 0, false);
508a9338 3925 }
09246b99 3926 } else {
90bf1e07
BP
3927 printf("nx_pull_match() returned error %s\n",
3928 ofperr_get_name(error));
09246b99
BP
3929 }
3930
3931 ofpbuf_uninit(&nx_match);
3932 }
3933 ds_destroy(&in);
064af421
BP
3934}
3935
b5ae8913
SH
3936/* "parse-nxm": reads a series of NXM nx_match specifications as strings from
3937 * stdin, does some internal fussing with them, and then prints them back as
3938 * strings on stdout. */
3939static void
1636c761 3940ofctl_parse_nxm(struct ovs_cmdl_context *ctx OVS_UNUSED)
b5ae8913 3941{
2f4aba0b 3942 ofctl_parse_nxm__(false, 0);
b5ae8913
SH
3943}
3944
9d84066c
BP
3945/* "parse-oxm VERSION": reads a series of OXM nx_match specifications as
3946 * strings from stdin, does some internal fussing with them, and then prints
3947 * them back as strings on stdout. VERSION must specify an OpenFlow version,
3948 * e.g. "OpenFlow12". */
b5ae8913 3949static void
1636c761 3950ofctl_parse_oxm(struct ovs_cmdl_context *ctx)
b5ae8913 3951{
1636c761 3952 enum ofp_version version = ofputil_version_from_string(ctx->argv[1]);
9d84066c 3953 if (version < OFP12_VERSION) {
1636c761 3954 ovs_fatal(0, "%s: not a valid version for OXM", ctx->argv[1]);
9d84066c
BP
3955 }
3956
2f4aba0b 3957 ofctl_parse_nxm__(true, version);
b5ae8913
SH
3958}
3959
f25d0cf3 3960static void
96628ae8
BP
3961print_differences(const char *prefix,
3962 const void *a_, size_t a_len,
f25d0cf3
BP
3963 const void *b_, size_t b_len)
3964{
3965 const uint8_t *a = a_;
3966 const uint8_t *b = b_;
3967 size_t i;
3968
3969 for (i = 0; i < MIN(a_len, b_len); i++) {
3970 if (a[i] != b[i]) {
34582733 3971 printf("%s%2"PRIuSIZE": %02"PRIx8" -> %02"PRIx8"\n",
96628ae8 3972 prefix, i, a[i], b[i]);
f25d0cf3
BP
3973 }
3974 }
3975 for (i = a_len; i < b_len; i++) {
34582733 3976 printf("%s%2"PRIuSIZE": (none) -> %02"PRIx8"\n", prefix, i, b[i]);
f25d0cf3
BP
3977 }
3978 for (i = b_len; i < a_len; i++) {
34582733 3979 printf("%s%2"PRIuSIZE": %02"PRIx8" -> (none)\n", prefix, i, a[i]);
f25d0cf3
BP
3980 }
3981}
3982
f25d0cf3 3983static void
65a8a59e 3984ofctl_parse_actions__(const char *version_s, bool instructions)
f25d0cf3 3985{
65a8a59e 3986 enum ofp_version version;
f25d0cf3
BP
3987 struct ds in;
3988
65a8a59e
BP
3989 version = ofputil_version_from_string(version_s);
3990 if (!version) {
3991 ovs_fatal(0, "%s: not a valid OpenFlow version", version_s);
3992 }
3993
f25d0cf3 3994 ds_init(&in);
bdda5aca 3995 while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
65a8a59e
BP
3996 struct ofpbuf of_out;
3997 struct ofpbuf of_in;
f25d0cf3 3998 struct ofpbuf ofpacts;
65a8a59e
BP
3999 const char *table_id;
4000 char *actions;
f25d0cf3
BP
4001 enum ofperr error;
4002 size_t size;
4003 struct ds s;
4004
65a8a59e
BP
4005 /* Parse table_id separated with the follow-up actions by ",", if
4006 * any. */
4007 actions = ds_cstr(&in);
4008 table_id = NULL;
4009 if (strstr(actions, ",")) {
4010 table_id = strsep(&actions, ",");
4011 }
4012
f25d0cf3 4013 /* Parse hex bytes. */
65a8a59e
BP
4014 ofpbuf_init(&of_in, 0);
4015 if (ofpbuf_put_hex(&of_in, actions, NULL)[0] != '\0') {
f25d0cf3
BP
4016 ovs_fatal(0, "Trailing garbage in hex data");
4017 }
4018
4019 /* Convert to ofpacts. */
4020 ofpbuf_init(&ofpacts, 0);
6fd6ed71 4021 size = of_in.size;
8f2cded4
BP
4022 error = (instructions
4023 ? ofpacts_pull_openflow_instructions
4024 : ofpacts_pull_openflow_actions)(
5c7c16d8 4025 &of_in, of_in.size, version, NULL, NULL, &ofpacts);
65a8a59e
BP
4026 if (!error && instructions) {
4027 /* Verify actions, enforce consistency. */
4028 enum ofputil_protocol protocol;
67210a55 4029 struct match match;
65a8a59e 4030
67210a55 4031 memset(&match, 0, sizeof match);
65a8a59e 4032 protocol = ofputil_protocols_from_ofp_version(version);
6fd6ed71 4033 error = ofpacts_check_consistency(ofpacts.data, ofpacts.size,
67210a55 4034 &match, OFPP_MAX,
65a8a59e 4035 table_id ? atoi(table_id) : 0,
00da1ac5 4036 OFPTT_MAX + 1, protocol);
65a8a59e 4037 }
f25d0cf3 4038 if (error) {
65a8a59e
BP
4039 printf("bad %s %s: %s\n\n",
4040 version_s, instructions ? "instructions" : "actions",
4041 ofperr_get_name(error));
f25d0cf3 4042 ofpbuf_uninit(&ofpacts);
65a8a59e 4043 ofpbuf_uninit(&of_in);
f25d0cf3
BP
4044 continue;
4045 }
65a8a59e 4046 ofpbuf_push_uninit(&of_in, size);
f25d0cf3
BP
4047
4048 /* Print cls_rule. */
4049 ds_init(&s);
455ecd77 4050 ds_put_cstr(&s, "actions=");
efefbcae
BP
4051 struct ofpact_format_params fp = { .s = &s };
4052 ofpacts_format(ofpacts.data, ofpacts.size, &fp);
f25d0cf3
BP
4053 puts(ds_cstr(&s));
4054 ds_destroy(&s);
4055
4056 /* Convert back to ofp10 actions and print differences from input. */
65a8a59e
BP
4057 ofpbuf_init(&of_out, 0);
4058 if (instructions) {
6fd6ed71
PS
4059 ofpacts_put_openflow_instructions(ofpacts.data, ofpacts.size,
4060 &of_out, version);
65a8a59e 4061 } else {
6fd6ed71 4062 ofpacts_put_openflow_actions(ofpacts.data, ofpacts.size,
65a8a59e
BP
4063 &of_out, version);
4064 }
f25d0cf3 4065
6fd6ed71
PS
4066 print_differences("", of_in.data, of_in.size,
4067 of_out.data, of_out.size);
f25d0cf3
BP
4068 putchar('\n');
4069
4070 ofpbuf_uninit(&ofpacts);
65a8a59e
BP
4071 ofpbuf_uninit(&of_in);
4072 ofpbuf_uninit(&of_out);
f25d0cf3
BP
4073 }
4074 ds_destroy(&in);
4075}
4076
65a8a59e
BP
4077/* "parse-actions VERSION": reads a series of action specifications for the
4078 * given OpenFlow VERSION as hex bytes from stdin, converts them to ofpacts,
4079 * prints them as strings on stdout, and then converts them back to hex bytes
4080 * and prints any differences from the input. */
8f2cded4 4081static void
1636c761 4082ofctl_parse_actions(struct ovs_cmdl_context *ctx)
8f2cded4 4083{
1636c761 4084 ofctl_parse_actions__(ctx->argv[1], false);
8f2cded4
BP
4085}
4086
65a8a59e
BP
4087/* "parse-actions VERSION": reads a series of instruction specifications for
4088 * the given OpenFlow VERSION as hex bytes from stdin, converts them to
4089 * ofpacts, prints them as strings on stdout, and then converts them back to
4090 * hex bytes and prints any differences from the input. */
8f2cded4 4091static void
1636c761 4092ofctl_parse_instructions(struct ovs_cmdl_context *ctx)
8f2cded4 4093{
1636c761 4094 ofctl_parse_actions__(ctx->argv[1], true);
8f2cded4
BP
4095}
4096
96628ae8
BP
4097/* "parse-ofp10-match": reads a series of ofp10_match specifications as hex
4098 * bytes from stdin, converts them to cls_rules, prints them as strings on
4099 * stdout, and then converts them back to hex bytes and prints any differences
8812ec2c
BP
4100 * from the input.
4101 *
4102 * The input hex bytes may contain "x"s to represent "don't-cares", bytes whose
4103 * values are ignored in the input and will be set to zero when OVS converts
4104 * them back to hex bytes. ovs-ofctl actually sets "x"s to random bits when
4105 * it does the conversion to hex, to ensure that in fact they are ignored. */
96628ae8 4106static void
1636c761 4107ofctl_parse_ofp10_match(struct ovs_cmdl_context *ctx OVS_UNUSED)
96628ae8 4108{
8812ec2c 4109 struct ds expout;
96628ae8
BP
4110 struct ds in;
4111
4112 ds_init(&in);
8812ec2c 4113 ds_init(&expout);
bdda5aca 4114 while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
8812ec2c 4115 struct ofpbuf match_in, match_expout;
96628ae8
BP
4116 struct ofp10_match match_out;
4117 struct ofp10_match match_normal;
81a76618 4118 struct match match;
8812ec2c
BP
4119 char *p;
4120
4121 /* Parse hex bytes to use for expected output. */
4122 ds_clear(&expout);
4123 ds_put_cstr(&expout, ds_cstr(&in));
4124 for (p = ds_cstr(&expout); *p; p++) {
4125 if (*p == 'x') {
4126 *p = '0';
4127 }
4128 }
4129 ofpbuf_init(&match_expout, 0);
4130 if (ofpbuf_put_hex(&match_expout, ds_cstr(&expout), NULL)[0] != '\0') {
4131 ovs_fatal(0, "Trailing garbage in hex data");
4132 }
6fd6ed71 4133 if (match_expout.size != sizeof(struct ofp10_match)) {
437d0d22 4134 ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
6fd6ed71 4135 match_expout.size, sizeof(struct ofp10_match));
8812ec2c 4136 }
96628ae8 4137
8812ec2c
BP
4138 /* Parse hex bytes for input. */
4139 for (p = ds_cstr(&in); *p; p++) {
4140 if (*p == 'x') {
4141 *p = "0123456789abcdef"[random_uint32() & 0xf];
4142 }
4143 }
96628ae8
BP
4144 ofpbuf_init(&match_in, 0);
4145 if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
4146 ovs_fatal(0, "Trailing garbage in hex data");
4147 }
6fd6ed71 4148 if (match_in.size != sizeof(struct ofp10_match)) {
437d0d22 4149 ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
6fd6ed71 4150 match_in.size, sizeof(struct ofp10_match));
96628ae8
BP
4151 }
4152
4153 /* Convert to cls_rule and print. */
6fd6ed71 4154 ofputil_match_from_ofp10_match(match_in.data, &match);
50f96b10 4155 match_print(&match, NULL);
96628ae8
BP
4156
4157 /* Convert back to ofp10_match and print differences from input. */
81a76618 4158 ofputil_match_to_ofp10_match(&match, &match_out);
6fd6ed71 4159 print_differences("", match_expout.data, match_expout.size,
96628ae8
BP
4160 &match_out, sizeof match_out);
4161
4162 /* Normalize, then convert and compare again. */
81a76618
BP
4163 ofputil_normalize_match(&match);
4164 ofputil_match_to_ofp10_match(&match, &match_normal);
96628ae8
BP
4165 print_differences("normal: ", &match_out, sizeof match_out,
4166 &match_normal, sizeof match_normal);
4167 putchar('\n');
4168
4169 ofpbuf_uninit(&match_in);
8812ec2c 4170 ofpbuf_uninit(&match_expout);
96628ae8
BP
4171 }
4172 ds_destroy(&in);
8812ec2c 4173 ds_destroy(&expout);
96628ae8
BP
4174}
4175
410698cf 4176/* "parse-ofp11-match": reads a series of ofp11_match specifications as hex
81a76618
BP
4177 * bytes from stdin, converts them to "struct match"es, prints them as strings
4178 * on stdout, and then converts them back to hex bytes and prints any
4179 * differences from the input. */
410698cf 4180static void
1636c761 4181ofctl_parse_ofp11_match(struct ovs_cmdl_context *ctx OVS_UNUSED)
410698cf
BP
4182{
4183 struct ds in;
4184
4185 ds_init(&in);
bdda5aca 4186 while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
410698cf
BP
4187 struct ofpbuf match_in;
4188 struct ofp11_match match_out;
81a76618 4189 struct match match;
410698cf 4190 enum ofperr error;
410698cf
BP
4191
4192 /* Parse hex bytes. */
4193 ofpbuf_init(&match_in, 0);
4194 if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
4195 ovs_fatal(0, "Trailing garbage in hex data");
4196 }
6fd6ed71 4197 if (match_in.size != sizeof(struct ofp11_match)) {
437d0d22 4198 ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
6fd6ed71 4199 match_in.size, sizeof(struct ofp11_match));
410698cf
BP
4200 }
4201
81a76618 4202 /* Convert to match. */
6fd6ed71 4203 error = ofputil_match_from_ofp11_match(match_in.data, &match);
410698cf
BP
4204 if (error) {
4205 printf("bad ofp11_match: %s\n\n", ofperr_get_name(error));
4206 ofpbuf_uninit(&match_in);
4207 continue;
4208 }
4209
81a76618 4210 /* Print match. */
50f96b10 4211 match_print(&match, NULL);
410698cf
BP
4212
4213 /* Convert back to ofp11_match and print differences from input. */
81a76618 4214 ofputil_match_to_ofp11_match(&match, &match_out);
410698cf 4215
6fd6ed71 4216 print_differences("", match_in.data, match_in.size,
d01c980f
BP
4217 &match_out, sizeof match_out);
4218 putchar('\n');
410698cf 4219
d01c980f
BP
4220 ofpbuf_uninit(&match_in);
4221 }
4222 ds_destroy(&in);
4223}
4224
77ab5fd2
BP
4225/* "parse-pcap PCAP...": read packets from each PCAP file and print their
4226 * flows. */
14249c02 4227static void
1636c761 4228ofctl_parse_pcap(struct ovs_cmdl_context *ctx)
14249c02 4229{
77ab5fd2
BP
4230 int error = 0;
4231 for (int i = 1; i < ctx->argc; i++) {
4232 const char *filename = ctx->argv[i];
4233 FILE *pcap = ovs_pcap_open(filename, "rb");
4234 if (!pcap) {
4235 error = errno;
4236 ovs_error(error, "%s: open failed", filename);
4237 continue;
4238 }
14249c02 4239
77ab5fd2
BP
4240 for (;;) {
4241 struct dp_packet *packet;
4242 struct flow flow;
4243 int retval;
14249c02 4244
77ab5fd2
BP
4245 retval = ovs_pcap_read(pcap, &packet, NULL);
4246 if (retval == EOF) {
4247 break;
4248 } else if (retval) {
4249 error = retval;
4250 ovs_error(error, "%s: read failed", filename);
4251 }
14249c02 4252
117d7249 4253 pkt_metadata_init(&packet->md, u32_to_odp(ofp_to_u16(OFPP_ANY)));
77ab5fd2 4254 flow_extract(packet, &flow);
50f96b10 4255 flow_print(stdout, &flow, NULL);
77ab5fd2
BP
4256 putchar('\n');
4257 dp_packet_delete(packet);
14249c02 4258 }
77ab5fd2 4259 fclose(pcap);
14249c02 4260 }
77ab5fd2 4261 exit(error);
14249c02
BP
4262}
4263
df778240
BP
4264/* "check-vlan VLAN_TCI VLAN_TCI_MASK": converts the specified vlan_tci and
4265 * mask values to and from various formats and prints the results. */
4266static void
1636c761 4267ofctl_check_vlan(struct ovs_cmdl_context *ctx)
df778240 4268{
81a76618 4269 struct match match;
df778240
BP
4270
4271 char *string_s;
4272 struct ofputil_flow_mod fm;
4273
4274 struct ofpbuf nxm;
81a76618 4275 struct match nxm_match;
df778240
BP
4276 int nxm_match_len;
4277 char *nxm_s;
4278
81a76618
BP
4279 struct ofp10_match of10_raw;
4280 struct match of10_match;
df778240 4281
81a76618
BP
4282 struct ofp11_match of11_raw;
4283 struct match of11_match;
df778240
BP
4284
4285 enum ofperr error;
bdda5aca 4286 char *error_s;
df778240 4287
db0b6c29
JR
4288 enum ofputil_protocol usable_protocols; /* Unused for now. */
4289
81a76618 4290 match_init_catchall(&match);
f0fb825a
EG
4291 match.flow.vlans[0].tci = htons(strtoul(ctx->argv[1], NULL, 16));
4292 match.wc.masks.vlans[0].tci = htons(strtoul(ctx->argv[2], NULL, 16));
df778240
BP
4293
4294 /* Convert to and from string. */
50f96b10 4295 string_s = match_to_string(&match, NULL, OFP_DEFAULT_PRIORITY);
df778240
BP
4296 printf("%s -> ", string_s);
4297 fflush(stdout);
50f96b10 4298 error_s = parse_ofp_str(&fm, -1, string_s, NULL, &usable_protocols);
bdda5aca
BP
4299 if (error_s) {
4300 ovs_fatal(0, "%s", error_s);
4301 }
df778240 4302 printf("%04"PRIx16"/%04"PRIx16"\n",
f0fb825a
EG
4303 ntohs(fm.match.flow.vlans[0].tci),
4304 ntohs(fm.match.wc.masks.vlans[0].tci));
4d859fa9 4305 free(string_s);
df778240
BP
4306
4307 /* Convert to and from NXM. */
4308 ofpbuf_init(&nxm, 0);
81a76618 4309 nxm_match_len = nx_put_match(&nxm, &match, htonll(0), htonll(0));
6fd6ed71 4310 nxm_s = nx_match_to_string(nxm.data, nxm_match_len);
d7892c81
YHW
4311 error = nx_pull_match(&nxm, nxm_match_len, &nxm_match, NULL, NULL, false,
4312 NULL, NULL);
df778240
BP
4313 printf("NXM: %s -> ", nxm_s);
4314 if (error) {
4315 printf("%s\n", ofperr_to_string(error));
4316 } else {
4317 printf("%04"PRIx16"/%04"PRIx16"\n",
f0fb825a
EG
4318 ntohs(nxm_match.flow.vlans[0].tci),
4319 ntohs(nxm_match.wc.masks.vlans[0].tci));
df778240
BP
4320 }
4321 free(nxm_s);
4322 ofpbuf_uninit(&nxm);
4323
476a0e9e
SH
4324 /* Convert to and from OXM. */
4325 ofpbuf_init(&nxm, 0);
9d84066c 4326 nxm_match_len = oxm_put_match(&nxm, &match, OFP12_VERSION);
db5a1019 4327 nxm_s = oxm_match_to_string(&nxm, nxm_match_len);
d7892c81 4328 error = oxm_pull_match(&nxm, false, NULL, NULL, &nxm_match);
476a0e9e
SH
4329 printf("OXM: %s -> ", nxm_s);
4330 if (error) {
4331 printf("%s\n", ofperr_to_string(error));
4332 } else {
f0fb825a 4333 uint16_t vid = ntohs(nxm_match.flow.vlans[0].tci) &
476a0e9e 4334 (VLAN_VID_MASK | VLAN_CFI);
f0fb825a 4335 uint16_t mask = ntohs(nxm_match.wc.masks.vlans[0].tci) &
476a0e9e
SH
4336 (VLAN_VID_MASK | VLAN_CFI);
4337
4338 printf("%04"PRIx16"/%04"PRIx16",", vid, mask);
f0fb825a 4339 if (vid && vlan_tci_to_pcp(nxm_match.wc.masks.vlans[0].tci)) {
fd13c6b5 4340 printf("%02d\n", vlan_tci_to_pcp(nxm_match.flow.vlans[0].tci));
476a0e9e
SH
4341 } else {
4342 printf("--\n");
4343 }
4344 }
4345 free(nxm_s);
4346 ofpbuf_uninit(&nxm);
4347
df778240 4348 /* Convert to and from OpenFlow 1.0. */
81a76618
BP
4349 ofputil_match_to_ofp10_match(&match, &of10_raw);
4350 ofputil_match_from_ofp10_match(&of10_raw, &of10_match);
df778240 4351 printf("OF1.0: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
81a76618
BP
4352 ntohs(of10_raw.dl_vlan),
4353 (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN)) != 0,
4354 of10_raw.dl_vlan_pcp,
4355 (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN_PCP)) != 0,
f0fb825a
EG
4356 ntohs(of10_match.flow.vlans[0].tci),
4357 ntohs(of10_match.wc.masks.vlans[0].tci));
df778240
BP
4358
4359 /* Convert to and from OpenFlow 1.1. */
81a76618
BP
4360 ofputil_match_to_ofp11_match(&match, &of11_raw);
4361 ofputil_match_from_ofp11_match(&of11_raw, &of11_match);
df778240 4362 printf("OF1.1: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
81a76618
BP
4363 ntohs(of11_raw.dl_vlan),
4364 (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN)) != 0,
4365 of11_raw.dl_vlan_pcp,
4366 (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN_PCP)) != 0,
f0fb825a
EG
4367 ntohs(of11_match.flow.vlans[0].tci),
4368 ntohs(of11_match.wc.masks.vlans[0].tci));
df778240
BP
4369}
4370
2e0525bc
SH
4371/* "print-error ENUM": Prints the type and code of ENUM for every OpenFlow
4372 * version. */
4373static void
1636c761 4374ofctl_print_error(struct ovs_cmdl_context *ctx)
2e0525bc
SH
4375{
4376 enum ofperr error;
4377 int version;
4378
1636c761 4379 error = ofperr_from_name(ctx->argv[1]);
2e0525bc 4380 if (!error) {
1636c761 4381 ovs_fatal(0, "unknown error \"%s\"", ctx->argv[1]);
2e0525bc
SH
4382 }
4383
4384 for (version = 0; version <= UINT8_MAX; version++) {
688e86e1 4385 const char *name = ofperr_domain_get_name(version);
514887ee
BP
4386 if (name) {
4387 int vendor = ofperr_get_vendor(error, version);
4388 int type = ofperr_get_type(error, version);
4389 int code = ofperr_get_code(error, version);
4390
4391 if (vendor != -1 || type != -1 || code != -1) {
4392 printf("%s: vendor %#x, type %d, code %d\n",
4393 name, vendor, type, code);
4394 }
2e0525bc 4395 }
2e0525bc
SH
4396 }
4397}
4398
edd70aa7
BP
4399/* "encode-error-reply ENUM REQUEST": Encodes an error reply to REQUEST for the
4400 * error named ENUM and prints the error reply in hex. */
4401static void
1636c761 4402ofctl_encode_error_reply(struct ovs_cmdl_context *ctx)
edd70aa7
BP
4403{
4404 const struct ofp_header *oh;
4405 struct ofpbuf request, *reply;
4406 enum ofperr error;
4407
1636c761 4408 error = ofperr_from_name(ctx->argv[1]);
edd70aa7 4409 if (!error) {
1636c761 4410 ovs_fatal(0, "unknown error \"%s\"", ctx->argv[1]);
edd70aa7
BP
4411 }
4412
4413 ofpbuf_init(&request, 0);
1636c761 4414 if (ofpbuf_put_hex(&request, ctx->argv[2], NULL)[0] != '\0') {
edd70aa7
BP
4415 ovs_fatal(0, "Trailing garbage in hex data");
4416 }
6fd6ed71 4417 if (request.size < sizeof(struct ofp_header)) {
edd70aa7
BP
4418 ovs_fatal(0, "Request too short");
4419 }
4420
6fd6ed71
PS
4421 oh = request.data;
4422 if (request.size != ntohs(oh->length)) {
edd70aa7
BP
4423 ovs_fatal(0, "Request size inconsistent");
4424 }
4425
6fd6ed71 4426 reply = ofperr_encode_reply(error, request.data);
edd70aa7
BP
4427 ofpbuf_uninit(&request);
4428
6fd6ed71 4429 ovs_hex_dump(stdout, reply->data, reply->size, 0, false);
edd70aa7
BP
4430 ofpbuf_delete(reply);
4431}
4432
fec00620
BP
4433/* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
4434 * binary data, interpreting them as an OpenFlow message, and prints the
8b227701
GS
4435 * OpenFlow message on stdout, at VERBOSITY (level 2 by default).
4436 *
4437 * Alternative usage: "ofp-print [VERBOSITY] - < HEXSTRING_FILE", where
4438 * HEXSTRING_FILE contains the HEXSTRING. */
fec00620 4439static void
1636c761 4440ofctl_ofp_print(struct ovs_cmdl_context *ctx)
fec00620
BP
4441{
4442 struct ofpbuf packet;
8b227701
GS
4443 char *buffer;
4444 int verbosity = 2;
4445 struct ds line;
4446
4447 ds_init(&line);
4448
1636c761 4449 if (!strcmp(ctx->argv[ctx->argc-1], "-")) {
8b227701
GS
4450 if (ds_get_line(&line, stdin)) {
4451 VLOG_FATAL("Failed to read stdin");
4452 }
4453
4454 buffer = line.string;
1636c761
RB
4455 verbosity = ctx->argc > 2 ? atoi(ctx->argv[1]) : verbosity;
4456 } else if (ctx->argc > 2) {
4457 buffer = ctx->argv[1];
4458 verbosity = atoi(ctx->argv[2]);
8b227701 4459 } else {
1636c761 4460 buffer = ctx->argv[1];
8b227701 4461 }
fec00620 4462
8b227701
GS
4463 ofpbuf_init(&packet, strlen(buffer) / 2);
4464 if (ofpbuf_put_hex(&packet, buffer, NULL)[0] != '\0') {
fec00620
BP
4465 ovs_fatal(0, "trailing garbage following hex bytes");
4466 }
50f96b10 4467 ofp_print(stdout, packet.data, packet.size, NULL, verbosity);
fec00620 4468 ofpbuf_uninit(&packet);
8b227701 4469 ds_destroy(&line);
fec00620
BP
4470}
4471
681ea7a0
BP
4472/* "encode-hello BITMAP...": Encodes each BITMAP as an OpenFlow hello message
4473 * and dumps each message in hex. */
4474static void
1636c761 4475ofctl_encode_hello(struct ovs_cmdl_context *ctx)
681ea7a0 4476{
1636c761 4477 uint32_t bitmap = strtol(ctx->argv[1], NULL, 0);
681ea7a0
BP
4478 struct ofpbuf *hello;
4479
4480 hello = ofputil_encode_hello(bitmap);
6fd6ed71 4481 ovs_hex_dump(stdout, hello->data, hello->size, 0, false);
50f96b10 4482 ofp_print(stdout, hello->data, hello->size, NULL, verbosity);
681ea7a0
BP
4483 ofpbuf_delete(hello);
4484}
4485
4a48cdfb
BP
4486static void
4487ofctl_parse_key_value(struct ovs_cmdl_context *ctx)
4488{
4489 for (size_t i = 1; i < ctx->argc; i++) {
4490 char *s = ctx->argv[i];
4491 char *key, *value;
4492 int j = 0;
4493 while (ofputil_parse_key_value(&s, &key, &value)) {
4494 if (j++) {
4495 fputs(", ", stdout);
4496 }
4497 fputs(key, stdout);
4498 if (value[0]) {
4499 printf("=%s", value);
4500 }
4501 }
4502 putchar('\n');
4503 }
4504}
4505
d060b8ab
BP
4506/* "compose-packet [--pcap] FLOW [L7]": Converts the OpenFlow flow
4507 * specification FLOW to a packet with flow_compose() and prints the hex bytes
4508 * in the packet on stdout. Also verifies that the flow extracted from that
4509 * packet matches the original FLOW.
4510 *
4511 * With --pcap, prints the packet to stdout instead as a pcap file, so that you
31bd820c
BP
4512 * can do something like "ovs-ofctl --pcap compose-packet udp | tcpdump -vvvv
4513 * -r-" to use another tool to dump the packet contents.
d060b8ab
BP
4514 *
4515 * If L7 is specified, draws the L7 payload data from it, otherwise defaults to
4516 * 64 bytes of payload. */
4517static void
4518ofctl_compose_packet(struct ovs_cmdl_context *ctx)
4519{
4520 if (print_pcap && isatty(STDOUT_FILENO)) {
4521 ovs_fatal(1, "not writing pcap data to stdout; redirect to a file "
4522 "or pipe to tcpdump instead");
4523 }
4524
4525 struct flow flow1;
4526 char *error = parse_ofp_exact_flow(&flow1, NULL, NULL, ctx->argv[1], NULL);
4527 if (error) {
4528 ovs_fatal(0, "%s", error);
4529 }
4530
4531 struct dp_packet p;
4532 memset(&p, 0, sizeof p);
4533 dp_packet_init(&p, 0);
4534
4535 void *l7 = NULL;
4536 size_t l7_len = 64;
4537 if (ctx->argc > 2) {
4538 struct dp_packet payload;
4539 memset(&payload, 0, sizeof payload);
4540 dp_packet_init(&payload, 0);
4541 if (dp_packet_put_hex(&payload, ctx->argv[2], NULL)[0] != '\0') {
4542 ovs_fatal(0, "%s: trailing garbage in packet data", ctx->argv[2]);
4543 }
4544 l7_len = dp_packet_size(&payload);
4545 l7 = dp_packet_steal_data(&payload);
4546 }
4547 flow_compose(&p, &flow1, l7, l7_len);
4548 free(l7);
4549
4550 if (print_pcap) {
4551 ovs_pcap_write_header(stdout);
4552 ovs_pcap_write(stdout, &p);
4553 } else {
4554 ovs_hex_dump(stdout, dp_packet_data(&p), dp_packet_size(&p), 0, false);
4555 }
4556
4557 struct flow flow2;
4558 flow_extract(&p, &flow2);
4559 flow2.in_port.ofp_port = OFPP_ANY;
4560
4561 dp_packet_uninit(&p);
4562
4563 if (!flow_equal(&flow1, &flow2)) {
4564 fprintf(stderr, "specified and extracted flows differ:\n");
4565 fputs("specified: ", stderr);
4566 flow_print(stderr, &flow1, NULL);
4567 fputs("\nextracted: ", stderr);
4568 flow_print(stderr, &flow2, NULL);
4569 exit(1);
4570 }
4571}
4572
5f383751 4573static const struct ovs_cmdl_command all_commands[] = {
451de37e 4574 { "show", "switch",
1f4a7252 4575 1, 1, ofctl_show, OVS_RO },
451de37e 4576 { "monitor", "switch [misslen] [invalid_ttl] [watch:[...]]",
1f4a7252 4577 1, 3, ofctl_monitor, OVS_RO },
451de37e 4578 { "snoop", "switch",
1f4a7252 4579 1, 1, ofctl_snoop, OVS_RO },
451de37e 4580 { "dump-desc", "switch",
1f4a7252 4581 1, 1, ofctl_dump_desc, OVS_RO },
451de37e 4582 { "dump-tables", "switch",
1f4a7252 4583 1, 1, ofctl_dump_tables, OVS_RO },
451de37e 4584 { "dump-table-features", "switch",
1f4a7252 4585 1, 1, ofctl_dump_table_features, OVS_RO },
03c72922 4586 { "dump-table-desc", "switch",
1f4a7252 4587 1, 1, ofctl_dump_table_desc, OVS_RO },
451de37e 4588 { "dump-flows", "switch",
1f4a7252 4589 1, 2, ofctl_dump_flows, OVS_RO },
451de37e 4590 { "dump-aggregate", "switch",
1f4a7252 4591 1, 2, ofctl_dump_aggregate, OVS_RO },
451de37e 4592 { "queue-stats", "switch [port [queue]]",
1f4a7252 4593 1, 3, ofctl_queue_stats, OVS_RO },
e016fb63 4594 { "queue-get-config", "switch [port [queue]]",
1f4a7252 4595 1, 3, ofctl_queue_get_config, OVS_RO },
451de37e 4596 { "add-flow", "switch flow",
1f4a7252 4597 2, 2, ofctl_add_flow, OVS_RW },
451de37e 4598 { "add-flows", "switch file",
1f4a7252 4599 2, 2, ofctl_add_flows, OVS_RW },
451de37e 4600 { "mod-flows", "switch flow",
1f4a7252 4601 2, 2, ofctl_mod_flows, OVS_RW },
451de37e 4602 { "del-flows", "switch [flow]",
1f4a7252 4603 1, 2, ofctl_del_flows, OVS_RW },
451de37e 4604 { "replace-flows", "switch file",
1f4a7252 4605 2, 2, ofctl_replace_flows, OVS_RW },
451de37e 4606 { "diff-flows", "source1 source2",
1f4a7252 4607 2, 2, ofctl_diff_flows, OVS_RW },
451de37e 4608 { "add-meter", "switch meter",
1f4a7252 4609 2, 2, ofctl_add_meter, OVS_RW },
451de37e 4610 { "mod-meter", "switch meter",
1f4a7252 4611 2, 2, ofctl_mod_meter, OVS_RW },
451de37e 4612 { "del-meter", "switch meter",
1f4a7252 4613 2, 2, ofctl_del_meters, OVS_RW },
451de37e 4614 { "del-meters", "switch",
1f4a7252 4615 1, 1, ofctl_del_meters, OVS_RW },
451de37e 4616 { "dump-meter", "switch meter",
1f4a7252 4617 2, 2, ofctl_dump_meters, OVS_RO },
451de37e 4618 { "dump-meters", "switch",
1f4a7252 4619 1, 1, ofctl_dump_meters, OVS_RO },
451de37e 4620 { "meter-stats", "switch [meter]",
1f4a7252 4621 1, 2, ofctl_meter_stats, OVS_RO },
451de37e 4622 { "meter-features", "switch",
1f4a7252 4623 1, 1, ofctl_meter_features, OVS_RO },
6dd3c787
JR
4624 { "packet-out", "switch \"in_port=<port> packet=<hex data> actions=...\"",
4625 2, INT_MAX, ofctl_packet_out, OVS_RW },
451de37e 4626 { "dump-ports", "switch [port]",
1f4a7252 4627 1, 2, ofctl_dump_ports, OVS_RO },
451de37e 4628 { "dump-ports-desc", "switch [port]",
1f4a7252 4629 1, 2, ofctl_dump_ports_desc, OVS_RO },
451de37e 4630 { "mod-port", "switch iface act",
1f4a7252 4631 3, 3, ofctl_mod_port, OVS_RW },
451de37e 4632 { "mod-table", "switch mod",
1f4a7252 4633 3, 3, ofctl_mod_table, OVS_RW },
451de37e 4634 { "get-frags", "switch",
1f4a7252 4635 1, 1, ofctl_get_frags, OVS_RO },
451de37e 4636 { "set-frags", "switch frag_mode",
1f4a7252 4637 2, 2, ofctl_set_frags, OVS_RW },
451de37e 4638 { "probe", "target",
1f4a7252 4639 1, 1, ofctl_probe, OVS_RO },
451de37e 4640 { "ping", "target [n]",
1f4a7252 4641 1, 2, ofctl_ping, OVS_RO },
451de37e 4642 { "benchmark", "target n count",
1f4a7252 4643 3, 3, ofctl_benchmark, OVS_RO },
451de37e 4644
fb8f22c1 4645 { "dump-ipfix-bridge", "switch",
1f4a7252 4646 1, 1, ofctl_dump_ipfix_bridge, OVS_RO },
fb8f22c1 4647 { "dump-ipfix-flow", "switch",
1f4a7252 4648 1, 1, ofctl_dump_ipfix_flow, OVS_RO },
fb8f22c1 4649
2a7c4805
JP
4650 { "ct-flush-zone", "switch zone",
4651 2, 2, ofctl_ct_flush_zone, OVS_RO },
4652
451de37e 4653 { "ofp-parse", "file",
1f4a7252 4654 1, 1, ofctl_ofp_parse, OVS_RW },
451de37e 4655 { "ofp-parse-pcap", "pcap",
1f4a7252 4656 1, INT_MAX, ofctl_ofp_parse_pcap, OVS_RW },
451de37e
AW
4657
4658 { "add-group", "switch group",
1f4a7252 4659 1, 2, ofctl_add_group, OVS_RW },
451de37e 4660 { "add-groups", "switch file",
1f4a7252 4661 1, 2, ofctl_add_groups, OVS_RW },
451de37e 4662 { "mod-group", "switch group",
1f4a7252 4663 1, 2, ofctl_mod_group, OVS_RW },
451de37e 4664 { "del-groups", "switch [group]",
1f4a7252 4665 1, 2, ofctl_del_groups, OVS_RW },
bdbb8426 4666 { "insert-buckets", "switch [group]",
1f4a7252 4667 1, 2, ofctl_insert_bucket, OVS_RW },
bdbb8426 4668 { "remove-buckets", "switch [group]",
1f4a7252 4669 1, 2, ofctl_remove_bucket, OVS_RW },
451de37e 4670 { "dump-groups", "switch [group]",
1f4a7252 4671 1, 2, ofctl_dump_group_desc, OVS_RO },
451de37e 4672 { "dump-group-stats", "switch [group]",
1f4a7252 4673 1, 2, ofctl_dump_group_stats, OVS_RO },
451de37e 4674 { "dump-group-features", "switch",
1f4a7252 4675 1, 1, ofctl_dump_group_features, OVS_RO },
25070e04
JR
4676
4677 { "bundle", "switch file",
1f4a7252 4678 2, 2, ofctl_bundle, OVS_RW },
25070e04 4679
4e548ad9 4680 { "add-tlv-map", "switch map",
1f4a7252 4681 2, 2, ofctl_add_tlv_map, OVS_RO },
4e548ad9 4682 { "del-tlv-map", "switch [map]",
1f4a7252 4683 1, 2, ofctl_del_tlv_map, OVS_RO },
4e548ad9 4684 { "dump-tlv-map", "switch",
1f4a7252
RM
4685 1, 1, ofctl_dump_tlv_map, OVS_RO },
4686 { "help", NULL, 0, INT_MAX, ofctl_help, OVS_RO },
4687 { "list-commands", NULL, 0, INT_MAX, ofctl_list_commands, OVS_RO },
09246b99
BP
4688
4689 /* Undocumented commands for testing. */
1f4a7252
RM
4690 { "parse-flow", NULL, 1, 1, ofctl_parse_flow, OVS_RW },
4691 { "parse-flows", NULL, 1, 1, ofctl_parse_flows, OVS_RW },
4692 { "parse-nx-match", NULL, 0, 0, ofctl_parse_nxm, OVS_RW },
4693 { "parse-nxm", NULL, 0, 0, ofctl_parse_nxm, OVS_RW },
4694 { "parse-oxm", NULL, 1, 1, ofctl_parse_oxm, OVS_RW },
4695 { "parse-actions", NULL, 1, 1, ofctl_parse_actions, OVS_RW },
4696 { "parse-instructions", NULL, 1, 1, ofctl_parse_instructions, OVS_RW },
4697 { "parse-ofp10-match", NULL, 0, 0, ofctl_parse_ofp10_match, OVS_RW },
4698 { "parse-ofp11-match", NULL, 0, 0, ofctl_parse_ofp11_match, OVS_RW },
4699 { "parse-pcap", NULL, 1, INT_MAX, ofctl_parse_pcap, OVS_RW },
4700 { "check-vlan", NULL, 2, 2, ofctl_check_vlan, OVS_RW },
4701 { "print-error", NULL, 1, 1, ofctl_print_error, OVS_RW },
4702 { "encode-error-reply", NULL, 2, 2, ofctl_encode_error_reply, OVS_RW },
4703 { "ofp-print", NULL, 1, 2, ofctl_ofp_print, OVS_RW },
4704 { "encode-hello", NULL, 1, 1, ofctl_encode_hello, OVS_RW },
4705 { "parse-key-value", NULL, 1, INT_MAX, ofctl_parse_key_value, OVS_RW },
d060b8ab 4706 { "compose-packet", NULL, 1, 2, ofctl_compose_packet, OVS_RO },
1f4a7252
RM
4707
4708 { NULL, NULL, 0, 0, NULL, OVS_RO },
064af421 4709};
3815d6c2 4710
5f383751 4711static const struct ovs_cmdl_command *get_all_commands(void)
3815d6c2
LS
4712{
4713 return all_commands;
4714}