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