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