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