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