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