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