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