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