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