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