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