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