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