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