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