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