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