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