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