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