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