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