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