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