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