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