]> git.proxmox.com Git - mirror_ovs.git/blob - utilities/ovs-ofctl.c
Merge remote-tracking branch 'origin/master' into ovn3
[mirror_ovs.git] / utilities / ovs-ofctl.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 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 "compiler.h"
37 #include "dirs.h"
38 #include "dynamic-string.h"
39 #include "fatal-signal.h"
40 #include "nx-match.h"
41 #include "odp-util.h"
42 #include "ofp-actions.h"
43 #include "ofp-errors.h"
44 #include "ofp-msgs.h"
45 #include "ofp-parse.h"
46 #include "ofp-print.h"
47 #include "ofp-util.h"
48 #include "ofp-version-opt.h"
49 #include "ofpbuf.h"
50 #include "ofproto/ofproto.h"
51 #include "openflow/nicira-ext.h"
52 #include "openflow/openflow.h"
53 #include "dp-packet.h"
54 #include "packets.h"
55 #include "pcap-file.h"
56 #include "poll-loop.h"
57 #include "random.h"
58 #include "stream-ssl.h"
59 #include "socket-util.h"
60 #include "timeval.h"
61 #include "unixctl.h"
62 #include "util.h"
63 #include "openvswitch/vconn.h"
64 #include "openvswitch/vlog.h"
65 #include "meta-flow.h"
66 #include "sort.h"
67
68 VLOG_DEFINE_THIS_MODULE(ofctl);
69
70 /* --strict: Use strict matching for flow mod commands? Additionally governs
71 * use of nx_pull_match() instead of nx_pull_match_loose() in parse-nx-match.
72 */
73 static bool strict;
74
75 /* --readd: If true, on replace-flows, re-add even flows that have not changed
76 * (to reset flow counters). */
77 static bool readd;
78
79 /* -F, --flow-format: Allowed protocols. By default, any protocol is
80 * allowed. */
81 static enum ofputil_protocol allowed_protocols = OFPUTIL_P_ANY;
82
83 /* -P, --packet-in-format: Packet IN format to use in monitor and snoop
84 * commands. Either one of NXPIF_* to force a particular packet_in format, or
85 * -1 to let ovs-ofctl choose the default. */
86 static int preferred_packet_in_format = -1;
87
88 /* -m, --more: Additional verbosity for ofp-print functions. */
89 static int verbosity;
90
91 /* --timestamp: Print a timestamp before each received packet on "monitor" and
92 * "snoop" command? */
93 static bool timestamp;
94
95 /* --unixctl-path: Path to use for unixctl server, for "monitor" and "snoop"
96 commands. */
97 static char *unixctl_path;
98
99 /* --sort, --rsort: Sort order. */
100 enum sort_order { SORT_ASC, SORT_DESC };
101 struct sort_criterion {
102 const struct mf_field *field; /* NULL means to sort by priority. */
103 enum sort_order order;
104 };
105 static struct sort_criterion *criteria;
106 static size_t n_criteria, allocated_criteria;
107
108 static const struct command *get_all_commands(void);
109
110 OVS_NO_RETURN static void usage(void);
111 static void parse_options(int argc, char *argv[]);
112
113 static bool recv_flow_stats_reply(struct vconn *, ovs_be32 send_xid,
114 struct ofpbuf **replyp,
115 struct ofputil_flow_stats *,
116 struct ofpbuf *ofpacts);
117 int
118 main(int argc, char *argv[])
119 {
120 set_program_name(argv[0]);
121 service_start(&argc, &argv);
122 parse_options(argc, argv);
123 fatal_ignore_sigpipe();
124 run_command(argc - optind, argv + optind, get_all_commands());
125 return 0;
126 }
127
128 static void
129 add_sort_criterion(enum sort_order order, const char *field)
130 {
131 struct sort_criterion *sc;
132
133 if (n_criteria >= allocated_criteria) {
134 criteria = x2nrealloc(criteria, &allocated_criteria, sizeof *criteria);
135 }
136
137 sc = &criteria[n_criteria++];
138 if (!field || !strcasecmp(field, "priority")) {
139 sc->field = NULL;
140 } else {
141 sc->field = mf_from_name(field);
142 if (!sc->field) {
143 ovs_fatal(0, "%s: unknown field name", field);
144 }
145 }
146 sc->order = order;
147 }
148
149 static void
150 parse_options(int argc, char *argv[])
151 {
152 enum {
153 OPT_STRICT = UCHAR_MAX + 1,
154 OPT_READD,
155 OPT_TIMESTAMP,
156 OPT_SORT,
157 OPT_RSORT,
158 OPT_UNIXCTL,
159 DAEMON_OPTION_ENUMS,
160 OFP_VERSION_OPTION_ENUMS,
161 VLOG_OPTION_ENUMS
162 };
163 static const struct option long_options[] = {
164 {"timeout", required_argument, NULL, 't'},
165 {"strict", no_argument, NULL, OPT_STRICT},
166 {"readd", no_argument, NULL, OPT_READD},
167 {"flow-format", required_argument, NULL, 'F'},
168 {"packet-in-format", required_argument, NULL, 'P'},
169 {"more", no_argument, NULL, 'm'},
170 {"timestamp", no_argument, NULL, OPT_TIMESTAMP},
171 {"sort", optional_argument, NULL, OPT_SORT},
172 {"rsort", optional_argument, NULL, OPT_RSORT},
173 {"unixctl", required_argument, NULL, OPT_UNIXCTL},
174 {"help", no_argument, NULL, 'h'},
175 {"option", no_argument, NULL, 'o'},
176 DAEMON_LONG_OPTIONS,
177 OFP_VERSION_LONG_OPTIONS,
178 VLOG_LONG_OPTIONS,
179 STREAM_SSL_LONG_OPTIONS,
180 {NULL, 0, NULL, 0},
181 };
182 char *short_options = long_options_to_short_options(long_options);
183 uint32_t versions;
184 enum ofputil_protocol version_protocols;
185
186 /* For now, ovs-ofctl only enables OpenFlow 1.0 by default. This is
187 * because ovs-ofctl implements command such as "add-flow" as raw OpenFlow
188 * requests, but those requests have subtly different semantics in
189 * different OpenFlow versions. For example:
190 *
191 * - In OpenFlow 1.0, a "mod-flow" operation that does not find any
192 * existing flow to modify adds a new flow.
193 *
194 * - In OpenFlow 1.1, a "mod-flow" operation that does not find any
195 * existing flow to modify adds a new flow, but only if the mod-flow
196 * did not match on the flow cookie.
197 *
198 * - In OpenFlow 1.2 and a later, a "mod-flow" operation never adds a
199 * new flow.
200 */
201 set_allowed_ofp_versions("OpenFlow10");
202
203 for (;;) {
204 unsigned long int timeout;
205 int c;
206
207 c = getopt_long(argc, argv, short_options, long_options, NULL);
208 if (c == -1) {
209 break;
210 }
211
212 switch (c) {
213 case 't':
214 timeout = strtoul(optarg, NULL, 10);
215 if (timeout <= 0) {
216 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
217 optarg);
218 } else {
219 time_alarm(timeout);
220 }
221 break;
222
223 case 'F':
224 allowed_protocols = ofputil_protocols_from_string(optarg);
225 if (!allowed_protocols) {
226 ovs_fatal(0, "%s: invalid flow format(s)", optarg);
227 }
228 break;
229
230 case 'P':
231 preferred_packet_in_format =
232 ofputil_packet_in_format_from_string(optarg);
233 if (preferred_packet_in_format < 0) {
234 ovs_fatal(0, "unknown packet-in format `%s'", optarg);
235 }
236 break;
237
238 case 'm':
239 verbosity++;
240 break;
241
242 case 'h':
243 usage();
244
245 case 'o':
246 print_options(long_options);
247 exit(EXIT_SUCCESS);
248
249 case OPT_STRICT:
250 strict = true;
251 break;
252
253 case OPT_READD:
254 readd = true;
255 break;
256
257 case OPT_TIMESTAMP:
258 timestamp = true;
259 break;
260
261 case OPT_SORT:
262 add_sort_criterion(SORT_ASC, optarg);
263 break;
264
265 case OPT_RSORT:
266 add_sort_criterion(SORT_DESC, optarg);
267 break;
268
269 case OPT_UNIXCTL:
270 unixctl_path = optarg;
271 break;
272
273 DAEMON_OPTION_HANDLERS
274 OFP_VERSION_OPTION_HANDLERS
275 VLOG_OPTION_HANDLERS
276 STREAM_SSL_OPTION_HANDLERS
277
278 case '?':
279 exit(EXIT_FAILURE);
280
281 default:
282 abort();
283 }
284 }
285
286 if (n_criteria) {
287 /* Always do a final sort pass based on priority. */
288 add_sort_criterion(SORT_DESC, "priority");
289 }
290
291 free(short_options);
292
293 versions = get_allowed_ofp_versions();
294 version_protocols = ofputil_protocols_from_version_bitmap(versions);
295 if (!(allowed_protocols & version_protocols)) {
296 char *protocols = ofputil_protocols_to_string(allowed_protocols);
297 struct ds version_s = DS_EMPTY_INITIALIZER;
298
299 ofputil_format_version_bitmap_names(&version_s, versions);
300 ovs_fatal(0, "None of the enabled OpenFlow versions (%s) supports "
301 "any of the enabled flow formats (%s). (Use -O to enable "
302 "additional OpenFlow versions or -F to enable additional "
303 "flow formats.)", ds_cstr(&version_s), protocols);
304 }
305 allowed_protocols &= version_protocols;
306 mask_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
307 allowed_protocols));
308 }
309
310 static void
311 usage(void)
312 {
313 printf("%s: OpenFlow switch management utility\n"
314 "usage: %s [OPTIONS] COMMAND [ARG...]\n"
315 "\nFor OpenFlow switches:\n"
316 " show SWITCH show OpenFlow information\n"
317 " dump-desc SWITCH print switch description\n"
318 " dump-tables SWITCH print table stats\n"
319 " dump-table-features SWITCH print table features\n"
320 " mod-port SWITCH IFACE ACT modify port behavior\n"
321 " mod-table SWITCH MOD modify flow table behavior\n"
322 " get-frags SWITCH print fragment handling behavior\n"
323 " set-frags SWITCH FRAG_MODE set fragment handling behavior\n"
324 " dump-ports SWITCH [PORT] print port statistics\n"
325 " dump-ports-desc SWITCH [PORT] print port descriptions\n"
326 " dump-flows SWITCH print all flow entries\n"
327 " dump-flows SWITCH FLOW print matching FLOWs\n"
328 " dump-aggregate SWITCH print aggregate flow statistics\n"
329 " dump-aggregate SWITCH FLOW print aggregate stats for FLOWs\n"
330 " queue-stats SWITCH [PORT [QUEUE]] dump queue stats\n"
331 " add-flow SWITCH FLOW add flow described by FLOW\n"
332 " add-flows SWITCH FILE add flows from FILE\n"
333 " mod-flows SWITCH FLOW modify actions of matching FLOWs\n"
334 " del-flows SWITCH [FLOW] delete matching FLOWs\n"
335 " replace-flows SWITCH FILE replace flows with those in FILE\n"
336 " diff-flows SOURCE1 SOURCE2 compare flows from two sources\n"
337 " packet-out SWITCH IN_PORT ACTIONS PACKET...\n"
338 " execute ACTIONS on PACKET\n"
339 " monitor SWITCH [MISSLEN] [invalid_ttl] [watch:[...]]\n"
340 " print packets received from SWITCH\n"
341 " snoop SWITCH snoop on SWITCH and its controller\n"
342 " add-group SWITCH GROUP add group described by GROUP\n"
343 " add-groups SWITCH FILE add group from FILE\n"
344 " mod-group SWITCH GROUP modify specific group\n"
345 " del-groups SWITCH [GROUP] delete matching GROUPs\n"
346 " insert-buckets SWITCH [GROUP] add buckets to GROUP\n"
347 " remove-buckets SWITCH [GROUP] remove buckets from GROUP\n"
348 " dump-group-features SWITCH print group features\n"
349 " dump-groups SWITCH [GROUP] print group description\n"
350 " dump-group-stats SWITCH [GROUP] print group statistics\n"
351 " queue-get-config SWITCH PORT print queue information for port\n"
352 " add-meter SWITCH METER add meter described by METER\n"
353 " mod-meter SWITCH METER modify specific METER\n"
354 " del-meter SWITCH METER delete METER\n"
355 " del-meters SWITCH delete all meters\n"
356 " dump-meter SWITCH METER print METER configuration\n"
357 " dump-meters SWITCH print all meter configuration\n"
358 " meter-stats SWITCH [METER] print meter statistics\n"
359 " meter-features SWITCH print meter features\n"
360 "\nFor OpenFlow switches and controllers:\n"
361 " probe TARGET probe whether TARGET is up\n"
362 " ping TARGET [N] latency of N-byte echos\n"
363 " benchmark TARGET N COUNT bandwidth of COUNT N-byte echos\n"
364 "SWITCH or TARGET is an active OpenFlow connection method.\n"
365 "\nOther commands:\n"
366 " ofp-parse FILE print messages read from FILE\n"
367 " ofp-parse-pcap PCAP print OpenFlow read from PCAP\n",
368 program_name, program_name);
369 vconn_usage(true, false, false);
370 daemon_usage();
371 ofp_version_usage();
372 vlog_usage();
373 printf("\nOther options:\n"
374 " --strict use strict match for flow commands\n"
375 " --readd replace flows that haven't changed\n"
376 " -F, --flow-format=FORMAT force particular flow format\n"
377 " -P, --packet-in-format=FRMT force particular packet in format\n"
378 " -m, --more be more verbose printing OpenFlow\n"
379 " --timestamp (monitor, snoop) print timestamps\n"
380 " -t, --timeout=SECS give up after SECS seconds\n"
381 " --sort[=field] sort in ascending order\n"
382 " --rsort[=field] sort in descending order\n"
383 " --unixctl=SOCKET set control socket name\n"
384 " -h, --help display this help message\n"
385 " -V, --version display version information\n");
386 exit(EXIT_SUCCESS);
387 }
388
389 static void
390 ofctl_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
391 const char *argv[] OVS_UNUSED, void *exiting_)
392 {
393 bool *exiting = exiting_;
394 *exiting = true;
395 unixctl_command_reply(conn, NULL);
396 }
397
398 static void run(int retval, const char *message, ...)
399 OVS_PRINTF_FORMAT(2, 3);
400
401 static void
402 run(int retval, const char *message, ...)
403 {
404 if (retval) {
405 va_list args;
406
407 va_start(args, message);
408 ovs_fatal_valist(retval, message, args);
409 }
410 }
411 \f
412 /* Generic commands. */
413
414 static int
415 open_vconn_socket(const char *name, struct vconn **vconnp)
416 {
417 char *vconn_name = xasprintf("unix:%s", name);
418 int error;
419
420 error = vconn_open(vconn_name, get_allowed_ofp_versions(), DSCP_DEFAULT,
421 vconnp);
422 if (error && error != ENOENT) {
423 ovs_fatal(0, "%s: failed to open socket (%s)", name,
424 ovs_strerror(error));
425 }
426 free(vconn_name);
427
428 return error;
429 }
430
431 enum open_target { MGMT, SNOOP };
432
433 static enum ofputil_protocol
434 open_vconn__(const char *name, enum open_target target,
435 struct vconn **vconnp)
436 {
437 const char *suffix = target == MGMT ? "mgmt" : "snoop";
438 char *datapath_name, *datapath_type, *socket_name;
439 enum ofputil_protocol protocol;
440 char *bridge_path;
441 int ofp_version;
442 int error;
443
444 bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, suffix);
445
446 ofproto_parse_name(name, &datapath_name, &datapath_type);
447 socket_name = xasprintf("%s/%s.%s", ovs_rundir(), datapath_name, suffix);
448 free(datapath_name);
449 free(datapath_type);
450
451 if (strchr(name, ':')) {
452 run(vconn_open(name, get_allowed_ofp_versions(), DSCP_DEFAULT, vconnp),
453 "connecting to %s", name);
454 } else if (!open_vconn_socket(name, vconnp)) {
455 /* Fall Through. */
456 } else if (!open_vconn_socket(bridge_path, vconnp)) {
457 /* Fall Through. */
458 } else if (!open_vconn_socket(socket_name, vconnp)) {
459 /* Fall Through. */
460 } else {
461 ovs_fatal(0, "%s is not a bridge or a socket", name);
462 }
463
464 if (target == SNOOP) {
465 vconn_set_recv_any_version(*vconnp);
466 }
467
468 free(bridge_path);
469 free(socket_name);
470
471 VLOG_DBG("connecting to %s", vconn_get_name(*vconnp));
472 error = vconn_connect_block(*vconnp);
473 if (error) {
474 ovs_fatal(0, "%s: failed to connect to socket (%s)", name,
475 ovs_strerror(error));
476 }
477
478 ofp_version = vconn_get_version(*vconnp);
479 protocol = ofputil_protocol_from_ofp_version(ofp_version);
480 if (!protocol) {
481 ovs_fatal(0, "%s: unsupported OpenFlow version 0x%02x",
482 name, ofp_version);
483 }
484 return protocol;
485 }
486
487 static enum ofputil_protocol
488 open_vconn(const char *name, struct vconn **vconnp)
489 {
490 return open_vconn__(name, MGMT, vconnp);
491 }
492
493 static void
494 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
495 {
496 ofpmsg_update_length(buffer);
497 run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
498 }
499
500 static void
501 dump_transaction(struct vconn *vconn, struct ofpbuf *request)
502 {
503 struct ofpbuf *reply;
504
505 ofpmsg_update_length(request);
506 run(vconn_transact(vconn, request, &reply), "talking to %s",
507 vconn_get_name(vconn));
508 ofp_print(stdout, reply->data, reply->size, verbosity + 1);
509 ofpbuf_delete(reply);
510 }
511
512 static void
513 dump_trivial_transaction(const char *vconn_name, enum ofpraw raw)
514 {
515 struct ofpbuf *request;
516 struct vconn *vconn;
517
518 open_vconn(vconn_name, &vconn);
519 request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
520 dump_transaction(vconn, request);
521 vconn_close(vconn);
522 }
523
524 static void
525 dump_stats_transaction(struct vconn *vconn, struct ofpbuf *request)
526 {
527 const struct ofp_header *request_oh = request->data;
528 ovs_be32 send_xid = request_oh->xid;
529 enum ofpraw request_raw;
530 enum ofpraw reply_raw;
531 bool done = false;
532
533 ofpraw_decode_partial(&request_raw, request->data, request->size);
534 reply_raw = ofpraw_stats_request_to_reply(request_raw,
535 request_oh->version);
536
537 send_openflow_buffer(vconn, request);
538 while (!done) {
539 ovs_be32 recv_xid;
540 struct ofpbuf *reply;
541
542 run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
543 recv_xid = ((struct ofp_header *) reply->data)->xid;
544 if (send_xid == recv_xid) {
545 enum ofpraw raw;
546
547 ofp_print(stdout, reply->data, reply->size, verbosity + 1);
548
549 ofpraw_decode(&raw, reply->data);
550 if (ofptype_from_ofpraw(raw) == OFPTYPE_ERROR) {
551 done = true;
552 } else if (raw == reply_raw) {
553 done = !ofpmp_more(reply->data);
554 } else {
555 ovs_fatal(0, "received bad reply: %s",
556 ofp_to_string(reply->data, reply->size,
557 verbosity + 1));
558 }
559 } else {
560 VLOG_DBG("received reply with xid %08"PRIx32" "
561 "!= expected %08"PRIx32, recv_xid, send_xid);
562 }
563 ofpbuf_delete(reply);
564 }
565 }
566
567 static void
568 dump_trivial_stats_transaction(const char *vconn_name, enum ofpraw raw)
569 {
570 struct ofpbuf *request;
571 struct vconn *vconn;
572
573 open_vconn(vconn_name, &vconn);
574 request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
575 dump_stats_transaction(vconn, request);
576 vconn_close(vconn);
577 }
578
579 /* Sends all of the 'requests', which should be requests that only have replies
580 * if an error occurs, and waits for them to succeed or fail. If an error does
581 * occur, prints it and exits with an error.
582 *
583 * Destroys all of the 'requests'. */
584 static void
585 transact_multiple_noreply(struct vconn *vconn, struct ovs_list *requests)
586 {
587 struct ofpbuf *request, *reply;
588
589 LIST_FOR_EACH (request, list_node, requests) {
590 ofpmsg_update_length(request);
591 }
592
593 run(vconn_transact_multiple_noreply(vconn, requests, &reply),
594 "talking to %s", vconn_get_name(vconn));
595 if (reply) {
596 ofp_print(stderr, reply->data, reply->size, verbosity + 2);
597 exit(1);
598 }
599 ofpbuf_delete(reply);
600 }
601
602 /* Sends 'request', which should be a request that only has a reply if an error
603 * occurs, and waits for it to succeed or fail. If an error does occur, prints
604 * it and exits with an error.
605 *
606 * Destroys 'request'. */
607 static void
608 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
609 {
610 struct ovs_list requests;
611
612 list_init(&requests);
613 list_push_back(&requests, &request->list_node);
614 transact_multiple_noreply(vconn, &requests);
615 }
616
617 static void
618 fetch_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
619 {
620 struct ofp_switch_config *config;
621 struct ofpbuf *request;
622 struct ofpbuf *reply;
623 enum ofptype type;
624
625 request = ofpraw_alloc(OFPRAW_OFPT_GET_CONFIG_REQUEST,
626 vconn_get_version(vconn), 0);
627 run(vconn_transact(vconn, request, &reply),
628 "talking to %s", vconn_get_name(vconn));
629
630 if (ofptype_pull(&type, reply) || type != OFPTYPE_GET_CONFIG_REPLY) {
631 ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
632 }
633
634 config = ofpbuf_pull(reply, sizeof *config);
635 *config_ = *config;
636
637 ofpbuf_delete(reply);
638 }
639
640 static void
641 set_switch_config(struct vconn *vconn, const struct ofp_switch_config *config)
642 {
643 struct ofpbuf *request;
644
645 request = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG, vconn_get_version(vconn), 0);
646 ofpbuf_put(request, config, sizeof *config);
647
648 transact_noreply(vconn, request);
649 }
650
651 static void
652 ofctl_show(int argc OVS_UNUSED, char *argv[])
653 {
654 const char *vconn_name = argv[1];
655 enum ofp_version version;
656 struct vconn *vconn;
657 struct ofpbuf *request;
658 struct ofpbuf *reply;
659 bool has_ports;
660
661 open_vconn(vconn_name, &vconn);
662 version = vconn_get_version(vconn);
663 request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST, version, 0);
664 run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
665
666 has_ports = ofputil_switch_features_has_ports(reply);
667 ofp_print(stdout, reply->data, reply->size, verbosity + 1);
668 ofpbuf_delete(reply);
669
670 if (!has_ports) {
671 request = ofputil_encode_port_desc_stats_request(version, OFPP_ANY);
672 dump_stats_transaction(vconn, request);
673 }
674 dump_trivial_transaction(vconn_name, OFPRAW_OFPT_GET_CONFIG_REQUEST);
675 vconn_close(vconn);
676 }
677
678 static void
679 ofctl_dump_desc(int argc OVS_UNUSED, char *argv[])
680 {
681 dump_trivial_stats_transaction(argv[1], OFPRAW_OFPST_DESC_REQUEST);
682 }
683
684 static void
685 ofctl_dump_tables(int argc OVS_UNUSED, char *argv[])
686 {
687 dump_trivial_stats_transaction(argv[1], OFPRAW_OFPST_TABLE_REQUEST);
688 }
689
690 static void
691 ofctl_dump_table_features(int argc OVS_UNUSED, char *argv[])
692 {
693 struct ofpbuf *request;
694 struct vconn *vconn;
695
696 open_vconn(argv[1], &vconn);
697 request = ofputil_encode_table_features_request(vconn_get_version(vconn));
698 if (request) {
699 dump_stats_transaction(vconn, request);
700 }
701
702 vconn_close(vconn);
703 }
704
705 static bool fetch_port_by_stats(struct vconn *,
706 const char *port_name, ofp_port_t port_no,
707 struct ofputil_phy_port *);
708
709 /* Uses OFPT_FEATURES_REQUEST to attempt to fetch information about the port
710 * named 'port_name' or numbered 'port_no' into '*pp'. Returns true if
711 * successful, false on failure.
712 *
713 * This is only appropriate for OpenFlow 1.0, 1.1, and 1.2, which include a
714 * list of ports in OFPT_FEATURES_REPLY. */
715 static bool
716 fetch_port_by_features(struct vconn *vconn,
717 const char *port_name, ofp_port_t port_no,
718 struct ofputil_phy_port *pp)
719 {
720 struct ofputil_switch_features features;
721 const struct ofp_header *oh;
722 struct ofpbuf *request, *reply;
723 enum ofperr error;
724 enum ofptype type;
725 struct ofpbuf b;
726 bool found = false;
727
728 /* Fetch the switch's ofp_switch_features. */
729 request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST,
730 vconn_get_version(vconn), 0);
731 run(vconn_transact(vconn, request, &reply),
732 "talking to %s", vconn_get_name(vconn));
733
734 oh = reply->data;
735 if (ofptype_decode(&type, reply->data)
736 || type != OFPTYPE_FEATURES_REPLY) {
737 ovs_fatal(0, "%s: received bad features reply", vconn_get_name(vconn));
738 }
739 if (!ofputil_switch_features_has_ports(reply)) {
740 /* The switch features reply does not contain a complete list of ports.
741 * Probably, there are more ports than will fit into a single 64 kB
742 * OpenFlow message. Use OFPST_PORT_DESC to get a complete list of
743 * ports. */
744 ofpbuf_delete(reply);
745 return fetch_port_by_stats(vconn, port_name, port_no, pp);
746 }
747
748 error = ofputil_decode_switch_features(oh, &features, &b);
749 if (error) {
750 ovs_fatal(0, "%s: failed to decode features reply (%s)",
751 vconn_get_name(vconn), ofperr_to_string(error));
752 }
753
754 while (!ofputil_pull_phy_port(oh->version, &b, pp)) {
755 if (port_no != OFPP_NONE
756 ? port_no == pp->port_no
757 : !strcmp(pp->name, port_name)) {
758 found = true;
759 break;
760 }
761 }
762 ofpbuf_delete(reply);
763 return found;
764 }
765
766 /* Uses a OFPST_PORT_DESC request to attempt to fetch information about the
767 * port named 'port_name' or numbered 'port_no' into '*pp'. Returns true if
768 * successful, false on failure.
769 *
770 * This is most appropriate for OpenFlow 1.3 and later. Open vSwitch 1.7 and
771 * later also implements OFPST_PORT_DESC, as an extension, for OpenFlow 1.0,
772 * 1.1, and 1.2, so this can be used as a fallback in those versions when there
773 * are too many ports than fit in an OFPT_FEATURES_REPLY. */
774 static bool
775 fetch_port_by_stats(struct vconn *vconn,
776 const char *port_name, ofp_port_t port_no,
777 struct ofputil_phy_port *pp)
778 {
779 struct ofpbuf *request;
780 ovs_be32 send_xid;
781 bool done = false;
782 bool found = false;
783
784 request = ofputil_encode_port_desc_stats_request(vconn_get_version(vconn),
785 port_no);
786 send_xid = ((struct ofp_header *) request->data)->xid;
787
788 send_openflow_buffer(vconn, request);
789 while (!done) {
790 ovs_be32 recv_xid;
791 struct ofpbuf *reply;
792
793 run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
794 recv_xid = ((struct ofp_header *) reply->data)->xid;
795 if (send_xid == recv_xid) {
796 struct ofp_header *oh = reply->data;
797 enum ofptype type;
798 struct ofpbuf b;
799 uint16_t flags;
800
801 ofpbuf_use_const(&b, oh, ntohs(oh->length));
802 if (ofptype_pull(&type, &b)
803 || type != OFPTYPE_PORT_DESC_STATS_REPLY) {
804 ovs_fatal(0, "received bad reply: %s",
805 ofp_to_string(reply->data, reply->size,
806 verbosity + 1));
807 }
808
809 flags = ofpmp_flags(oh);
810 done = !(flags & OFPSF_REPLY_MORE);
811
812 if (found) {
813 /* We've already found the port, but we need to drain
814 * the queue of any other replies for this request. */
815 continue;
816 }
817
818 while (!ofputil_pull_phy_port(oh->version, &b, pp)) {
819 if (port_no != OFPP_NONE ? port_no == pp->port_no
820 : !strcmp(pp->name, port_name)) {
821 found = true;
822 break;
823 }
824 }
825 } else {
826 VLOG_DBG("received reply with xid %08"PRIx32" "
827 "!= expected %08"PRIx32, recv_xid, send_xid);
828 }
829 ofpbuf_delete(reply);
830 }
831
832 return found;
833 }
834
835 static bool
836 str_to_ofp(const char *s, ofp_port_t *ofp_port)
837 {
838 bool ret;
839 uint32_t port_;
840
841 ret = str_to_uint(s, 10, &port_);
842 *ofp_port = u16_to_ofp(port_);
843 return ret;
844 }
845
846 /* Opens a connection to 'vconn_name', fetches the port structure for
847 * 'port_name' (which may be a port name or number), and copies it into
848 * '*pp'. */
849 static void
850 fetch_ofputil_phy_port(const char *vconn_name, const char *port_name,
851 struct ofputil_phy_port *pp)
852 {
853 struct vconn *vconn;
854 ofp_port_t port_no;
855 bool found;
856
857 /* Try to interpret the argument as a port number. */
858 if (!str_to_ofp(port_name, &port_no)) {
859 port_no = OFPP_NONE;
860 }
861
862 /* OpenFlow 1.0, 1.1, and 1.2 put the list of ports in the
863 * OFPT_FEATURES_REPLY message. OpenFlow 1.3 and later versions put it
864 * into the OFPST_PORT_DESC reply. Try it the correct way. */
865 open_vconn(vconn_name, &vconn);
866 found = (vconn_get_version(vconn) < OFP13_VERSION
867 ? fetch_port_by_features(vconn, port_name, port_no, pp)
868 : fetch_port_by_stats(vconn, port_name, port_no, pp));
869 vconn_close(vconn);
870
871 if (!found) {
872 ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
873 }
874 }
875
876 /* Returns the port number corresponding to 'port_name' (which may be a port
877 * name or number) within the switch 'vconn_name'. */
878 static ofp_port_t
879 str_to_port_no(const char *vconn_name, const char *port_name)
880 {
881 ofp_port_t port_no;
882
883 if (ofputil_port_from_string(port_name, &port_no)) {
884 return port_no;
885 } else {
886 struct ofputil_phy_port pp;
887
888 fetch_ofputil_phy_port(vconn_name, port_name, &pp);
889 return pp.port_no;
890 }
891 }
892
893 static bool
894 try_set_protocol(struct vconn *vconn, enum ofputil_protocol want,
895 enum ofputil_protocol *cur)
896 {
897 for (;;) {
898 struct ofpbuf *request, *reply;
899 enum ofputil_protocol next;
900
901 request = ofputil_encode_set_protocol(*cur, want, &next);
902 if (!request) {
903 return *cur == want;
904 }
905
906 run(vconn_transact_noreply(vconn, request, &reply),
907 "talking to %s", vconn_get_name(vconn));
908 if (reply) {
909 char *s = ofp_to_string(reply->data, reply->size, 2);
910 VLOG_DBG("%s: failed to set protocol, switch replied: %s",
911 vconn_get_name(vconn), s);
912 free(s);
913 ofpbuf_delete(reply);
914 return false;
915 }
916
917 *cur = next;
918 }
919 }
920
921 static enum ofputil_protocol
922 set_protocol_for_flow_dump(struct vconn *vconn,
923 enum ofputil_protocol cur_protocol,
924 enum ofputil_protocol usable_protocols)
925 {
926 char *usable_s;
927 int i;
928
929 for (i = 0; i < ofputil_n_flow_dump_protocols; i++) {
930 enum ofputil_protocol f = ofputil_flow_dump_protocols[i];
931 if (f & usable_protocols & allowed_protocols
932 && try_set_protocol(vconn, f, &cur_protocol)) {
933 return f;
934 }
935 }
936
937 usable_s = ofputil_protocols_to_string(usable_protocols);
938 if (usable_protocols & allowed_protocols) {
939 ovs_fatal(0, "switch does not support any of the usable flow "
940 "formats (%s)", usable_s);
941 } else {
942 char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
943 ovs_fatal(0, "none of the usable flow formats (%s) is among the "
944 "allowed flow formats (%s)", usable_s, allowed_s);
945 }
946 }
947
948 static struct vconn *
949 prepare_dump_flows(int argc, char *argv[], bool aggregate,
950 struct ofpbuf **requestp)
951 {
952 enum ofputil_protocol usable_protocols, protocol;
953 struct ofputil_flow_stats_request fsr;
954 struct vconn *vconn;
955 char *error;
956
957 error = parse_ofp_flow_stats_request_str(&fsr, aggregate,
958 argc > 2 ? argv[2] : "",
959 &usable_protocols);
960 if (error) {
961 ovs_fatal(0, "%s", error);
962 }
963
964 protocol = open_vconn(argv[1], &vconn);
965 protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
966 *requestp = ofputil_encode_flow_stats_request(&fsr, protocol);
967 return vconn;
968 }
969
970 static void
971 ofctl_dump_flows__(int argc, char *argv[], bool aggregate)
972 {
973 struct ofpbuf *request;
974 struct vconn *vconn;
975
976 vconn = prepare_dump_flows(argc, argv, aggregate, &request);
977 dump_stats_transaction(vconn, request);
978 vconn_close(vconn);
979 }
980
981 static int
982 compare_flows(const void *afs_, const void *bfs_)
983 {
984 const struct ofputil_flow_stats *afs = afs_;
985 const struct ofputil_flow_stats *bfs = bfs_;
986 const struct match *a = &afs->match;
987 const struct match *b = &bfs->match;
988 const struct sort_criterion *sc;
989
990 for (sc = criteria; sc < &criteria[n_criteria]; sc++) {
991 const struct mf_field *f = sc->field;
992 int ret;
993
994 if (!f) {
995 int a_pri = afs->priority;
996 int b_pri = bfs->priority;
997 ret = a_pri < b_pri ? -1 : a_pri > b_pri;
998 } else {
999 bool ina, inb;
1000
1001 ina = mf_are_prereqs_ok(f, &a->flow) && !mf_is_all_wild(f, &a->wc);
1002 inb = mf_are_prereqs_ok(f, &b->flow) && !mf_is_all_wild(f, &b->wc);
1003 if (ina != inb) {
1004 /* Skip the test for sc->order, so that missing fields always
1005 * sort to the end whether we're sorting in ascending or
1006 * descending order. */
1007 return ina ? -1 : 1;
1008 } else {
1009 union mf_value aval, bval;
1010
1011 mf_get_value(f, &a->flow, &aval);
1012 mf_get_value(f, &b->flow, &bval);
1013 ret = memcmp(&aval, &bval, f->n_bytes);
1014 }
1015 }
1016
1017 if (ret) {
1018 return sc->order == SORT_ASC ? ret : -ret;
1019 }
1020 }
1021
1022 return 0;
1023 }
1024
1025 static void
1026 ofctl_dump_flows(int argc, char *argv[])
1027 {
1028 if (!n_criteria) {
1029 ofctl_dump_flows__(argc, argv, false);
1030 return;
1031 } else {
1032 struct ofputil_flow_stats *fses;
1033 size_t n_fses, allocated_fses;
1034 struct ofpbuf *request;
1035 struct ofpbuf ofpacts;
1036 struct ofpbuf *reply;
1037 struct vconn *vconn;
1038 ovs_be32 send_xid;
1039 struct ds s;
1040 size_t i;
1041
1042 vconn = prepare_dump_flows(argc, argv, false, &request);
1043 send_xid = ((struct ofp_header *) request->data)->xid;
1044 send_openflow_buffer(vconn, request);
1045
1046 fses = NULL;
1047 n_fses = allocated_fses = 0;
1048 reply = NULL;
1049 ofpbuf_init(&ofpacts, 0);
1050 for (;;) {
1051 struct ofputil_flow_stats *fs;
1052
1053 if (n_fses >= allocated_fses) {
1054 fses = x2nrealloc(fses, &allocated_fses, sizeof *fses);
1055 }
1056
1057 fs = &fses[n_fses];
1058 if (!recv_flow_stats_reply(vconn, send_xid, &reply, fs,
1059 &ofpacts)) {
1060 break;
1061 }
1062 fs->ofpacts = xmemdup(fs->ofpacts, fs->ofpacts_len);
1063 n_fses++;
1064 }
1065 ofpbuf_uninit(&ofpacts);
1066
1067 qsort(fses, n_fses, sizeof *fses, compare_flows);
1068
1069 ds_init(&s);
1070 for (i = 0; i < n_fses; i++) {
1071 ds_clear(&s);
1072 ofp_print_flow_stats(&s, &fses[i]);
1073 puts(ds_cstr(&s));
1074 }
1075 ds_destroy(&s);
1076
1077 for (i = 0; i < n_fses; i++) {
1078 free(CONST_CAST(struct ofpact *, fses[i].ofpacts));
1079 }
1080 free(fses);
1081
1082 vconn_close(vconn);
1083 }
1084 }
1085
1086 static void
1087 ofctl_dump_aggregate(int argc, char *argv[])
1088 {
1089 ofctl_dump_flows__(argc, argv, true);
1090 }
1091
1092 static void
1093 ofctl_queue_stats(int argc, char *argv[])
1094 {
1095 struct ofpbuf *request;
1096 struct vconn *vconn;
1097 struct ofputil_queue_stats_request oqs;
1098
1099 open_vconn(argv[1], &vconn);
1100
1101 if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
1102 oqs.port_no = str_to_port_no(argv[1], argv[2]);
1103 } else {
1104 oqs.port_no = OFPP_ANY;
1105 }
1106 if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
1107 oqs.queue_id = atoi(argv[3]);
1108 } else {
1109 oqs.queue_id = OFPQ_ALL;
1110 }
1111
1112 request = ofputil_encode_queue_stats_request(vconn_get_version(vconn), &oqs);
1113 dump_stats_transaction(vconn, request);
1114 vconn_close(vconn);
1115 }
1116
1117 static void
1118 ofctl_queue_get_config(int argc OVS_UNUSED, char *argv[])
1119 {
1120 const char *vconn_name = argv[1];
1121 const char *port_name = argv[2];
1122 enum ofputil_protocol protocol;
1123 enum ofp_version version;
1124 struct ofpbuf *request;
1125 struct vconn *vconn;
1126 ofp_port_t port;
1127
1128 port = str_to_port_no(vconn_name, port_name);
1129
1130 protocol = open_vconn(vconn_name, &vconn);
1131 version = ofputil_protocol_to_ofp_version(protocol);
1132 request = ofputil_encode_queue_get_config_request(version, port);
1133 dump_transaction(vconn, request);
1134 vconn_close(vconn);
1135 }
1136
1137 static enum ofputil_protocol
1138 open_vconn_for_flow_mod(const char *remote, struct vconn **vconnp,
1139 enum ofputil_protocol usable_protocols)
1140 {
1141 enum ofputil_protocol cur_protocol;
1142 char *usable_s;
1143 int i;
1144
1145 if (!(usable_protocols & allowed_protocols)) {
1146 char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
1147 usable_s = ofputil_protocols_to_string(usable_protocols);
1148 ovs_fatal(0, "none of the usable flow formats (%s) is among the "
1149 "allowed flow formats (%s)", usable_s, allowed_s);
1150 }
1151
1152 /* If the initial flow format is allowed and usable, keep it. */
1153 cur_protocol = open_vconn(remote, vconnp);
1154 if (usable_protocols & allowed_protocols & cur_protocol) {
1155 return cur_protocol;
1156 }
1157
1158 /* Otherwise try each flow format in turn. */
1159 for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1160 enum ofputil_protocol f = 1 << i;
1161
1162 if (f != cur_protocol
1163 && f & usable_protocols & allowed_protocols
1164 && try_set_protocol(*vconnp, f, &cur_protocol)) {
1165 return f;
1166 }
1167 }
1168
1169 usable_s = ofputil_protocols_to_string(usable_protocols);
1170 ovs_fatal(0, "switch does not support any of the usable flow "
1171 "formats (%s)", usable_s);
1172 }
1173
1174 static void
1175 ofctl_flow_mod__(const char *remote, struct ofputil_flow_mod *fms,
1176 size_t n_fms, enum ofputil_protocol usable_protocols)
1177 {
1178 enum ofputil_protocol protocol;
1179 struct vconn *vconn;
1180 size_t i;
1181
1182 protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
1183
1184 for (i = 0; i < n_fms; i++) {
1185 struct ofputil_flow_mod *fm = &fms[i];
1186
1187 transact_noreply(vconn, ofputil_encode_flow_mod(fm, protocol));
1188 free(CONST_CAST(struct ofpact *, fm->ofpacts));
1189 }
1190 vconn_close(vconn);
1191 }
1192
1193 static void
1194 ofctl_flow_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
1195 {
1196 enum ofputil_protocol usable_protocols;
1197 struct ofputil_flow_mod *fms = NULL;
1198 size_t n_fms = 0;
1199 char *error;
1200
1201 error = parse_ofp_flow_mod_file(argv[2], command, &fms, &n_fms,
1202 &usable_protocols);
1203 if (error) {
1204 ovs_fatal(0, "%s", error);
1205 }
1206 ofctl_flow_mod__(argv[1], fms, n_fms, usable_protocols);
1207 free(fms);
1208 }
1209
1210 static void
1211 ofctl_flow_mod(int argc, char *argv[], uint16_t command)
1212 {
1213 if (argc > 2 && !strcmp(argv[2], "-")) {
1214 ofctl_flow_mod_file(argc, argv, command);
1215 } else {
1216 struct ofputil_flow_mod fm;
1217 char *error;
1218 enum ofputil_protocol usable_protocols;
1219
1220 error = parse_ofp_flow_mod_str(&fm, argc > 2 ? argv[2] : "", command,
1221 &usable_protocols);
1222 if (error) {
1223 ovs_fatal(0, "%s", error);
1224 }
1225 ofctl_flow_mod__(argv[1], &fm, 1, usable_protocols);
1226 }
1227 }
1228
1229 static void
1230 ofctl_add_flow(int argc, char *argv[])
1231 {
1232 ofctl_flow_mod(argc, argv, OFPFC_ADD);
1233 }
1234
1235 static void
1236 ofctl_add_flows(int argc, char *argv[])
1237 {
1238 ofctl_flow_mod_file(argc, argv, OFPFC_ADD);
1239 }
1240
1241 static void
1242 ofctl_mod_flows(int argc, char *argv[])
1243 {
1244 ofctl_flow_mod(argc, argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
1245 }
1246
1247 static void
1248 ofctl_del_flows(int argc, char *argv[])
1249 {
1250 ofctl_flow_mod(argc, argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
1251 }
1252
1253 static void
1254 set_packet_in_format(struct vconn *vconn,
1255 enum nx_packet_in_format packet_in_format)
1256 {
1257 struct ofpbuf *spif;
1258
1259 spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1260 packet_in_format);
1261 transact_noreply(vconn, spif);
1262 VLOG_DBG("%s: using user-specified packet in format %s",
1263 vconn_get_name(vconn),
1264 ofputil_packet_in_format_to_string(packet_in_format));
1265 }
1266
1267 static int
1268 monitor_set_invalid_ttl_to_controller(struct vconn *vconn)
1269 {
1270 struct ofp_switch_config config;
1271 enum ofp_config_flags flags;
1272
1273 fetch_switch_config(vconn, &config);
1274 flags = ntohs(config.flags);
1275 if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
1276 /* Set the invalid ttl config. */
1277 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
1278
1279 config.flags = htons(flags);
1280 set_switch_config(vconn, &config);
1281
1282 /* Then retrieve the configuration to see if it really took. OpenFlow
1283 * doesn't define error reporting for bad modes, so this is all we can
1284 * do. */
1285 fetch_switch_config(vconn, &config);
1286 flags = ntohs(config.flags);
1287 if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
1288 ovs_fatal(0, "setting invalid_ttl_to_controller failed (this "
1289 "switch probably doesn't support mode)");
1290 return -EOPNOTSUPP;
1291 }
1292 }
1293 return 0;
1294 }
1295
1296 /* Converts hex digits in 'hex' to an OpenFlow message in '*msgp'. The
1297 * caller must free '*msgp'. On success, returns NULL. On failure, returns
1298 * an error message and stores NULL in '*msgp'. */
1299 static const char *
1300 openflow_from_hex(const char *hex, struct ofpbuf **msgp)
1301 {
1302 struct ofp_header *oh;
1303 struct ofpbuf *msg;
1304
1305 msg = ofpbuf_new(strlen(hex) / 2);
1306 *msgp = NULL;
1307
1308 if (ofpbuf_put_hex(msg, hex, NULL)[0] != '\0') {
1309 ofpbuf_delete(msg);
1310 return "Trailing garbage in hex data";
1311 }
1312
1313 if (msg->size < sizeof(struct ofp_header)) {
1314 ofpbuf_delete(msg);
1315 return "Message too short for OpenFlow";
1316 }
1317
1318 oh = msg->data;
1319 if (msg->size != ntohs(oh->length)) {
1320 ofpbuf_delete(msg);
1321 return "Message size does not match length in OpenFlow header";
1322 }
1323
1324 *msgp = msg;
1325 return NULL;
1326 }
1327
1328 static void
1329 ofctl_send(struct unixctl_conn *conn, int argc,
1330 const char *argv[], void *vconn_)
1331 {
1332 struct vconn *vconn = vconn_;
1333 struct ds reply;
1334 bool ok;
1335 int i;
1336
1337 ok = true;
1338 ds_init(&reply);
1339 for (i = 1; i < argc; i++) {
1340 const char *error_msg;
1341 struct ofpbuf *msg;
1342 int error;
1343
1344 error_msg = openflow_from_hex(argv[i], &msg);
1345 if (error_msg) {
1346 ds_put_format(&reply, "%s\n", error_msg);
1347 ok = false;
1348 continue;
1349 }
1350
1351 fprintf(stderr, "send: ");
1352 ofp_print(stderr, msg->data, msg->size, verbosity);
1353
1354 error = vconn_send_block(vconn, msg);
1355 if (error) {
1356 ofpbuf_delete(msg);
1357 ds_put_format(&reply, "%s\n", ovs_strerror(error));
1358 ok = false;
1359 } else {
1360 ds_put_cstr(&reply, "sent\n");
1361 }
1362 }
1363
1364 if (ok) {
1365 unixctl_command_reply(conn, ds_cstr(&reply));
1366 } else {
1367 unixctl_command_reply_error(conn, ds_cstr(&reply));
1368 }
1369 ds_destroy(&reply);
1370 }
1371
1372 struct barrier_aux {
1373 struct vconn *vconn; /* OpenFlow connection for sending barrier. */
1374 struct unixctl_conn *conn; /* Connection waiting for barrier response. */
1375 };
1376
1377 static void
1378 ofctl_barrier(struct unixctl_conn *conn, int argc OVS_UNUSED,
1379 const char *argv[] OVS_UNUSED, void *aux_)
1380 {
1381 struct barrier_aux *aux = aux_;
1382 struct ofpbuf *msg;
1383 int error;
1384
1385 if (aux->conn) {
1386 unixctl_command_reply_error(conn, "already waiting for barrier reply");
1387 return;
1388 }
1389
1390 msg = ofputil_encode_barrier_request(vconn_get_version(aux->vconn));
1391 error = vconn_send_block(aux->vconn, msg);
1392 if (error) {
1393 ofpbuf_delete(msg);
1394 unixctl_command_reply_error(conn, ovs_strerror(error));
1395 } else {
1396 aux->conn = conn;
1397 }
1398 }
1399
1400 static void
1401 ofctl_set_output_file(struct unixctl_conn *conn, int argc OVS_UNUSED,
1402 const char *argv[], void *aux OVS_UNUSED)
1403 {
1404 int fd;
1405
1406 fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
1407 if (fd < 0) {
1408 unixctl_command_reply_error(conn, ovs_strerror(errno));
1409 return;
1410 }
1411
1412 fflush(stderr);
1413 dup2(fd, STDERR_FILENO);
1414 close(fd);
1415 unixctl_command_reply(conn, NULL);
1416 }
1417
1418 static void
1419 ofctl_block(struct unixctl_conn *conn, int argc OVS_UNUSED,
1420 const char *argv[] OVS_UNUSED, void *blocked_)
1421 {
1422 bool *blocked = blocked_;
1423
1424 if (!*blocked) {
1425 *blocked = true;
1426 unixctl_command_reply(conn, NULL);
1427 } else {
1428 unixctl_command_reply(conn, "already blocking");
1429 }
1430 }
1431
1432 static void
1433 ofctl_unblock(struct unixctl_conn *conn, int argc OVS_UNUSED,
1434 const char *argv[] OVS_UNUSED, void *blocked_)
1435 {
1436 bool *blocked = blocked_;
1437
1438 if (*blocked) {
1439 *blocked = false;
1440 unixctl_command_reply(conn, NULL);
1441 } else {
1442 unixctl_command_reply(conn, "already unblocked");
1443 }
1444 }
1445
1446 /* Prints to stdout all of the messages received on 'vconn'.
1447 *
1448 * Iff 'reply_to_echo_requests' is true, sends a reply to any echo request
1449 * received on 'vconn'. */
1450 static void
1451 monitor_vconn(struct vconn *vconn, bool reply_to_echo_requests)
1452 {
1453 struct barrier_aux barrier_aux = { vconn, NULL };
1454 struct unixctl_server *server;
1455 bool exiting = false;
1456 bool blocked = false;
1457 int error;
1458
1459 daemon_save_fd(STDERR_FILENO);
1460 daemonize_start();
1461 error = unixctl_server_create(unixctl_path, &server);
1462 if (error) {
1463 ovs_fatal(error, "failed to create unixctl server");
1464 }
1465 unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
1466 unixctl_command_register("ofctl/send", "OFMSG...", 1, INT_MAX,
1467 ofctl_send, vconn);
1468 unixctl_command_register("ofctl/barrier", "", 0, 0,
1469 ofctl_barrier, &barrier_aux);
1470 unixctl_command_register("ofctl/set-output-file", "FILE", 1, 1,
1471 ofctl_set_output_file, NULL);
1472
1473 unixctl_command_register("ofctl/block", "", 0, 0, ofctl_block, &blocked);
1474 unixctl_command_register("ofctl/unblock", "", 0, 0, ofctl_unblock,
1475 &blocked);
1476
1477 daemonize_complete();
1478
1479 for (;;) {
1480 struct ofpbuf *b;
1481 int retval;
1482
1483 unixctl_server_run(server);
1484
1485 while (!blocked) {
1486 enum ofptype type;
1487
1488 retval = vconn_recv(vconn, &b);
1489 if (retval == EAGAIN) {
1490 break;
1491 }
1492 run(retval, "vconn_recv");
1493
1494 if (timestamp) {
1495 char *s = xastrftime_msec("%Y-%m-%d %H:%M:%S.###: ",
1496 time_wall_msec(), true);
1497 fputs(s, stderr);
1498 free(s);
1499 }
1500
1501 ofptype_decode(&type, b->data);
1502 ofp_print(stderr, b->data, b->size, verbosity + 2);
1503 fflush(stderr);
1504
1505 switch ((int) type) {
1506 case OFPTYPE_BARRIER_REPLY:
1507 if (barrier_aux.conn) {
1508 unixctl_command_reply(barrier_aux.conn, NULL);
1509 barrier_aux.conn = NULL;
1510 }
1511 break;
1512
1513 case OFPTYPE_ECHO_REQUEST:
1514 if (reply_to_echo_requests) {
1515 struct ofpbuf *reply;
1516
1517 reply = make_echo_reply(b->data);
1518 retval = vconn_send_block(vconn, reply);
1519 if (retval) {
1520 ovs_fatal(retval, "failed to send echo reply");
1521 }
1522 }
1523 break;
1524 }
1525 ofpbuf_delete(b);
1526 }
1527
1528 if (exiting) {
1529 break;
1530 }
1531
1532 vconn_run(vconn);
1533 vconn_run_wait(vconn);
1534 if (!blocked) {
1535 vconn_recv_wait(vconn);
1536 }
1537 unixctl_server_wait(server);
1538 poll_block();
1539 }
1540 vconn_close(vconn);
1541 unixctl_server_destroy(server);
1542 }
1543
1544 static void
1545 ofctl_monitor(int argc, char *argv[])
1546 {
1547 struct vconn *vconn;
1548 int i;
1549 enum ofputil_protocol usable_protocols;
1550
1551 open_vconn(argv[1], &vconn);
1552 for (i = 2; i < argc; i++) {
1553 const char *arg = argv[i];
1554
1555 if (isdigit((unsigned char) *arg)) {
1556 struct ofp_switch_config config;
1557
1558 fetch_switch_config(vconn, &config);
1559 config.miss_send_len = htons(atoi(arg));
1560 set_switch_config(vconn, &config);
1561 } else if (!strcmp(arg, "invalid_ttl")) {
1562 monitor_set_invalid_ttl_to_controller(vconn);
1563 } else if (!strncmp(arg, "watch:", 6)) {
1564 struct ofputil_flow_monitor_request fmr;
1565 struct ofpbuf *msg;
1566 char *error;
1567
1568 error = parse_flow_monitor_request(&fmr, arg + 6,
1569 &usable_protocols);
1570 if (error) {
1571 ovs_fatal(0, "%s", error);
1572 }
1573
1574 msg = ofpbuf_new(0);
1575 ofputil_append_flow_monitor_request(&fmr, msg);
1576 dump_stats_transaction(vconn, msg);
1577 fflush(stdout);
1578 } else {
1579 ovs_fatal(0, "%s: unsupported \"monitor\" argument", arg);
1580 }
1581 }
1582
1583 if (preferred_packet_in_format >= 0) {
1584 set_packet_in_format(vconn, preferred_packet_in_format);
1585 } else {
1586 enum ofp_version version = vconn_get_version(vconn);
1587
1588 switch (version) {
1589 case OFP10_VERSION: {
1590 struct ofpbuf *spif, *reply;
1591
1592 spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1593 NXPIF_NXM);
1594 run(vconn_transact_noreply(vconn, spif, &reply),
1595 "talking to %s", vconn_get_name(vconn));
1596 if (reply) {
1597 char *s = ofp_to_string(reply->data, reply->size, 2);
1598 VLOG_DBG("%s: failed to set packet in format to nxm, controller"
1599 " replied: %s. Falling back to the switch default.",
1600 vconn_get_name(vconn), s);
1601 free(s);
1602 ofpbuf_delete(reply);
1603 }
1604 break;
1605 }
1606 case OFP11_VERSION:
1607 case OFP12_VERSION:
1608 case OFP13_VERSION:
1609 case OFP14_VERSION:
1610 case OFP15_VERSION:
1611 break;
1612 default:
1613 OVS_NOT_REACHED();
1614 }
1615 }
1616
1617 monitor_vconn(vconn, true);
1618 }
1619
1620 static void
1621 ofctl_snoop(int argc OVS_UNUSED, char *argv[])
1622 {
1623 struct vconn *vconn;
1624
1625 open_vconn__(argv[1], SNOOP, &vconn);
1626 monitor_vconn(vconn, false);
1627 }
1628
1629 static void
1630 ofctl_dump_ports(int argc, char *argv[])
1631 {
1632 struct ofpbuf *request;
1633 struct vconn *vconn;
1634 ofp_port_t port;
1635
1636 open_vconn(argv[1], &vconn);
1637 port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_ANY;
1638 request = ofputil_encode_dump_ports_request(vconn_get_version(vconn), port);
1639 dump_stats_transaction(vconn, request);
1640 vconn_close(vconn);
1641 }
1642
1643 static void
1644 ofctl_dump_ports_desc(int argc OVS_UNUSED, char *argv[])
1645 {
1646 struct ofpbuf *request;
1647 struct vconn *vconn;
1648 ofp_port_t port;
1649
1650 open_vconn(argv[1], &vconn);
1651 port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_ANY;
1652 request = ofputil_encode_port_desc_stats_request(vconn_get_version(vconn),
1653 port);
1654 dump_stats_transaction(vconn, request);
1655 vconn_close(vconn);
1656 }
1657
1658 static void
1659 ofctl_probe(int argc OVS_UNUSED, char *argv[])
1660 {
1661 struct ofpbuf *request;
1662 struct vconn *vconn;
1663 struct ofpbuf *reply;
1664
1665 open_vconn(argv[1], &vconn);
1666 request = make_echo_request(vconn_get_version(vconn));
1667 run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1668 if (reply->size != sizeof(struct ofp_header)) {
1669 ovs_fatal(0, "reply does not match request");
1670 }
1671 ofpbuf_delete(reply);
1672 vconn_close(vconn);
1673 }
1674
1675 static void
1676 ofctl_packet_out(int argc, char *argv[])
1677 {
1678 enum ofputil_protocol protocol;
1679 struct ofputil_packet_out po;
1680 struct ofpbuf ofpacts;
1681 struct vconn *vconn;
1682 char *error;
1683 int i;
1684 enum ofputil_protocol usable_protocols; /* XXX: Use in proto selection */
1685
1686 ofpbuf_init(&ofpacts, 64);
1687 error = ofpacts_parse_actions(argv[3], &ofpacts, &usable_protocols);
1688 if (error) {
1689 ovs_fatal(0, "%s", error);
1690 }
1691
1692 po.buffer_id = UINT32_MAX;
1693 po.in_port = str_to_port_no(argv[1], argv[2]);
1694 po.ofpacts = ofpacts.data;
1695 po.ofpacts_len = ofpacts.size;
1696
1697 protocol = open_vconn(argv[1], &vconn);
1698 for (i = 4; i < argc; i++) {
1699 struct dp_packet *packet;
1700 struct ofpbuf *opo;
1701 const char *error_msg;
1702
1703 error_msg = eth_from_hex(argv[i], &packet);
1704 if (error_msg) {
1705 ovs_fatal(0, "%s", error_msg);
1706 }
1707
1708 po.packet = dp_packet_data(packet);
1709 po.packet_len = dp_packet_size(packet);
1710 opo = ofputil_encode_packet_out(&po, protocol);
1711 transact_noreply(vconn, opo);
1712 dp_packet_delete(packet);
1713 }
1714 vconn_close(vconn);
1715 ofpbuf_uninit(&ofpacts);
1716 }
1717
1718 static void
1719 ofctl_mod_port(int argc OVS_UNUSED, char *argv[])
1720 {
1721 struct ofp_config_flag {
1722 const char *name; /* The flag's name. */
1723 enum ofputil_port_config bit; /* Bit to turn on or off. */
1724 bool on; /* Value to set the bit to. */
1725 };
1726 static const struct ofp_config_flag flags[] = {
1727 { "up", OFPUTIL_PC_PORT_DOWN, false },
1728 { "down", OFPUTIL_PC_PORT_DOWN, true },
1729 { "stp", OFPUTIL_PC_NO_STP, false },
1730 { "receive", OFPUTIL_PC_NO_RECV, false },
1731 { "receive-stp", OFPUTIL_PC_NO_RECV_STP, false },
1732 { "flood", OFPUTIL_PC_NO_FLOOD, false },
1733 { "forward", OFPUTIL_PC_NO_FWD, false },
1734 { "packet-in", OFPUTIL_PC_NO_PACKET_IN, false },
1735 };
1736
1737 const struct ofp_config_flag *flag;
1738 enum ofputil_protocol protocol;
1739 struct ofputil_port_mod pm;
1740 struct ofputil_phy_port pp;
1741 struct vconn *vconn;
1742 const char *command;
1743 bool not;
1744
1745 fetch_ofputil_phy_port(argv[1], argv[2], &pp);
1746
1747 pm.port_no = pp.port_no;
1748 memcpy(pm.hw_addr, pp.hw_addr, ETH_ADDR_LEN);
1749 pm.config = 0;
1750 pm.mask = 0;
1751 pm.advertise = 0;
1752
1753 if (!strncasecmp(argv[3], "no-", 3)) {
1754 command = argv[3] + 3;
1755 not = true;
1756 } else if (!strncasecmp(argv[3], "no", 2)) {
1757 command = argv[3] + 2;
1758 not = true;
1759 } else {
1760 command = argv[3];
1761 not = false;
1762 }
1763 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1764 if (!strcasecmp(command, flag->name)) {
1765 pm.mask = flag->bit;
1766 pm.config = flag->on ^ not ? flag->bit : 0;
1767 goto found;
1768 }
1769 }
1770 ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1771
1772 found:
1773 protocol = open_vconn(argv[1], &vconn);
1774 transact_noreply(vconn, ofputil_encode_port_mod(&pm, protocol));
1775 vconn_close(vconn);
1776 }
1777
1778 static void
1779 ofctl_mod_table(int argc OVS_UNUSED, char *argv[])
1780 {
1781 enum ofputil_protocol protocol, usable_protocols;
1782 struct ofputil_table_mod tm;
1783 struct vconn *vconn;
1784 char *error;
1785 int i;
1786
1787 error = parse_ofp_table_mod(&tm, argv[2], argv[3], &usable_protocols);
1788 if (error) {
1789 ovs_fatal(0, "%s", error);
1790 }
1791
1792 protocol = open_vconn(argv[1], &vconn);
1793 if (!(protocol & usable_protocols)) {
1794 for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1795 enum ofputil_protocol f = 1 << i;
1796 if (f != protocol
1797 && f & usable_protocols
1798 && try_set_protocol(vconn, f, &protocol)) {
1799 protocol = f;
1800 break;
1801 }
1802 }
1803 }
1804
1805 if (!(protocol & usable_protocols)) {
1806 char *usable_s = ofputil_protocols_to_string(usable_protocols);
1807 ovs_fatal(0, "Switch does not support table mod message(%s)", usable_s);
1808 }
1809
1810 transact_noreply(vconn, ofputil_encode_table_mod(&tm, protocol));
1811 vconn_close(vconn);
1812 }
1813
1814 static void
1815 ofctl_get_frags(int argc OVS_UNUSED, char *argv[])
1816 {
1817 struct ofp_switch_config config;
1818 struct vconn *vconn;
1819
1820 open_vconn(argv[1], &vconn);
1821 fetch_switch_config(vconn, &config);
1822 puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
1823 vconn_close(vconn);
1824 }
1825
1826 static void
1827 ofctl_set_frags(int argc OVS_UNUSED, char *argv[])
1828 {
1829 struct ofp_switch_config config;
1830 enum ofp_config_flags mode;
1831 struct vconn *vconn;
1832 ovs_be16 flags;
1833
1834 if (!ofputil_frag_handling_from_string(argv[2], &mode)) {
1835 ovs_fatal(0, "%s: unknown fragment handling mode", argv[2]);
1836 }
1837
1838 open_vconn(argv[1], &vconn);
1839 fetch_switch_config(vconn, &config);
1840 flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
1841 if (flags != config.flags) {
1842 /* Set the configuration. */
1843 config.flags = flags;
1844 set_switch_config(vconn, &config);
1845
1846 /* Then retrieve the configuration to see if it really took. OpenFlow
1847 * doesn't define error reporting for bad modes, so this is all we can
1848 * do. */
1849 fetch_switch_config(vconn, &config);
1850 if (flags != config.flags) {
1851 ovs_fatal(0, "%s: setting fragment handling mode failed (this "
1852 "switch probably doesn't support mode \"%s\")",
1853 argv[1], ofputil_frag_handling_to_string(mode));
1854 }
1855 }
1856 vconn_close(vconn);
1857 }
1858
1859 static void
1860 ofctl_ofp_parse(int argc OVS_UNUSED, char *argv[])
1861 {
1862 const char *filename = argv[1];
1863 struct ofpbuf b;
1864 FILE *file;
1865
1866 file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
1867 if (file == NULL) {
1868 ovs_fatal(errno, "%s: open", filename);
1869 }
1870
1871 ofpbuf_init(&b, 65536);
1872 for (;;) {
1873 struct ofp_header *oh;
1874 size_t length, tail_len;
1875 void *tail;
1876 size_t n;
1877
1878 ofpbuf_clear(&b);
1879 oh = ofpbuf_put_uninit(&b, sizeof *oh);
1880 n = fread(oh, 1, sizeof *oh, file);
1881 if (n == 0) {
1882 break;
1883 } else if (n < sizeof *oh) {
1884 ovs_fatal(0, "%s: unexpected end of file mid-message", filename);
1885 }
1886
1887 length = ntohs(oh->length);
1888 if (length < sizeof *oh) {
1889 ovs_fatal(0, "%s: %"PRIuSIZE"-byte message is too short for OpenFlow",
1890 filename, length);
1891 }
1892
1893 tail_len = length - sizeof *oh;
1894 tail = ofpbuf_put_uninit(&b, tail_len);
1895 n = fread(tail, 1, tail_len, file);
1896 if (n < tail_len) {
1897 ovs_fatal(0, "%s: unexpected end of file mid-message", filename);
1898 }
1899
1900 ofp_print(stdout, b.data, b.size, verbosity + 2);
1901 }
1902 ofpbuf_uninit(&b);
1903
1904 if (file != stdin) {
1905 fclose(file);
1906 }
1907 }
1908
1909 static bool
1910 is_openflow_port(ovs_be16 port_, char *ports[])
1911 {
1912 uint16_t port = ntohs(port_);
1913 if (ports[0]) {
1914 int i;
1915
1916 for (i = 0; ports[i]; i++) {
1917 if (port == atoi(ports[i])) {
1918 return true;
1919 }
1920 }
1921 return false;
1922 } else {
1923 return port == OFP_PORT || port == OFP_OLD_PORT;
1924 }
1925 }
1926
1927 static void
1928 ofctl_ofp_parse_pcap(int argc OVS_UNUSED, char *argv[])
1929 {
1930 struct tcp_reader *reader;
1931 FILE *file;
1932 int error;
1933 bool first;
1934
1935 file = ovs_pcap_open(argv[1], "rb");
1936 if (!file) {
1937 ovs_fatal(errno, "%s: open failed", argv[1]);
1938 }
1939
1940 reader = tcp_reader_open();
1941 first = true;
1942 for (;;) {
1943 struct dp_packet *packet;
1944 long long int when;
1945 struct flow flow;
1946
1947 error = ovs_pcap_read(file, &packet, &when);
1948 if (error) {
1949 break;
1950 }
1951 packet->md = PKT_METADATA_INITIALIZER(ODPP_NONE);
1952 flow_extract(packet, &flow);
1953 if (flow.dl_type == htons(ETH_TYPE_IP)
1954 && flow.nw_proto == IPPROTO_TCP
1955 && (is_openflow_port(flow.tp_src, argv + 2) ||
1956 is_openflow_port(flow.tp_dst, argv + 2))) {
1957 struct dp_packet *payload = tcp_reader_run(reader, &flow, packet);
1958 if (payload) {
1959 while (dp_packet_size(payload) >= sizeof(struct ofp_header)) {
1960 const struct ofp_header *oh;
1961 void *data = dp_packet_data(payload);
1962 int length;
1963
1964 /* Align OpenFlow on 8-byte boundary for safe access. */
1965 dp_packet_shift(payload, -((intptr_t) data & 7));
1966
1967 oh = dp_packet_data(payload);
1968 length = ntohs(oh->length);
1969 if (dp_packet_size(payload) < length) {
1970 break;
1971 }
1972
1973 if (!first) {
1974 putchar('\n');
1975 }
1976 first = false;
1977
1978 if (timestamp) {
1979 char *s = xastrftime_msec("%H:%M:%S.### ", when, true);
1980 fputs(s, stdout);
1981 free(s);
1982 }
1983
1984 printf(IP_FMT".%"PRIu16" > "IP_FMT".%"PRIu16":\n",
1985 IP_ARGS(flow.nw_src), ntohs(flow.tp_src),
1986 IP_ARGS(flow.nw_dst), ntohs(flow.tp_dst));
1987 ofp_print(stdout, dp_packet_data(payload), length, verbosity + 1);
1988 dp_packet_pull(payload, length);
1989 }
1990 }
1991 }
1992 dp_packet_delete(packet);
1993 }
1994 tcp_reader_close(reader);
1995 }
1996
1997 static void
1998 ofctl_ping(int argc, char *argv[])
1999 {
2000 size_t max_payload = 65535 - sizeof(struct ofp_header);
2001 unsigned int payload;
2002 struct vconn *vconn;
2003 int i;
2004
2005 payload = argc > 2 ? atoi(argv[2]) : 64;
2006 if (payload > max_payload) {
2007 ovs_fatal(0, "payload must be between 0 and %"PRIuSIZE" bytes", max_payload);
2008 }
2009
2010 open_vconn(argv[1], &vconn);
2011 for (i = 0; i < 10; i++) {
2012 struct timeval start, end;
2013 struct ofpbuf *request, *reply;
2014 const struct ofp_header *rpy_hdr;
2015 enum ofptype type;
2016
2017 request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
2018 vconn_get_version(vconn), payload);
2019 random_bytes(ofpbuf_put_uninit(request, payload), payload);
2020
2021 xgettimeofday(&start);
2022 run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
2023 xgettimeofday(&end);
2024
2025 rpy_hdr = reply->data;
2026 if (ofptype_pull(&type, reply)
2027 || type != OFPTYPE_ECHO_REPLY
2028 || reply->size != payload
2029 || memcmp(request->msg, reply->msg, payload)) {
2030 printf("Reply does not match request. Request:\n");
2031 ofp_print(stdout, request, request->size, verbosity + 2);
2032 printf("Reply:\n");
2033 ofp_print(stdout, reply, reply->size, verbosity + 2);
2034 }
2035 printf("%"PRIu32" bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
2036 reply->size, argv[1], ntohl(rpy_hdr->xid),
2037 (1000*(double)(end.tv_sec - start.tv_sec))
2038 + (.001*(end.tv_usec - start.tv_usec)));
2039 ofpbuf_delete(request);
2040 ofpbuf_delete(reply);
2041 }
2042 vconn_close(vconn);
2043 }
2044
2045 static void
2046 ofctl_benchmark(int argc OVS_UNUSED, char *argv[])
2047 {
2048 size_t max_payload = 65535 - sizeof(struct ofp_header);
2049 struct timeval start, end;
2050 unsigned int payload_size, message_size;
2051 struct vconn *vconn;
2052 double duration;
2053 int count;
2054 int i;
2055
2056 payload_size = atoi(argv[2]);
2057 if (payload_size > max_payload) {
2058 ovs_fatal(0, "payload must be between 0 and %"PRIuSIZE" bytes", max_payload);
2059 }
2060 message_size = sizeof(struct ofp_header) + payload_size;
2061
2062 count = atoi(argv[3]);
2063
2064 printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
2065 count, message_size, count * message_size);
2066
2067 open_vconn(argv[1], &vconn);
2068 xgettimeofday(&start);
2069 for (i = 0; i < count; i++) {
2070 struct ofpbuf *request, *reply;
2071
2072 request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
2073 vconn_get_version(vconn), payload_size);
2074 ofpbuf_put_zeros(request, payload_size);
2075 run(vconn_transact(vconn, request, &reply), "transact");
2076 ofpbuf_delete(reply);
2077 }
2078 xgettimeofday(&end);
2079 vconn_close(vconn);
2080
2081 duration = ((1000*(double)(end.tv_sec - start.tv_sec))
2082 + (.001*(end.tv_usec - start.tv_usec)));
2083 printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
2084 duration, count / (duration / 1000.0),
2085 count * message_size / (duration / 1000.0));
2086 }
2087
2088 static void
2089 ofctl_group_mod__(const char *remote, struct ofputil_group_mod *gms,
2090 size_t n_gms, enum ofputil_protocol usable_protocols)
2091 {
2092 enum ofputil_protocol protocol;
2093 struct ofputil_group_mod *gm;
2094 enum ofp_version version;
2095 struct ofpbuf *request;
2096
2097 struct vconn *vconn;
2098 size_t i;
2099
2100 protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
2101 version = ofputil_protocol_to_ofp_version(protocol);
2102
2103 for (i = 0; i < n_gms; i++) {
2104 gm = &gms[i];
2105 request = ofputil_encode_group_mod(version, gm);
2106 if (request) {
2107 transact_noreply(vconn, request);
2108 }
2109 }
2110
2111 vconn_close(vconn);
2112
2113 }
2114
2115
2116 static void
2117 ofctl_group_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
2118 {
2119 struct ofputil_group_mod *gms = NULL;
2120 enum ofputil_protocol usable_protocols;
2121 size_t n_gms = 0;
2122 char *error;
2123 int i;
2124
2125 error = parse_ofp_group_mod_file(argv[2], command, &gms, &n_gms,
2126 &usable_protocols);
2127 if (error) {
2128 ovs_fatal(0, "%s", error);
2129 }
2130 ofctl_group_mod__(argv[1], gms, n_gms, usable_protocols);
2131 for (i = 0; i < n_gms; i++) {
2132 ofputil_bucket_list_destroy(&gms[i].buckets);
2133 }
2134 free(gms);
2135 }
2136
2137 static void
2138 ofctl_group_mod(int argc, char *argv[], uint16_t command)
2139 {
2140 if (argc > 2 && !strcmp(argv[2], "-")) {
2141 ofctl_group_mod_file(argc, argv, command);
2142 } else {
2143 enum ofputil_protocol usable_protocols;
2144 struct ofputil_group_mod gm;
2145 char *error;
2146
2147 error = parse_ofp_group_mod_str(&gm, command, argc > 2 ? argv[2] : "",
2148 &usable_protocols);
2149 if (error) {
2150 ovs_fatal(0, "%s", error);
2151 }
2152 ofctl_group_mod__(argv[1], &gm, 1, usable_protocols);
2153 ofputil_bucket_list_destroy(&gm.buckets);
2154 }
2155 }
2156
2157 static void
2158 ofctl_add_group(int argc, char *argv[])
2159 {
2160 ofctl_group_mod(argc, argv, OFPGC11_ADD);
2161 }
2162
2163 static void
2164 ofctl_add_groups(int argc, char *argv[])
2165 {
2166 ofctl_group_mod_file(argc, argv, OFPGC11_ADD);
2167 }
2168
2169 static void
2170 ofctl_mod_group(int argc, char *argv[])
2171 {
2172 ofctl_group_mod(argc, argv, OFPGC11_MODIFY);
2173 }
2174
2175 static void
2176 ofctl_del_groups(int argc, char *argv[])
2177 {
2178 ofctl_group_mod(argc, argv, OFPGC11_DELETE);
2179 }
2180
2181 static void
2182 ofctl_insert_bucket(int argc, char *argv[])
2183 {
2184 ofctl_group_mod(argc, argv, OFPGC15_INSERT_BUCKET);
2185 }
2186
2187 static void
2188 ofctl_remove_bucket(int argc, char *argv[])
2189 {
2190 ofctl_group_mod(argc, argv, OFPGC15_REMOVE_BUCKET);
2191 }
2192
2193 static void
2194 ofctl_dump_group_stats(int argc, char *argv[])
2195 {
2196 enum ofputil_protocol usable_protocols;
2197 struct ofputil_group_mod gm;
2198 struct ofpbuf *request;
2199 struct vconn *vconn;
2200 uint32_t group_id;
2201 char *error;
2202
2203 memset(&gm, 0, sizeof gm);
2204
2205 error = parse_ofp_group_mod_str(&gm, OFPGC11_DELETE,
2206 argc > 2 ? argv[2] : "",
2207 &usable_protocols);
2208 if (error) {
2209 ovs_fatal(0, "%s", error);
2210 }
2211
2212 group_id = gm.group_id;
2213
2214 open_vconn(argv[1], &vconn);
2215 request = ofputil_encode_group_stats_request(vconn_get_version(vconn),
2216 group_id);
2217 if (request) {
2218 dump_stats_transaction(vconn, request);
2219 }
2220
2221 vconn_close(vconn);
2222 }
2223
2224 static void
2225 ofctl_dump_group_desc(int argc OVS_UNUSED, char *argv[])
2226 {
2227 struct ofpbuf *request;
2228 struct vconn *vconn;
2229 uint32_t group_id;
2230
2231 open_vconn(argv[1], &vconn);
2232
2233 if (argc < 3 || !ofputil_group_from_string(argv[2], &group_id)) {
2234 group_id = OFPG11_ALL;
2235 }
2236
2237 request = ofputil_encode_group_desc_request(vconn_get_version(vconn),
2238 group_id);
2239 if (request) {
2240 dump_stats_transaction(vconn, request);
2241 }
2242
2243 vconn_close(vconn);
2244 }
2245
2246 static void
2247 ofctl_dump_group_features(int argc OVS_UNUSED, char *argv[])
2248 {
2249 struct ofpbuf *request;
2250 struct vconn *vconn;
2251
2252 open_vconn(argv[1], &vconn);
2253 request = ofputil_encode_group_features_request(vconn_get_version(vconn));
2254 if (request) {
2255 dump_stats_transaction(vconn, request);
2256 }
2257
2258 vconn_close(vconn);
2259 }
2260
2261 static void
2262 ofctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2263 {
2264 usage();
2265 }
2266
2267 static void
2268 ofctl_list_commands(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2269 {
2270 print_commands(get_all_commands());
2271 }
2272 \f
2273 /* replace-flows and diff-flows commands. */
2274
2275 /* A flow table entry, possibly with two different versions. */
2276 struct fte {
2277 struct cls_rule rule; /* Within a "struct classifier". */
2278 struct fte_version *versions[2];
2279 };
2280
2281 /* One version of a Flow Table Entry. */
2282 struct fte_version {
2283 ovs_be64 cookie;
2284 uint16_t idle_timeout;
2285 uint16_t hard_timeout;
2286 uint16_t importance;
2287 uint16_t flags;
2288 struct ofpact *ofpacts;
2289 size_t ofpacts_len;
2290 };
2291
2292 /* Frees 'version' and the data that it owns. */
2293 static void
2294 fte_version_free(struct fte_version *version)
2295 {
2296 if (version) {
2297 free(CONST_CAST(struct ofpact *, version->ofpacts));
2298 free(version);
2299 }
2300 }
2301
2302 /* Returns true if 'a' and 'b' are the same, false if they differ.
2303 *
2304 * Ignores differences in 'flags' because there's no way to retrieve flags from
2305 * an OpenFlow switch. We have to assume that they are the same. */
2306 static bool
2307 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
2308 {
2309 return (a->cookie == b->cookie
2310 && a->idle_timeout == b->idle_timeout
2311 && a->hard_timeout == b->hard_timeout
2312 && a->importance == b->importance
2313 && ofpacts_equal(a->ofpacts, a->ofpacts_len,
2314 b->ofpacts, b->ofpacts_len));
2315 }
2316
2317 /* Clears 's', then if 's' has a version 'index', formats 'fte' and version
2318 * 'index' into 's', followed by a new-line. */
2319 static void
2320 fte_version_format(const struct fte *fte, int index, struct ds *s)
2321 {
2322 const struct fte_version *version = fte->versions[index];
2323
2324 ds_clear(s);
2325 if (!version) {
2326 return;
2327 }
2328
2329 cls_rule_format(&fte->rule, s);
2330 if (version->cookie != htonll(0)) {
2331 ds_put_format(s, " cookie=0x%"PRIx64, ntohll(version->cookie));
2332 }
2333 if (version->idle_timeout != OFP_FLOW_PERMANENT) {
2334 ds_put_format(s, " idle_timeout=%"PRIu16, version->idle_timeout);
2335 }
2336 if (version->hard_timeout != OFP_FLOW_PERMANENT) {
2337 ds_put_format(s, " hard_timeout=%"PRIu16, version->hard_timeout);
2338 }
2339 if (version->importance != 0) {
2340 ds_put_format(s, " importance=%"PRIu16, version->importance);
2341 }
2342
2343 ds_put_cstr(s, " actions=");
2344 ofpacts_format(version->ofpacts, version->ofpacts_len, s);
2345
2346 ds_put_char(s, '\n');
2347 }
2348
2349 static struct fte *
2350 fte_from_cls_rule(const struct cls_rule *cls_rule)
2351 {
2352 return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
2353 }
2354
2355 /* Frees 'fte' and its versions. */
2356 static void
2357 fte_free(struct fte *fte)
2358 {
2359 if (fte) {
2360 fte_version_free(fte->versions[0]);
2361 fte_version_free(fte->versions[1]);
2362 cls_rule_destroy(&fte->rule);
2363 free(fte);
2364 }
2365 }
2366
2367 /* Frees all of the FTEs within 'cls'. */
2368 static void
2369 fte_free_all(struct classifier *cls)
2370 {
2371 struct fte *fte;
2372
2373 classifier_defer(cls);
2374 CLS_FOR_EACH (fte, rule, cls) {
2375 classifier_remove(cls, &fte->rule);
2376 ovsrcu_postpone(fte_free, fte);
2377 }
2378 classifier_destroy(cls);
2379 }
2380
2381 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
2382 * necessary. Sets 'version' as the version of that rule with the given
2383 * 'index', replacing any existing version, if any.
2384 *
2385 * Takes ownership of 'version'. */
2386 static void
2387 fte_insert(struct classifier *cls, const struct match *match,
2388 int priority, struct fte_version *version, int index)
2389 {
2390 struct fte *old, *fte;
2391
2392 fte = xzalloc(sizeof *fte);
2393 cls_rule_init(&fte->rule, match, priority);
2394 fte->versions[index] = version;
2395
2396 old = fte_from_cls_rule(classifier_replace(cls, &fte->rule, NULL, 0));
2397 if (old) {
2398 fte->versions[!index] = old->versions[!index];
2399 old->versions[!index] = NULL;
2400
2401 ovsrcu_postpone(fte_free, old);
2402 }
2403 }
2404
2405 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
2406 * with the specified 'index'. Returns the flow formats able to represent the
2407 * flows that were read. */
2408 static enum ofputil_protocol
2409 read_flows_from_file(const char *filename, struct classifier *cls, int index)
2410 {
2411 enum ofputil_protocol usable_protocols;
2412 int line_number;
2413 struct ds s;
2414 FILE *file;
2415
2416 file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
2417 if (file == NULL) {
2418 ovs_fatal(errno, "%s: open", filename);
2419 }
2420
2421 ds_init(&s);
2422 usable_protocols = OFPUTIL_P_ANY;
2423 line_number = 0;
2424 classifier_defer(cls);
2425 while (!ds_get_preprocessed_line(&s, file, &line_number)) {
2426 struct fte_version *version;
2427 struct ofputil_flow_mod fm;
2428 char *error;
2429 enum ofputil_protocol usable;
2430
2431 error = parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), &usable);
2432 if (error) {
2433 ovs_fatal(0, "%s:%d: %s", filename, line_number, error);
2434 }
2435 usable_protocols &= usable;
2436
2437 version = xmalloc(sizeof *version);
2438 version->cookie = fm.new_cookie;
2439 version->idle_timeout = fm.idle_timeout;
2440 version->hard_timeout = fm.hard_timeout;
2441 version->importance = fm.importance;
2442 version->flags = fm.flags & (OFPUTIL_FF_SEND_FLOW_REM
2443 | OFPUTIL_FF_EMERG);
2444 version->ofpacts = fm.ofpacts;
2445 version->ofpacts_len = fm.ofpacts_len;
2446
2447 fte_insert(cls, &fm.match, fm.priority, version, index);
2448 }
2449 classifier_publish(cls);
2450 ds_destroy(&s);
2451
2452 if (file != stdin) {
2453 fclose(file);
2454 }
2455
2456 return usable_protocols;
2457 }
2458
2459 static bool
2460 recv_flow_stats_reply(struct vconn *vconn, ovs_be32 send_xid,
2461 struct ofpbuf **replyp,
2462 struct ofputil_flow_stats *fs, struct ofpbuf *ofpacts)
2463 {
2464 struct ofpbuf *reply = *replyp;
2465
2466 for (;;) {
2467 int retval;
2468 bool more;
2469
2470 /* Get a flow stats reply message, if we don't already have one. */
2471 if (!reply) {
2472 enum ofptype type;
2473 enum ofperr error;
2474
2475 do {
2476 run(vconn_recv_block(vconn, &reply),
2477 "OpenFlow packet receive failed");
2478 } while (((struct ofp_header *) reply->data)->xid != send_xid);
2479
2480 error = ofptype_decode(&type, reply->data);
2481 if (error || type != OFPTYPE_FLOW_STATS_REPLY) {
2482 ovs_fatal(0, "received bad reply: %s",
2483 ofp_to_string(reply->data, reply->size,
2484 verbosity + 1));
2485 }
2486 }
2487
2488 /* Pull an individual flow stats reply out of the message. */
2489 retval = ofputil_decode_flow_stats_reply(fs, reply, false, ofpacts);
2490 switch (retval) {
2491 case 0:
2492 *replyp = reply;
2493 return true;
2494
2495 case EOF:
2496 more = ofpmp_more(reply->header);
2497 ofpbuf_delete(reply);
2498 reply = NULL;
2499 if (!more) {
2500 *replyp = NULL;
2501 return false;
2502 }
2503 break;
2504
2505 default:
2506 ovs_fatal(0, "parse error in reply (%s)",
2507 ofperr_to_string(retval));
2508 }
2509 }
2510 }
2511
2512 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
2513 * format 'protocol', and adds them as flow table entries in 'cls' for the
2514 * version with the specified 'index'. */
2515 static void
2516 read_flows_from_switch(struct vconn *vconn,
2517 enum ofputil_protocol protocol,
2518 struct classifier *cls, int index)
2519 {
2520 struct ofputil_flow_stats_request fsr;
2521 struct ofputil_flow_stats fs;
2522 struct ofpbuf *request;
2523 struct ofpbuf ofpacts;
2524 struct ofpbuf *reply;
2525 ovs_be32 send_xid;
2526
2527 fsr.aggregate = false;
2528 match_init_catchall(&fsr.match);
2529 fsr.out_port = OFPP_ANY;
2530 fsr.table_id = 0xff;
2531 fsr.cookie = fsr.cookie_mask = htonll(0);
2532 request = ofputil_encode_flow_stats_request(&fsr, protocol);
2533 send_xid = ((struct ofp_header *) request->data)->xid;
2534 send_openflow_buffer(vconn, request);
2535
2536 reply = NULL;
2537 ofpbuf_init(&ofpacts, 0);
2538 classifier_defer(cls);
2539 while (recv_flow_stats_reply(vconn, send_xid, &reply, &fs, &ofpacts)) {
2540 struct fte_version *version;
2541
2542 version = xmalloc(sizeof *version);
2543 version->cookie = fs.cookie;
2544 version->idle_timeout = fs.idle_timeout;
2545 version->hard_timeout = fs.hard_timeout;
2546 version->importance = fs.importance;
2547 version->flags = 0;
2548 version->ofpacts_len = fs.ofpacts_len;
2549 version->ofpacts = xmemdup(fs.ofpacts, fs.ofpacts_len);
2550
2551 fte_insert(cls, &fs.match, fs.priority, version, index);
2552 }
2553 classifier_publish(cls);
2554 ofpbuf_uninit(&ofpacts);
2555 }
2556
2557 static void
2558 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
2559 enum ofputil_protocol protocol, struct ovs_list *packets)
2560 {
2561 const struct fte_version *version = fte->versions[index];
2562 struct ofputil_flow_mod fm;
2563 struct ofpbuf *ofm;
2564
2565 minimatch_expand(&fte->rule.match, &fm.match);
2566 fm.priority = fte->rule.priority;
2567 fm.cookie = htonll(0);
2568 fm.cookie_mask = htonll(0);
2569 fm.new_cookie = version->cookie;
2570 fm.modify_cookie = true;
2571 fm.table_id = 0xff;
2572 fm.command = command;
2573 fm.idle_timeout = version->idle_timeout;
2574 fm.hard_timeout = version->hard_timeout;
2575 fm.importance = version->importance;
2576 fm.buffer_id = UINT32_MAX;
2577 fm.out_port = OFPP_ANY;
2578 fm.flags = version->flags;
2579 if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
2580 command == OFPFC_MODIFY_STRICT) {
2581 fm.ofpacts = version->ofpacts;
2582 fm.ofpacts_len = version->ofpacts_len;
2583 } else {
2584 fm.ofpacts = NULL;
2585 fm.ofpacts_len = 0;
2586 }
2587 fm.delete_reason = OFPRR_DELETE;
2588
2589 ofm = ofputil_encode_flow_mod(&fm, protocol);
2590 list_push_back(packets, &ofm->list_node);
2591 }
2592
2593 static void
2594 ofctl_replace_flows(int argc OVS_UNUSED, char *argv[])
2595 {
2596 enum { FILE_IDX = 0, SWITCH_IDX = 1 };
2597 enum ofputil_protocol usable_protocols, protocol;
2598 struct classifier cls;
2599 struct ovs_list requests;
2600 struct vconn *vconn;
2601 struct fte *fte;
2602
2603 classifier_init(&cls, NULL);
2604 usable_protocols = read_flows_from_file(argv[2], &cls, FILE_IDX);
2605
2606 protocol = open_vconn(argv[1], &vconn);
2607 protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
2608
2609 read_flows_from_switch(vconn, protocol, &cls, SWITCH_IDX);
2610
2611 list_init(&requests);
2612
2613 /* Delete flows that exist on the switch but not in the file. */
2614 CLS_FOR_EACH (fte, rule, &cls) {
2615 struct fte_version *file_ver = fte->versions[FILE_IDX];
2616 struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
2617
2618 if (sw_ver && !file_ver) {
2619 fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
2620 protocol, &requests);
2621 }
2622 }
2623
2624 /* Add flows that exist in the file but not on the switch.
2625 * Update flows that exist in both places but differ. */
2626 CLS_FOR_EACH (fte, rule, &cls) {
2627 struct fte_version *file_ver = fte->versions[FILE_IDX];
2628 struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
2629
2630 if (file_ver
2631 && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
2632 fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, protocol, &requests);
2633 }
2634 }
2635 transact_multiple_noreply(vconn, &requests);
2636 vconn_close(vconn);
2637
2638 fte_free_all(&cls);
2639 }
2640
2641 static void
2642 read_flows_from_source(const char *source, struct classifier *cls, int index)
2643 {
2644 struct stat s;
2645
2646 if (source[0] == '/' || source[0] == '.'
2647 || (!strchr(source, ':') && !stat(source, &s))) {
2648 read_flows_from_file(source, cls, index);
2649 } else {
2650 enum ofputil_protocol protocol;
2651 struct vconn *vconn;
2652
2653 protocol = open_vconn(source, &vconn);
2654 protocol = set_protocol_for_flow_dump(vconn, protocol, OFPUTIL_P_ANY);
2655 read_flows_from_switch(vconn, protocol, cls, index);
2656 vconn_close(vconn);
2657 }
2658 }
2659
2660 static void
2661 ofctl_diff_flows(int argc OVS_UNUSED, char *argv[])
2662 {
2663 bool differences = false;
2664 struct classifier cls;
2665 struct ds a_s, b_s;
2666 struct fte *fte;
2667
2668 classifier_init(&cls, NULL);
2669 read_flows_from_source(argv[1], &cls, 0);
2670 read_flows_from_source(argv[2], &cls, 1);
2671
2672 ds_init(&a_s);
2673 ds_init(&b_s);
2674
2675 CLS_FOR_EACH (fte, rule, &cls) {
2676 struct fte_version *a = fte->versions[0];
2677 struct fte_version *b = fte->versions[1];
2678
2679 if (!a || !b || !fte_version_equals(a, b)) {
2680 fte_version_format(fte, 0, &a_s);
2681 fte_version_format(fte, 1, &b_s);
2682 if (strcmp(ds_cstr(&a_s), ds_cstr(&b_s))) {
2683 if (a_s.length) {
2684 printf("-%s", ds_cstr(&a_s));
2685 }
2686 if (b_s.length) {
2687 printf("+%s", ds_cstr(&b_s));
2688 }
2689 differences = true;
2690 }
2691 }
2692 }
2693
2694 ds_destroy(&a_s);
2695 ds_destroy(&b_s);
2696
2697 fte_free_all(&cls);
2698
2699 if (differences) {
2700 exit(2);
2701 }
2702 }
2703
2704 static void
2705 ofctl_meter_mod__(const char *bridge, const char *str, int command)
2706 {
2707 struct ofputil_meter_mod mm;
2708 struct vconn *vconn;
2709 enum ofputil_protocol protocol;
2710 enum ofputil_protocol usable_protocols;
2711 enum ofp_version version;
2712
2713 if (str) {
2714 char *error;
2715 error = parse_ofp_meter_mod_str(&mm, str, command, &usable_protocols);
2716 if (error) {
2717 ovs_fatal(0, "%s", error);
2718 }
2719 } else {
2720 usable_protocols = OFPUTIL_P_OF13_UP;
2721 mm.command = command;
2722 mm.meter.meter_id = OFPM13_ALL;
2723 }
2724
2725 protocol = open_vconn_for_flow_mod(bridge, &vconn, usable_protocols);
2726 version = ofputil_protocol_to_ofp_version(protocol);
2727 transact_noreply(vconn, ofputil_encode_meter_mod(version, &mm));
2728 vconn_close(vconn);
2729 }
2730
2731 static void
2732 ofctl_meter_request__(const char *bridge, const char *str,
2733 enum ofputil_meter_request_type type)
2734 {
2735 struct ofputil_meter_mod mm;
2736 struct vconn *vconn;
2737 enum ofputil_protocol usable_protocols;
2738 enum ofputil_protocol protocol;
2739 enum ofp_version version;
2740
2741 if (str) {
2742 char *error;
2743 error = parse_ofp_meter_mod_str(&mm, str, -1, &usable_protocols);
2744 if (error) {
2745 ovs_fatal(0, "%s", error);
2746 }
2747 } else {
2748 usable_protocols = OFPUTIL_P_OF13_UP;
2749 mm.meter.meter_id = OFPM13_ALL;
2750 }
2751
2752 protocol = open_vconn_for_flow_mod(bridge, &vconn, usable_protocols);
2753 version = ofputil_protocol_to_ofp_version(protocol);
2754 transact_noreply(vconn, ofputil_encode_meter_request(version,
2755 type,
2756 mm.meter.meter_id));
2757 vconn_close(vconn);
2758 }
2759
2760
2761 static void
2762 ofctl_add_meter(int argc OVS_UNUSED, char *argv[])
2763 {
2764 ofctl_meter_mod__(argv[1], argv[2], OFPMC13_ADD);
2765 }
2766
2767 static void
2768 ofctl_mod_meter(int argc OVS_UNUSED, char *argv[])
2769 {
2770 ofctl_meter_mod__(argv[1], argv[2], OFPMC13_MODIFY);
2771 }
2772
2773 static void
2774 ofctl_del_meters(int argc, char *argv[])
2775 {
2776 ofctl_meter_mod__(argv[1], argc > 2 ? argv[2] : NULL, OFPMC13_DELETE);
2777 }
2778
2779 static void
2780 ofctl_dump_meters(int argc, char *argv[])
2781 {
2782 ofctl_meter_request__(argv[1], argc > 2 ? argv[2] : NULL,
2783 OFPUTIL_METER_CONFIG);
2784 }
2785
2786 static void
2787 ofctl_meter_stats(int argc, char *argv[])
2788 {
2789 ofctl_meter_request__(argv[1], argc > 2 ? argv[2] : NULL,
2790 OFPUTIL_METER_STATS);
2791 }
2792
2793 static void
2794 ofctl_meter_features(int argc OVS_UNUSED, char *argv[])
2795 {
2796 ofctl_meter_request__(argv[1], NULL, OFPUTIL_METER_FEATURES);
2797 }
2798
2799 \f
2800 /* Undocumented commands for unit testing. */
2801
2802 static void
2803 ofctl_parse_flows__(struct ofputil_flow_mod *fms, size_t n_fms,
2804 enum ofputil_protocol usable_protocols)
2805 {
2806 enum ofputil_protocol protocol = 0;
2807 char *usable_s;
2808 size_t i;
2809
2810 usable_s = ofputil_protocols_to_string(usable_protocols);
2811 printf("usable protocols: %s\n", usable_s);
2812 free(usable_s);
2813
2814 if (!(usable_protocols & allowed_protocols)) {
2815 ovs_fatal(0, "no usable protocol");
2816 }
2817 for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
2818 protocol = 1 << i;
2819 if (protocol & usable_protocols & allowed_protocols) {
2820 break;
2821 }
2822 }
2823 ovs_assert(is_pow2(protocol));
2824
2825 printf("chosen protocol: %s\n", ofputil_protocol_to_string(protocol));
2826
2827 for (i = 0; i < n_fms; i++) {
2828 struct ofputil_flow_mod *fm = &fms[i];
2829 struct ofpbuf *msg;
2830
2831 msg = ofputil_encode_flow_mod(fm, protocol);
2832 ofp_print(stdout, msg->data, msg->size, verbosity);
2833 ofpbuf_delete(msg);
2834
2835 free(CONST_CAST(struct ofpact *, fm->ofpacts));
2836 }
2837 }
2838
2839 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
2840 * it back to stdout. */
2841 static void
2842 ofctl_parse_flow(int argc OVS_UNUSED, char *argv[])
2843 {
2844 enum ofputil_protocol usable_protocols;
2845 struct ofputil_flow_mod fm;
2846 char *error;
2847
2848 error = parse_ofp_flow_mod_str(&fm, argv[1], OFPFC_ADD, &usable_protocols);
2849 if (error) {
2850 ovs_fatal(0, "%s", error);
2851 }
2852 ofctl_parse_flows__(&fm, 1, usable_protocols);
2853 }
2854
2855 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
2856 * add-flows) and prints each of the flows back to stdout. */
2857 static void
2858 ofctl_parse_flows(int argc OVS_UNUSED, char *argv[])
2859 {
2860 enum ofputil_protocol usable_protocols;
2861 struct ofputil_flow_mod *fms = NULL;
2862 size_t n_fms = 0;
2863 char *error;
2864
2865 error = parse_ofp_flow_mod_file(argv[1], OFPFC_ADD, &fms, &n_fms,
2866 &usable_protocols);
2867 if (error) {
2868 ovs_fatal(0, "%s", error);
2869 }
2870 ofctl_parse_flows__(fms, n_fms, usable_protocols);
2871 free(fms);
2872 }
2873
2874 static void
2875 ofctl_parse_nxm__(bool oxm, enum ofp_version version)
2876 {
2877 struct ds in;
2878
2879 ds_init(&in);
2880 while (!ds_get_test_line(&in, stdin)) {
2881 struct ofpbuf nx_match;
2882 struct match match;
2883 ovs_be64 cookie, cookie_mask;
2884 enum ofperr error;
2885 int match_len;
2886
2887 /* Convert string to nx_match. */
2888 ofpbuf_init(&nx_match, 0);
2889 if (oxm) {
2890 match_len = oxm_match_from_string(ds_cstr(&in), &nx_match);
2891 } else {
2892 match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
2893 }
2894
2895 /* Convert nx_match to match. */
2896 if (strict) {
2897 if (oxm) {
2898 error = oxm_pull_match(&nx_match, &match);
2899 } else {
2900 error = nx_pull_match(&nx_match, match_len, &match,
2901 &cookie, &cookie_mask);
2902 }
2903 } else {
2904 if (oxm) {
2905 error = oxm_pull_match_loose(&nx_match, &match);
2906 } else {
2907 error = nx_pull_match_loose(&nx_match, match_len, &match,
2908 &cookie, &cookie_mask);
2909 }
2910 }
2911
2912
2913 if (!error) {
2914 char *out;
2915
2916 /* Convert match back to nx_match. */
2917 ofpbuf_uninit(&nx_match);
2918 ofpbuf_init(&nx_match, 0);
2919 if (oxm) {
2920 match_len = oxm_put_match(&nx_match, &match, version);
2921 out = oxm_match_to_string(&nx_match, match_len);
2922 } else {
2923 match_len = nx_put_match(&nx_match, &match,
2924 cookie, cookie_mask);
2925 out = nx_match_to_string(nx_match.data, match_len);
2926 }
2927
2928 puts(out);
2929 free(out);
2930
2931 if (verbosity > 0) {
2932 ovs_hex_dump(stdout, nx_match.data, nx_match.size, 0, false);
2933 }
2934 } else {
2935 printf("nx_pull_match() returned error %s\n",
2936 ofperr_get_name(error));
2937 }
2938
2939 ofpbuf_uninit(&nx_match);
2940 }
2941 ds_destroy(&in);
2942 }
2943
2944 /* "parse-nxm": reads a series of NXM nx_match specifications as strings from
2945 * stdin, does some internal fussing with them, and then prints them back as
2946 * strings on stdout. */
2947 static void
2948 ofctl_parse_nxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2949 {
2950 ofctl_parse_nxm__(false, 0);
2951 }
2952
2953 /* "parse-oxm VERSION": reads a series of OXM nx_match specifications as
2954 * strings from stdin, does some internal fussing with them, and then prints
2955 * them back as strings on stdout. VERSION must specify an OpenFlow version,
2956 * e.g. "OpenFlow12". */
2957 static void
2958 ofctl_parse_oxm(int argc OVS_UNUSED, char *argv[])
2959 {
2960 enum ofp_version version = ofputil_version_from_string(argv[1]);
2961 if (version < OFP12_VERSION) {
2962 ovs_fatal(0, "%s: not a valid version for OXM", argv[1]);
2963 }
2964
2965 ofctl_parse_nxm__(true, version);
2966 }
2967
2968 static void
2969 print_differences(const char *prefix,
2970 const void *a_, size_t a_len,
2971 const void *b_, size_t b_len)
2972 {
2973 const uint8_t *a = a_;
2974 const uint8_t *b = b_;
2975 size_t i;
2976
2977 for (i = 0; i < MIN(a_len, b_len); i++) {
2978 if (a[i] != b[i]) {
2979 printf("%s%2"PRIuSIZE": %02"PRIx8" -> %02"PRIx8"\n",
2980 prefix, i, a[i], b[i]);
2981 }
2982 }
2983 for (i = a_len; i < b_len; i++) {
2984 printf("%s%2"PRIuSIZE": (none) -> %02"PRIx8"\n", prefix, i, b[i]);
2985 }
2986 for (i = b_len; i < a_len; i++) {
2987 printf("%s%2"PRIuSIZE": %02"PRIx8" -> (none)\n", prefix, i, a[i]);
2988 }
2989 }
2990
2991 static void
2992 ofctl_parse_actions__(const char *version_s, bool instructions)
2993 {
2994 enum ofp_version version;
2995 struct ds in;
2996
2997 version = ofputil_version_from_string(version_s);
2998 if (!version) {
2999 ovs_fatal(0, "%s: not a valid OpenFlow version", version_s);
3000 }
3001
3002 ds_init(&in);
3003 while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3004 struct ofpbuf of_out;
3005 struct ofpbuf of_in;
3006 struct ofpbuf ofpacts;
3007 const char *table_id;
3008 char *actions;
3009 enum ofperr error;
3010 size_t size;
3011 struct ds s;
3012
3013 /* Parse table_id separated with the follow-up actions by ",", if
3014 * any. */
3015 actions = ds_cstr(&in);
3016 table_id = NULL;
3017 if (strstr(actions, ",")) {
3018 table_id = strsep(&actions, ",");
3019 }
3020
3021 /* Parse hex bytes. */
3022 ofpbuf_init(&of_in, 0);
3023 if (ofpbuf_put_hex(&of_in, actions, NULL)[0] != '\0') {
3024 ovs_fatal(0, "Trailing garbage in hex data");
3025 }
3026
3027 /* Convert to ofpacts. */
3028 ofpbuf_init(&ofpacts, 0);
3029 size = of_in.size;
3030 error = (instructions
3031 ? ofpacts_pull_openflow_instructions
3032 : ofpacts_pull_openflow_actions)(
3033 &of_in, of_in.size, version, &ofpacts);
3034 if (!error && instructions) {
3035 /* Verify actions, enforce consistency. */
3036 enum ofputil_protocol protocol;
3037 struct flow flow;
3038
3039 memset(&flow, 0, sizeof flow);
3040 protocol = ofputil_protocols_from_ofp_version(version);
3041 error = ofpacts_check_consistency(ofpacts.data, ofpacts.size,
3042 &flow, OFPP_MAX,
3043 table_id ? atoi(table_id) : 0,
3044 255, protocol);
3045 }
3046 if (error) {
3047 printf("bad %s %s: %s\n\n",
3048 version_s, instructions ? "instructions" : "actions",
3049 ofperr_get_name(error));
3050 ofpbuf_uninit(&ofpacts);
3051 ofpbuf_uninit(&of_in);
3052 continue;
3053 }
3054 ofpbuf_push_uninit(&of_in, size);
3055
3056 /* Print cls_rule. */
3057 ds_init(&s);
3058 ds_put_cstr(&s, "actions=");
3059 ofpacts_format(ofpacts.data, ofpacts.size, &s);
3060 puts(ds_cstr(&s));
3061 ds_destroy(&s);
3062
3063 /* Convert back to ofp10 actions and print differences from input. */
3064 ofpbuf_init(&of_out, 0);
3065 if (instructions) {
3066 ofpacts_put_openflow_instructions(ofpacts.data, ofpacts.size,
3067 &of_out, version);
3068 } else {
3069 ofpacts_put_openflow_actions(ofpacts.data, ofpacts.size,
3070 &of_out, version);
3071 }
3072
3073 print_differences("", of_in.data, of_in.size,
3074 of_out.data, of_out.size);
3075 putchar('\n');
3076
3077 ofpbuf_uninit(&ofpacts);
3078 ofpbuf_uninit(&of_in);
3079 ofpbuf_uninit(&of_out);
3080 }
3081 ds_destroy(&in);
3082 }
3083
3084 /* "parse-actions VERSION": reads a series of action specifications for the
3085 * given OpenFlow VERSION as hex bytes from stdin, converts them to ofpacts,
3086 * prints them as strings on stdout, and then converts them back to hex bytes
3087 * and prints any differences from the input. */
3088 static void
3089 ofctl_parse_actions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
3090 {
3091 ofctl_parse_actions__(argv[1], false);
3092 }
3093
3094 /* "parse-actions VERSION": reads a series of instruction specifications for
3095 * the given OpenFlow VERSION as hex bytes from stdin, converts them to
3096 * ofpacts, prints them as strings on stdout, and then converts them back to
3097 * hex bytes and prints any differences from the input. */
3098 static void
3099 ofctl_parse_instructions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
3100 {
3101 ofctl_parse_actions__(argv[1], true);
3102 }
3103
3104 /* "parse-ofp10-match": reads a series of ofp10_match specifications as hex
3105 * bytes from stdin, converts them to cls_rules, prints them as strings on
3106 * stdout, and then converts them back to hex bytes and prints any differences
3107 * from the input.
3108 *
3109 * The input hex bytes may contain "x"s to represent "don't-cares", bytes whose
3110 * values are ignored in the input and will be set to zero when OVS converts
3111 * them back to hex bytes. ovs-ofctl actually sets "x"s to random bits when
3112 * it does the conversion to hex, to ensure that in fact they are ignored. */
3113 static void
3114 ofctl_parse_ofp10_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
3115 {
3116 struct ds expout;
3117 struct ds in;
3118
3119 ds_init(&in);
3120 ds_init(&expout);
3121 while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3122 struct ofpbuf match_in, match_expout;
3123 struct ofp10_match match_out;
3124 struct ofp10_match match_normal;
3125 struct match match;
3126 char *p;
3127
3128 /* Parse hex bytes to use for expected output. */
3129 ds_clear(&expout);
3130 ds_put_cstr(&expout, ds_cstr(&in));
3131 for (p = ds_cstr(&expout); *p; p++) {
3132 if (*p == 'x') {
3133 *p = '0';
3134 }
3135 }
3136 ofpbuf_init(&match_expout, 0);
3137 if (ofpbuf_put_hex(&match_expout, ds_cstr(&expout), NULL)[0] != '\0') {
3138 ovs_fatal(0, "Trailing garbage in hex data");
3139 }
3140 if (match_expout.size != sizeof(struct ofp10_match)) {
3141 ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
3142 match_expout.size, sizeof(struct ofp10_match));
3143 }
3144
3145 /* Parse hex bytes for input. */
3146 for (p = ds_cstr(&in); *p; p++) {
3147 if (*p == 'x') {
3148 *p = "0123456789abcdef"[random_uint32() & 0xf];
3149 }
3150 }
3151 ofpbuf_init(&match_in, 0);
3152 if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
3153 ovs_fatal(0, "Trailing garbage in hex data");
3154 }
3155 if (match_in.size != sizeof(struct ofp10_match)) {
3156 ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
3157 match_in.size, sizeof(struct ofp10_match));
3158 }
3159
3160 /* Convert to cls_rule and print. */
3161 ofputil_match_from_ofp10_match(match_in.data, &match);
3162 match_print(&match);
3163
3164 /* Convert back to ofp10_match and print differences from input. */
3165 ofputil_match_to_ofp10_match(&match, &match_out);
3166 print_differences("", match_expout.data, match_expout.size,
3167 &match_out, sizeof match_out);
3168
3169 /* Normalize, then convert and compare again. */
3170 ofputil_normalize_match(&match);
3171 ofputil_match_to_ofp10_match(&match, &match_normal);
3172 print_differences("normal: ", &match_out, sizeof match_out,
3173 &match_normal, sizeof match_normal);
3174 putchar('\n');
3175
3176 ofpbuf_uninit(&match_in);
3177 ofpbuf_uninit(&match_expout);
3178 }
3179 ds_destroy(&in);
3180 ds_destroy(&expout);
3181 }
3182
3183 /* "parse-ofp11-match": reads a series of ofp11_match specifications as hex
3184 * bytes from stdin, converts them to "struct match"es, prints them as strings
3185 * on stdout, and then converts them back to hex bytes and prints any
3186 * differences from the input. */
3187 static void
3188 ofctl_parse_ofp11_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
3189 {
3190 struct ds in;
3191
3192 ds_init(&in);
3193 while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3194 struct ofpbuf match_in;
3195 struct ofp11_match match_out;
3196 struct match match;
3197 enum ofperr error;
3198
3199 /* Parse hex bytes. */
3200 ofpbuf_init(&match_in, 0);
3201 if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
3202 ovs_fatal(0, "Trailing garbage in hex data");
3203 }
3204 if (match_in.size != sizeof(struct ofp11_match)) {
3205 ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
3206 match_in.size, sizeof(struct ofp11_match));
3207 }
3208
3209 /* Convert to match. */
3210 error = ofputil_match_from_ofp11_match(match_in.data, &match);
3211 if (error) {
3212 printf("bad ofp11_match: %s\n\n", ofperr_get_name(error));
3213 ofpbuf_uninit(&match_in);
3214 continue;
3215 }
3216
3217 /* Print match. */
3218 match_print(&match);
3219
3220 /* Convert back to ofp11_match and print differences from input. */
3221 ofputil_match_to_ofp11_match(&match, &match_out);
3222
3223 print_differences("", match_in.data, match_in.size,
3224 &match_out, sizeof match_out);
3225 putchar('\n');
3226
3227 ofpbuf_uninit(&match_in);
3228 }
3229 ds_destroy(&in);
3230 }
3231
3232 /* "parse-pcap PCAP": read packets from PCAP and print their flows. */
3233 static void
3234 ofctl_parse_pcap(int argc OVS_UNUSED, char *argv[])
3235 {
3236 FILE *pcap;
3237
3238 pcap = ovs_pcap_open(argv[1], "rb");
3239 if (!pcap) {
3240 ovs_fatal(errno, "%s: open failed", argv[1]);
3241 }
3242
3243 for (;;) {
3244 struct dp_packet *packet;
3245 struct flow flow;
3246 int error;
3247
3248 error = ovs_pcap_read(pcap, &packet, NULL);
3249 if (error == EOF) {
3250 break;
3251 } else if (error) {
3252 ovs_fatal(error, "%s: read failed", argv[1]);
3253 }
3254
3255 packet->md = PKT_METADATA_INITIALIZER(ODPP_NONE);
3256 flow_extract(packet, &flow);
3257 flow_print(stdout, &flow);
3258 putchar('\n');
3259 dp_packet_delete(packet);
3260 }
3261 }
3262
3263 /* "check-vlan VLAN_TCI VLAN_TCI_MASK": converts the specified vlan_tci and
3264 * mask values to and from various formats and prints the results. */
3265 static void
3266 ofctl_check_vlan(int argc OVS_UNUSED, char *argv[])
3267 {
3268 struct match match;
3269
3270 char *string_s;
3271 struct ofputil_flow_mod fm;
3272
3273 struct ofpbuf nxm;
3274 struct match nxm_match;
3275 int nxm_match_len;
3276 char *nxm_s;
3277
3278 struct ofp10_match of10_raw;
3279 struct match of10_match;
3280
3281 struct ofp11_match of11_raw;
3282 struct match of11_match;
3283
3284 enum ofperr error;
3285 char *error_s;
3286
3287 enum ofputil_protocol usable_protocols; /* Unused for now. */
3288
3289 match_init_catchall(&match);
3290 match.flow.vlan_tci = htons(strtoul(argv[1], NULL, 16));
3291 match.wc.masks.vlan_tci = htons(strtoul(argv[2], NULL, 16));
3292
3293 /* Convert to and from string. */
3294 string_s = match_to_string(&match, OFP_DEFAULT_PRIORITY);
3295 printf("%s -> ", string_s);
3296 fflush(stdout);
3297 error_s = parse_ofp_str(&fm, -1, string_s, &usable_protocols);
3298 if (error_s) {
3299 ovs_fatal(0, "%s", error_s);
3300 }
3301 printf("%04"PRIx16"/%04"PRIx16"\n",
3302 ntohs(fm.match.flow.vlan_tci),
3303 ntohs(fm.match.wc.masks.vlan_tci));
3304 free(string_s);
3305
3306 /* Convert to and from NXM. */
3307 ofpbuf_init(&nxm, 0);
3308 nxm_match_len = nx_put_match(&nxm, &match, htonll(0), htonll(0));
3309 nxm_s = nx_match_to_string(nxm.data, nxm_match_len);
3310 error = nx_pull_match(&nxm, nxm_match_len, &nxm_match, NULL, NULL);
3311 printf("NXM: %s -> ", nxm_s);
3312 if (error) {
3313 printf("%s\n", ofperr_to_string(error));
3314 } else {
3315 printf("%04"PRIx16"/%04"PRIx16"\n",
3316 ntohs(nxm_match.flow.vlan_tci),
3317 ntohs(nxm_match.wc.masks.vlan_tci));
3318 }
3319 free(nxm_s);
3320 ofpbuf_uninit(&nxm);
3321
3322 /* Convert to and from OXM. */
3323 ofpbuf_init(&nxm, 0);
3324 nxm_match_len = oxm_put_match(&nxm, &match, OFP12_VERSION);
3325 nxm_s = oxm_match_to_string(&nxm, nxm_match_len);
3326 error = oxm_pull_match(&nxm, &nxm_match);
3327 printf("OXM: %s -> ", nxm_s);
3328 if (error) {
3329 printf("%s\n", ofperr_to_string(error));
3330 } else {
3331 uint16_t vid = ntohs(nxm_match.flow.vlan_tci) &
3332 (VLAN_VID_MASK | VLAN_CFI);
3333 uint16_t mask = ntohs(nxm_match.wc.masks.vlan_tci) &
3334 (VLAN_VID_MASK | VLAN_CFI);
3335
3336 printf("%04"PRIx16"/%04"PRIx16",", vid, mask);
3337 if (vid && vlan_tci_to_pcp(nxm_match.wc.masks.vlan_tci)) {
3338 printf("%02"PRIx8"\n", vlan_tci_to_pcp(nxm_match.flow.vlan_tci));
3339 } else {
3340 printf("--\n");
3341 }
3342 }
3343 free(nxm_s);
3344 ofpbuf_uninit(&nxm);
3345
3346 /* Convert to and from OpenFlow 1.0. */
3347 ofputil_match_to_ofp10_match(&match, &of10_raw);
3348 ofputil_match_from_ofp10_match(&of10_raw, &of10_match);
3349 printf("OF1.0: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
3350 ntohs(of10_raw.dl_vlan),
3351 (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN)) != 0,
3352 of10_raw.dl_vlan_pcp,
3353 (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN_PCP)) != 0,
3354 ntohs(of10_match.flow.vlan_tci),
3355 ntohs(of10_match.wc.masks.vlan_tci));
3356
3357 /* Convert to and from OpenFlow 1.1. */
3358 ofputil_match_to_ofp11_match(&match, &of11_raw);
3359 ofputil_match_from_ofp11_match(&of11_raw, &of11_match);
3360 printf("OF1.1: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
3361 ntohs(of11_raw.dl_vlan),
3362 (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN)) != 0,
3363 of11_raw.dl_vlan_pcp,
3364 (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN_PCP)) != 0,
3365 ntohs(of11_match.flow.vlan_tci),
3366 ntohs(of11_match.wc.masks.vlan_tci));
3367 }
3368
3369 /* "print-error ENUM": Prints the type and code of ENUM for every OpenFlow
3370 * version. */
3371 static void
3372 ofctl_print_error(int argc OVS_UNUSED, char *argv[])
3373 {
3374 enum ofperr error;
3375 int version;
3376
3377 error = ofperr_from_name(argv[1]);
3378 if (!error) {
3379 ovs_fatal(0, "unknown error \"%s\"", argv[1]);
3380 }
3381
3382 for (version = 0; version <= UINT8_MAX; version++) {
3383 const char *name = ofperr_domain_get_name(version);
3384 if (name) {
3385 int vendor = ofperr_get_vendor(error, version);
3386 int type = ofperr_get_type(error, version);
3387 int code = ofperr_get_code(error, version);
3388
3389 if (vendor != -1 || type != -1 || code != -1) {
3390 printf("%s: vendor %#x, type %d, code %d\n",
3391 name, vendor, type, code);
3392 }
3393 }
3394 }
3395 }
3396
3397 /* "encode-error-reply ENUM REQUEST": Encodes an error reply to REQUEST for the
3398 * error named ENUM and prints the error reply in hex. */
3399 static void
3400 ofctl_encode_error_reply(int argc OVS_UNUSED, char *argv[])
3401 {
3402 const struct ofp_header *oh;
3403 struct ofpbuf request, *reply;
3404 enum ofperr error;
3405
3406 error = ofperr_from_name(argv[1]);
3407 if (!error) {
3408 ovs_fatal(0, "unknown error \"%s\"", argv[1]);
3409 }
3410
3411 ofpbuf_init(&request, 0);
3412 if (ofpbuf_put_hex(&request, argv[2], NULL)[0] != '\0') {
3413 ovs_fatal(0, "Trailing garbage in hex data");
3414 }
3415 if (request.size < sizeof(struct ofp_header)) {
3416 ovs_fatal(0, "Request too short");
3417 }
3418
3419 oh = request.data;
3420 if (request.size != ntohs(oh->length)) {
3421 ovs_fatal(0, "Request size inconsistent");
3422 }
3423
3424 reply = ofperr_encode_reply(error, request.data);
3425 ofpbuf_uninit(&request);
3426
3427 ovs_hex_dump(stdout, reply->data, reply->size, 0, false);
3428 ofpbuf_delete(reply);
3429 }
3430
3431 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
3432 * binary data, interpreting them as an OpenFlow message, and prints the
3433 * OpenFlow message on stdout, at VERBOSITY (level 2 by default).
3434 *
3435 * Alternative usage: "ofp-print [VERBOSITY] - < HEXSTRING_FILE", where
3436 * HEXSTRING_FILE contains the HEXSTRING. */
3437 static void
3438 ofctl_ofp_print(int argc, char *argv[])
3439 {
3440 struct ofpbuf packet;
3441 char *buffer;
3442 int verbosity = 2;
3443 struct ds line;
3444
3445 ds_init(&line);
3446
3447 if (!strcmp(argv[argc-1], "-")) {
3448 if (ds_get_line(&line, stdin)) {
3449 VLOG_FATAL("Failed to read stdin");
3450 }
3451
3452 buffer = line.string;
3453 verbosity = argc > 2 ? atoi(argv[1]) : verbosity;
3454 } else if (argc > 2) {
3455 buffer = argv[1];
3456 verbosity = atoi(argv[2]);
3457 } else {
3458 buffer = argv[1];
3459 }
3460
3461 ofpbuf_init(&packet, strlen(buffer) / 2);
3462 if (ofpbuf_put_hex(&packet, buffer, NULL)[0] != '\0') {
3463 ovs_fatal(0, "trailing garbage following hex bytes");
3464 }
3465 ofp_print(stdout, packet.data, packet.size, verbosity);
3466 ofpbuf_uninit(&packet);
3467 ds_destroy(&line);
3468 }
3469
3470 /* "encode-hello BITMAP...": Encodes each BITMAP as an OpenFlow hello message
3471 * and dumps each message in hex. */
3472 static void
3473 ofctl_encode_hello(int argc OVS_UNUSED, char *argv[])
3474 {
3475 uint32_t bitmap = strtol(argv[1], NULL, 0);
3476 struct ofpbuf *hello;
3477
3478 hello = ofputil_encode_hello(bitmap);
3479 ovs_hex_dump(stdout, hello->data, hello->size, 0, false);
3480 ofp_print(stdout, hello->data, hello->size, verbosity);
3481 ofpbuf_delete(hello);
3482 }
3483
3484 static const struct command all_commands[] = {
3485 { "show", "switch",
3486 1, 1, ofctl_show },
3487 { "monitor", "switch [misslen] [invalid_ttl] [watch:[...]]",
3488 1, 3, ofctl_monitor },
3489 { "snoop", "switch",
3490 1, 1, ofctl_snoop },
3491 { "dump-desc", "switch",
3492 1, 1, ofctl_dump_desc },
3493 { "dump-tables", "switch",
3494 1, 1, ofctl_dump_tables },
3495 { "dump-table-features", "switch",
3496 1, 1, ofctl_dump_table_features },
3497 { "dump-flows", "switch",
3498 1, 2, ofctl_dump_flows },
3499 { "dump-aggregate", "switch",
3500 1, 2, ofctl_dump_aggregate },
3501 { "queue-stats", "switch [port [queue]]",
3502 1, 3, ofctl_queue_stats },
3503 { "queue-get-config", "switch port",
3504 2, 2, ofctl_queue_get_config },
3505 { "add-flow", "switch flow",
3506 2, 2, ofctl_add_flow },
3507 { "add-flows", "switch file",
3508 2, 2, ofctl_add_flows },
3509 { "mod-flows", "switch flow",
3510 2, 2, ofctl_mod_flows },
3511 { "del-flows", "switch [flow]",
3512 1, 2, ofctl_del_flows },
3513 { "replace-flows", "switch file",
3514 2, 2, ofctl_replace_flows },
3515 { "diff-flows", "source1 source2",
3516 2, 2, ofctl_diff_flows },
3517 { "add-meter", "switch meter",
3518 2, 2, ofctl_add_meter },
3519 { "mod-meter", "switch meter",
3520 2, 2, ofctl_mod_meter },
3521 { "del-meter", "switch meter",
3522 2, 2, ofctl_del_meters },
3523 { "del-meters", "switch",
3524 1, 1, ofctl_del_meters },
3525 { "dump-meter", "switch meter",
3526 2, 2, ofctl_dump_meters },
3527 { "dump-meters", "switch",
3528 1, 1, ofctl_dump_meters },
3529 { "meter-stats", "switch [meter]",
3530 1, 2, ofctl_meter_stats },
3531 { "meter-features", "switch",
3532 1, 1, ofctl_meter_features },
3533 { "packet-out", "switch in_port actions packet...",
3534 4, INT_MAX, ofctl_packet_out },
3535 { "dump-ports", "switch [port]",
3536 1, 2, ofctl_dump_ports },
3537 { "dump-ports-desc", "switch [port]",
3538 1, 2, ofctl_dump_ports_desc },
3539 { "mod-port", "switch iface act",
3540 3, 3, ofctl_mod_port },
3541 { "mod-table", "switch mod",
3542 3, 3, ofctl_mod_table },
3543 { "get-frags", "switch",
3544 1, 1, ofctl_get_frags },
3545 { "set-frags", "switch frag_mode",
3546 2, 2, ofctl_set_frags },
3547 { "probe", "target",
3548 1, 1, ofctl_probe },
3549 { "ping", "target [n]",
3550 1, 2, ofctl_ping },
3551 { "benchmark", "target n count",
3552 3, 3, ofctl_benchmark },
3553
3554 { "ofp-parse", "file",
3555 1, 1, ofctl_ofp_parse },
3556 { "ofp-parse-pcap", "pcap",
3557 1, INT_MAX, ofctl_ofp_parse_pcap },
3558
3559 { "add-group", "switch group",
3560 1, 2, ofctl_add_group },
3561 { "add-groups", "switch file",
3562 1, 2, ofctl_add_groups },
3563 { "mod-group", "switch group",
3564 1, 2, ofctl_mod_group },
3565 { "del-groups", "switch [group]",
3566 1, 2, ofctl_del_groups },
3567 { "insert-buckets", "switch [group]",
3568 1, 2, ofctl_insert_bucket },
3569 { "remove-buckets", "switch [group]",
3570 1, 2, ofctl_remove_bucket },
3571 { "dump-groups", "switch [group]",
3572 1, 2, ofctl_dump_group_desc },
3573 { "dump-group-stats", "switch [group]",
3574 1, 2, ofctl_dump_group_stats },
3575 { "dump-group-features", "switch",
3576 1, 1, ofctl_dump_group_features },
3577 { "help", NULL, 0, INT_MAX, ofctl_help },
3578 { "list-commands", NULL, 0, INT_MAX, ofctl_list_commands },
3579
3580 /* Undocumented commands for testing. */
3581 { "parse-flow", NULL, 1, 1, ofctl_parse_flow },
3582 { "parse-flows", NULL, 1, 1, ofctl_parse_flows },
3583 { "parse-nx-match", NULL, 0, 0, ofctl_parse_nxm },
3584 { "parse-nxm", NULL, 0, 0, ofctl_parse_nxm },
3585 { "parse-oxm", NULL, 1, 1, ofctl_parse_oxm },
3586 { "parse-actions", NULL, 1, 1, ofctl_parse_actions },
3587 { "parse-instructions", NULL, 1, 1, ofctl_parse_instructions },
3588 { "parse-ofp10-match", NULL, 0, 0, ofctl_parse_ofp10_match },
3589 { "parse-ofp11-match", NULL, 0, 0, ofctl_parse_ofp11_match },
3590 { "parse-pcap", NULL, 1, 1, ofctl_parse_pcap },
3591 { "check-vlan", NULL, 2, 2, ofctl_check_vlan },
3592 { "print-error", NULL, 1, 1, ofctl_print_error },
3593 { "encode-error-reply", NULL, 2, 2, ofctl_encode_error_reply },
3594 { "ofp-print", NULL, 1, 2, ofctl_ofp_print },
3595 { "encode-hello", NULL, 1, 1, ofctl_encode_hello },
3596
3597 { NULL, NULL, 0, 0, NULL },
3598 };
3599
3600 static const struct command *get_all_commands(void)
3601 {
3602 return all_commands;
3603 }