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