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