ovs-ofctl: Reject impossible protocols configurations at startup.
[sliver-openvswitch.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 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 <sys/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 "nx-match.h"
40 #include "odp-util.h"
41 #include "ofp-actions.h"
42 #include "ofp-errors.h"
43 #include "ofp-msgs.h"
44 #include "ofp-parse.h"
45 #include "ofp-print.h"
46 #include "ofp-util.h"
47 #include "ofp-version-opt.h"
48 #include "ofpbuf.h"
49 #include "ofproto/ofproto.h"
50 #include "openflow/nicira-ext.h"
51 #include "openflow/openflow.h"
52 #include "packets.h"
53 #include "poll-loop.h"
54 #include "random.h"
55 #include "stream-ssl.h"
56 #include "socket-util.h"
57 #include "timeval.h"
58 #include "unixctl.h"
59 #include "util.h"
60 #include "vconn.h"
61 #include "vlog.h"
62 #include "meta-flow.h"
63 #include "sort.h"
64
65 VLOG_DEFINE_THIS_MODULE(ofctl);
66
67 /* --strict: Use strict matching for flow mod commands?  Additionally governs
68  * use of nx_pull_match() instead of nx_pull_match_loose() in parse-nx-match.
69  */
70 static bool strict;
71
72 /* --readd: If true, on replace-flows, re-add even flows that have not changed
73  * (to reset flow counters). */
74 static bool readd;
75
76 /* -F, --flow-format: Allowed protocols.  By default, any protocol is
77  * allowed. */
78 static enum ofputil_protocol allowed_protocols = OFPUTIL_P_ANY;
79
80 /* -P, --packet-in-format: Packet IN format to use in monitor and snoop
81  * commands.  Either one of NXPIF_* to force a particular packet_in format, or
82  * -1 to let ovs-ofctl choose the default. */
83 static int preferred_packet_in_format = -1;
84
85 /* -m, --more: Additional verbosity for ofp-print functions. */
86 static int verbosity;
87
88 /* --timestamp: Print a timestamp before each received packet on "monitor" and
89  * "snoop" command? */
90 static bool timestamp;
91
92 /* --sort, --rsort: Sort order. */
93 enum sort_order { SORT_ASC, SORT_DESC };
94 struct sort_criterion {
95     const struct mf_field *field; /* NULL means to sort by priority. */
96     enum sort_order order;
97 };
98 static struct sort_criterion *criteria;
99 static size_t n_criteria, allocated_criteria;
100
101 static const struct command all_commands[];
102
103 static void usage(void) NO_RETURN;
104 static void parse_options(int argc, char *argv[]);
105
106 static bool recv_flow_stats_reply(struct vconn *, ovs_be32 send_xid,
107                                   struct ofpbuf **replyp,
108                                   struct ofputil_flow_stats *,
109                                   struct ofpbuf *ofpacts);
110 int
111 main(int argc, char *argv[])
112 {
113     set_program_name(argv[0]);
114     parse_options(argc, argv);
115     signal(SIGPIPE, SIG_IGN);
116     run_command(argc - optind, argv + optind, all_commands);
117     return 0;
118 }
119
120 static void
121 add_sort_criterion(enum sort_order order, const char *field)
122 {
123     struct sort_criterion *sc;
124
125     if (n_criteria >= allocated_criteria) {
126         criteria = x2nrealloc(criteria, &allocated_criteria, sizeof *criteria);
127     }
128
129     sc = &criteria[n_criteria++];
130     if (!field || !strcasecmp(field, "priority")) {
131         sc->field = NULL;
132     } else {
133         sc->field = mf_from_name(field);
134         if (!sc->field) {
135             ovs_fatal(0, "%s: unknown field name", field);
136         }
137     }
138     sc->order = order;
139 }
140
141 static void
142 parse_options(int argc, char *argv[])
143 {
144     enum {
145         OPT_STRICT = UCHAR_MAX + 1,
146         OPT_READD,
147         OPT_TIMESTAMP,
148         OPT_SORT,
149         OPT_RSORT,
150         DAEMON_OPTION_ENUMS,
151         OFP_VERSION_OPTION_ENUMS,
152         VLOG_OPTION_ENUMS
153     };
154     static struct option long_options[] = {
155         {"timeout", required_argument, NULL, 't'},
156         {"strict", no_argument, NULL, OPT_STRICT},
157         {"readd", no_argument, NULL, OPT_READD},
158         {"flow-format", required_argument, NULL, 'F'},
159         {"packet-in-format", required_argument, NULL, 'P'},
160         {"more", no_argument, NULL, 'm'},
161         {"timestamp", no_argument, NULL, OPT_TIMESTAMP},
162         {"sort", optional_argument, NULL, OPT_SORT},
163         {"rsort", optional_argument, NULL, OPT_RSORT},
164         {"help", no_argument, NULL, 'h'},
165         DAEMON_LONG_OPTIONS,
166         OFP_VERSION_LONG_OPTIONS,
167         VLOG_LONG_OPTIONS,
168         STREAM_SSL_LONG_OPTIONS,
169         {NULL, 0, NULL, 0},
170     };
171     char *short_options = long_options_to_short_options(long_options);
172     uint32_t versions;
173     enum ofputil_protocol version_protocols;
174
175     for (;;) {
176         unsigned long int timeout;
177         int c;
178
179         c = getopt_long(argc, argv, short_options, long_options, NULL);
180         if (c == -1) {
181             break;
182         }
183
184         switch (c) {
185         case 't':
186             timeout = strtoul(optarg, NULL, 10);
187             if (timeout <= 0) {
188                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
189                           optarg);
190             } else {
191                 time_alarm(timeout);
192             }
193             break;
194
195         case 'F':
196             allowed_protocols = ofputil_protocols_from_string(optarg);
197             if (!allowed_protocols) {
198                 ovs_fatal(0, "%s: invalid flow format(s)", optarg);
199             }
200             break;
201
202         case 'P':
203             preferred_packet_in_format =
204                 ofputil_packet_in_format_from_string(optarg);
205             if (preferred_packet_in_format < 0) {
206                 ovs_fatal(0, "unknown packet-in format `%s'", optarg);
207             }
208             break;
209
210         case 'm':
211             verbosity++;
212             break;
213
214         case 'h':
215             usage();
216
217         case OPT_STRICT:
218             strict = true;
219             break;
220
221         case OPT_READD:
222             readd = true;
223             break;
224
225         case OPT_TIMESTAMP:
226             timestamp = true;
227             break;
228
229         case OPT_SORT:
230             add_sort_criterion(SORT_ASC, optarg);
231             break;
232
233         case OPT_RSORT:
234             add_sort_criterion(SORT_DESC, optarg);
235             break;
236
237         DAEMON_OPTION_HANDLERS
238         OFP_VERSION_OPTION_HANDLERS
239         VLOG_OPTION_HANDLERS
240         STREAM_SSL_OPTION_HANDLERS
241
242         case '?':
243             exit(EXIT_FAILURE);
244
245         default:
246             abort();
247         }
248     }
249
250     if (n_criteria) {
251         /* Always do a final sort pass based on priority. */
252         add_sort_criterion(SORT_DESC, "priority");
253     }
254
255     free(short_options);
256
257     versions = get_allowed_ofp_versions();
258     version_protocols = ofputil_protocols_from_version_bitmap(versions);
259     if (!(allowed_protocols & version_protocols)) {
260         char *protocols = ofputil_protocols_to_string(allowed_protocols);
261         struct ds version_s = DS_EMPTY_INITIALIZER;
262
263         ofputil_format_version_bitmap_names(&version_s, versions);
264         ovs_fatal(0, "None of the enabled OpenFlow versions (%s) supports "
265                   "any of the enabled flow formats (%s).  (Use -O to enable "
266                   "additional OpenFlow versions or -F to enable additional "
267                   "flow formats.)", ds_cstr(&version_s), protocols);
268     }
269     allowed_protocols &= version_protocols;
270     mask_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
271                                   allowed_protocols));
272 }
273
274 static void
275 usage(void)
276 {
277     printf("%s: OpenFlow switch management utility\n"
278            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
279            "\nFor OpenFlow switches:\n"
280            "  show SWITCH                 show OpenFlow information\n"
281            "  dump-desc SWITCH            print switch description\n"
282            "  dump-tables SWITCH          print table stats\n"
283            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
284            "  get-frags SWITCH            print fragment handling behavior\n"
285            "  set-frags SWITCH FRAG_MODE  set fragment handling behavior\n"
286            "  dump-ports SWITCH [PORT]    print port statistics\n"
287            "  dump-ports-desc SWITCH      print port descriptions\n"
288            "  dump-flows SWITCH           print all flow entries\n"
289            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
290            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
291            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
292            "  queue-stats SWITCH [PORT [QUEUE]]  dump queue stats\n"
293            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
294            "  add-flows SWITCH FILE       add flows from FILE\n"
295            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
296            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
297            "  replace-flows SWITCH FILE   replace flows with those in FILE\n"
298            "  diff-flows SOURCE1 SOURCE2  compare flows from two sources\n"
299            "  packet-out SWITCH IN_PORT ACTIONS PACKET...\n"
300            "                              execute ACTIONS on PACKET\n"
301            "  monitor SWITCH [MISSLEN] [invalid_ttl] [watch:[...]]\n"
302            "                              print packets received from SWITCH\n"
303            "  snoop SWITCH                snoop on SWITCH and its controller\n"
304            "\nFor OpenFlow switches and controllers:\n"
305            "  probe TARGET                probe whether TARGET is up\n"
306            "  ping TARGET [N]             latency of N-byte echos\n"
307            "  benchmark TARGET N COUNT    bandwidth of COUNT N-byte echos\n"
308            "where SWITCH or TARGET is an active OpenFlow connection method.\n",
309            program_name, program_name);
310     vconn_usage(true, false, false);
311     daemon_usage();
312     ofp_version_usage();
313     vlog_usage();
314     printf("\nOther options:\n"
315            "  --strict                    use strict match for flow commands\n"
316            "  --readd                     replace flows that haven't changed\n"
317            "  -F, --flow-format=FORMAT    force particular flow format\n"
318            "  -P, --packet-in-format=FRMT force particular packet in format\n"
319            "  -m, --more                  be more verbose printing OpenFlow\n"
320            "  --timestamp                 (monitor, snoop) print timestamps\n"
321            "  -t, --timeout=SECS          give up after SECS seconds\n"
322            "  --sort[=field]              sort in ascending order\n"
323            "  --rsort[=field]             sort in descending order\n"
324            "  -h, --help                  display this help message\n"
325            "  -V, --version               display version information\n");
326     exit(EXIT_SUCCESS);
327 }
328
329 static void
330 ofctl_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
331            const char *argv[] OVS_UNUSED, void *exiting_)
332 {
333     bool *exiting = exiting_;
334     *exiting = true;
335     unixctl_command_reply(conn, NULL);
336 }
337
338 static void run(int retval, const char *message, ...)
339     PRINTF_FORMAT(2, 3);
340
341 static void
342 run(int retval, const char *message, ...)
343 {
344     if (retval) {
345         va_list args;
346
347         va_start(args, message);
348         ovs_fatal_valist(retval, message, args);
349     }
350 }
351 \f
352 /* Generic commands. */
353
354 static int
355 open_vconn_socket(const char *name, struct vconn **vconnp)
356 {
357     char *vconn_name = xasprintf("unix:%s", name);
358     int error;
359
360     error = vconn_open(vconn_name, get_allowed_ofp_versions(), vconnp,
361                        DSCP_DEFAULT);
362     if (error && error != ENOENT) {
363         ovs_fatal(0, "%s: failed to open socket (%s)", name,
364                   strerror(error));
365     }
366     free(vconn_name);
367
368     return error;
369 }
370
371 static enum ofputil_protocol
372 open_vconn__(const char *name, const char *default_suffix,
373              struct vconn **vconnp)
374 {
375     char *datapath_name, *datapath_type, *socket_name;
376     enum ofputil_protocol protocol;
377     char *bridge_path;
378     int ofp_version;
379     int error;
380
381     bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, default_suffix);
382
383     ofproto_parse_name(name, &datapath_name, &datapath_type);
384     socket_name = xasprintf("%s/%s.%s",
385                             ovs_rundir(), datapath_name, default_suffix);
386     free(datapath_name);
387     free(datapath_type);
388
389     if (strchr(name, ':')) {
390         run(vconn_open_block(name, get_allowed_ofp_versions(), vconnp),
391             "connecting to %s", name);
392     } else if (!open_vconn_socket(name, vconnp)) {
393         /* Fall Through. */
394     } else if (!open_vconn_socket(bridge_path, vconnp)) {
395         /* Fall Through. */
396     } else if (!open_vconn_socket(socket_name, vconnp)) {
397         /* Fall Through. */
398     } else {
399         ovs_fatal(0, "%s is not a bridge or a socket", name);
400     }
401
402     free(bridge_path);
403     free(socket_name);
404
405     VLOG_DBG("connecting to %s", vconn_get_name(*vconnp));
406     error = vconn_connect_block(*vconnp);
407     if (error) {
408         ovs_fatal(0, "%s: failed to connect to socket (%s)", name,
409                   strerror(error));
410     }
411
412     ofp_version = vconn_get_version(*vconnp);
413     protocol = ofputil_protocol_from_ofp_version(ofp_version);
414     if (!protocol) {
415         ovs_fatal(0, "%s: unsupported OpenFlow version 0x%02x",
416                   name, ofp_version);
417     }
418     return protocol;
419 }
420
421 static enum ofputil_protocol
422 open_vconn(const char *name, struct vconn **vconnp)
423 {
424     return open_vconn__(name, "mgmt", vconnp);
425 }
426
427 static void
428 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
429 {
430     ofpmsg_update_length(buffer);
431     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
432 }
433
434 static void
435 dump_transaction(struct vconn *vconn, struct ofpbuf *request)
436 {
437     struct ofpbuf *reply;
438
439     ofpmsg_update_length(request);
440     run(vconn_transact(vconn, request, &reply), "talking to %s",
441         vconn_get_name(vconn));
442     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
443     ofpbuf_delete(reply);
444 }
445
446 static void
447 dump_trivial_transaction(const char *vconn_name, enum ofpraw raw)
448 {
449     struct ofpbuf *request;
450     struct vconn *vconn;
451
452     open_vconn(vconn_name, &vconn);
453     request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
454     dump_transaction(vconn, request);
455     vconn_close(vconn);
456 }
457
458 static void
459 dump_stats_transaction(struct vconn *vconn, struct ofpbuf *request)
460 {
461     const struct ofp_header *request_oh = request->data;
462     ovs_be32 send_xid = request_oh->xid;
463     enum ofpraw request_raw;
464     enum ofpraw reply_raw;
465     bool done = false;
466
467     ofpraw_decode_partial(&request_raw, request->data, request->size);
468     reply_raw = ofpraw_stats_request_to_reply(request_raw,
469                                               request_oh->version);
470
471     send_openflow_buffer(vconn, request);
472     while (!done) {
473         ovs_be32 recv_xid;
474         struct ofpbuf *reply;
475
476         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
477         recv_xid = ((struct ofp_header *) reply->data)->xid;
478         if (send_xid == recv_xid) {
479             enum ofpraw raw;
480
481             ofp_print(stdout, reply->data, reply->size, verbosity + 1);
482
483             ofpraw_decode(&raw, reply->data);
484             if (ofptype_from_ofpraw(raw) == OFPTYPE_ERROR) {
485                 done = true;
486             } else if (raw == reply_raw) {
487                 done = !ofpmp_more(reply->data);
488             } else {
489                 ovs_fatal(0, "received bad reply: %s",
490                           ofp_to_string(reply->data, reply->size,
491                                         verbosity + 1));
492             }
493         } else {
494             VLOG_DBG("received reply with xid %08"PRIx32" "
495                      "!= expected %08"PRIx32, recv_xid, send_xid);
496         }
497         ofpbuf_delete(reply);
498     }
499 }
500
501 static void
502 dump_trivial_stats_transaction(const char *vconn_name, enum ofpraw raw)
503 {
504     struct ofpbuf *request;
505     struct vconn *vconn;
506
507     open_vconn(vconn_name, &vconn);
508     request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
509     dump_stats_transaction(vconn, request);
510     vconn_close(vconn);
511 }
512
513 /* Sends 'request', which should be a request that only has a reply if an error
514  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
515  * it and exits with an error.
516  *
517  * Destroys all of the 'requests'. */
518 static void
519 transact_multiple_noreply(struct vconn *vconn, struct list *requests)
520 {
521     struct ofpbuf *request, *reply;
522
523     LIST_FOR_EACH (request, list_node, requests) {
524         ofpmsg_update_length(request);
525     }
526
527     run(vconn_transact_multiple_noreply(vconn, requests, &reply),
528         "talking to %s", vconn_get_name(vconn));
529     if (reply) {
530         ofp_print(stderr, reply->data, reply->size, verbosity + 2);
531         exit(1);
532     }
533     ofpbuf_delete(reply);
534 }
535
536 /* Sends 'request', which should be a request that only has a reply if an error
537  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
538  * it and exits with an error.
539  *
540  * Destroys 'request'. */
541 static void
542 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
543 {
544     struct list requests;
545
546     list_init(&requests);
547     list_push_back(&requests, &request->list_node);
548     transact_multiple_noreply(vconn, &requests);
549 }
550
551 static void
552 fetch_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
553 {
554     struct ofp_switch_config *config;
555     struct ofpbuf *request;
556     struct ofpbuf *reply;
557     enum ofptype type;
558
559     request = ofpraw_alloc(OFPRAW_OFPT_GET_CONFIG_REQUEST,
560                            vconn_get_version(vconn), 0);
561     run(vconn_transact(vconn, request, &reply),
562         "talking to %s", vconn_get_name(vconn));
563
564     if (ofptype_pull(&type, reply) || type != OFPTYPE_GET_CONFIG_REPLY) {
565         ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
566     }
567
568     config = ofpbuf_pull(reply, sizeof *config);
569     *config_ = *config;
570
571     ofpbuf_delete(reply);
572 }
573
574 static void
575 set_switch_config(struct vconn *vconn, const struct ofp_switch_config *config)
576 {
577     struct ofpbuf *request;
578
579     request = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG, vconn_get_version(vconn), 0);
580     ofpbuf_put(request, config, sizeof *config);
581
582     transact_noreply(vconn, request);
583 }
584
585 static void
586 ofctl_show(int argc OVS_UNUSED, char *argv[])
587 {
588     const char *vconn_name = argv[1];
589     struct vconn *vconn;
590     struct ofpbuf *request;
591     struct ofpbuf *reply;
592     bool trunc;
593
594     open_vconn(vconn_name, &vconn);
595     request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST,
596                            vconn_get_version(vconn), 0);
597     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
598
599     trunc = ofputil_switch_features_ports_trunc(reply);
600     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
601
602     ofpbuf_delete(reply);
603
604     if (trunc) {
605         /* The Features Reply may not contain all the ports, so send a
606          * Port Description stats request, which doesn't have size
607          * constraints. */
608         dump_trivial_stats_transaction(vconn_name,
609                                        OFPRAW_OFPST_PORT_DESC_REQUEST);
610     }
611     dump_trivial_transaction(vconn_name, OFPRAW_OFPT_GET_CONFIG_REQUEST);
612     vconn_close(vconn);
613 }
614
615 static void
616 ofctl_dump_desc(int argc OVS_UNUSED, char *argv[])
617 {
618     dump_trivial_stats_transaction(argv[1], OFPRAW_OFPST_DESC_REQUEST);
619 }
620
621 static void
622 ofctl_dump_tables(int argc OVS_UNUSED, char *argv[])
623 {
624     dump_trivial_stats_transaction(argv[1], OFPRAW_OFPST_TABLE_REQUEST);
625 }
626
627 static bool
628 fetch_port_by_features(const char *vconn_name,
629                        const char *port_name, unsigned int port_no,
630                        struct ofputil_phy_port *pp, bool *trunc)
631 {
632     struct ofputil_switch_features features;
633     const struct ofp_header *oh;
634     struct ofpbuf *request, *reply;
635     struct vconn *vconn;
636     enum ofperr error;
637     enum ofptype type;
638     struct ofpbuf b;
639     bool found = false;
640
641     /* Fetch the switch's ofp_switch_features. */
642     open_vconn(vconn_name, &vconn);
643     request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST,
644                            vconn_get_version(vconn), 0);
645     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
646     vconn_close(vconn);
647
648     oh = reply->data;
649     if (ofptype_decode(&type, reply->data)
650         || type != OFPTYPE_FEATURES_REPLY) {
651         ovs_fatal(0, "%s: received bad features reply", vconn_name);
652     }
653
654     *trunc = false;
655     if (ofputil_switch_features_ports_trunc(reply)) {
656         *trunc = true;
657         goto exit;
658     }
659
660     error = ofputil_decode_switch_features(oh, &features, &b);
661     if (error) {
662         ovs_fatal(0, "%s: failed to decode features reply (%s)",
663                   vconn_name, ofperr_to_string(error));
664     }
665
666     while (!ofputil_pull_phy_port(oh->version, &b, pp)) {
667         if (port_no != UINT_MAX
668             ? port_no == pp->port_no
669             : !strcmp(pp->name, port_name)) {
670             found = true;
671             goto exit;
672         }
673     }
674
675 exit:
676     ofpbuf_delete(reply);
677     return found;
678 }
679
680 static bool
681 fetch_port_by_stats(const char *vconn_name,
682                     const char *port_name, unsigned int port_no,
683                     struct ofputil_phy_port *pp)
684 {
685     struct ofpbuf *request;
686     struct vconn *vconn;
687     ovs_be32 send_xid;
688     bool done = false;
689     bool found = false;
690
691     request = ofpraw_alloc(OFPRAW_OFPST_PORT_DESC_REQUEST, OFP10_VERSION, 0);
692     send_xid = ((struct ofp_header *) request->data)->xid;
693
694     open_vconn(vconn_name, &vconn);
695     send_openflow_buffer(vconn, request);
696     while (!done) {
697         ovs_be32 recv_xid;
698         struct ofpbuf *reply;
699
700         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
701         recv_xid = ((struct ofp_header *) reply->data)->xid;
702         if (send_xid == recv_xid) {
703             struct ofp_header *oh = reply->data;
704             enum ofptype type;
705             struct ofpbuf b;
706             uint16_t flags;
707
708             ofpbuf_use_const(&b, oh, ntohs(oh->length));
709             if (ofptype_pull(&type, &b)
710                 || type != OFPTYPE_PORT_DESC_STATS_REPLY) {
711                 ovs_fatal(0, "received bad reply: %s",
712                           ofp_to_string(reply->data, reply->size,
713                                         verbosity + 1));
714             }
715
716             flags = ofpmp_flags(oh);
717             done = !(flags & OFPSF_REPLY_MORE);
718
719             if (found) {
720                 /* We've already found the port, but we need to drain
721                  * the queue of any other replies for this request. */
722                 continue;
723             }
724
725             while (!ofputil_pull_phy_port(oh->version, &b, pp)) {
726                 if (port_no != UINT_MAX ? port_no == pp->port_no
727                                         : !strcmp(pp->name, port_name)) {
728                     found = true;
729                     break;
730                 }
731             }
732         } else {
733             VLOG_DBG("received reply with xid %08"PRIx32" "
734                      "!= expected %08"PRIx32, recv_xid, send_xid);
735         }
736         ofpbuf_delete(reply);
737     }
738     vconn_close(vconn);
739
740     return found;
741 }
742
743
744 /* Opens a connection to 'vconn_name', fetches the port structure for
745  * 'port_name' (which may be a port name or number), and copies it into
746  * '*pp'. */
747 static void
748 fetch_ofputil_phy_port(const char *vconn_name, const char *port_name,
749                        struct ofputil_phy_port *pp)
750 {
751     unsigned int port_no;
752     bool found;
753     bool trunc;
754
755     /* Try to interpret the argument as a port number. */
756     if (!str_to_uint(port_name, 10, &port_no)) {
757         port_no = UINT_MAX;
758     }
759
760     /* Try to find the port based on the Features Reply.  If it looks
761      * like the results may be truncated, then use the Port Description
762      * stats message introduced in OVS 1.7. */
763     found = fetch_port_by_features(vconn_name, port_name, port_no, pp,
764                                    &trunc);
765     if (trunc) {
766         found = fetch_port_by_stats(vconn_name, port_name, port_no, pp);
767     }
768
769     if (!found) {
770         ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
771     }
772 }
773
774 /* Returns the port number corresponding to 'port_name' (which may be a port
775  * name or number) within the switch 'vconn_name'. */
776 static uint16_t
777 str_to_port_no(const char *vconn_name, const char *port_name)
778 {
779     uint16_t port_no;
780
781     if (ofputil_port_from_string(port_name, &port_no)) {
782         return port_no;
783     } else {
784         struct ofputil_phy_port pp;
785
786         fetch_ofputil_phy_port(vconn_name, port_name, &pp);
787         return pp.port_no;
788     }
789 }
790
791 static bool
792 try_set_protocol(struct vconn *vconn, enum ofputil_protocol want,
793                  enum ofputil_protocol *cur)
794 {
795     for (;;) {
796         struct ofpbuf *request, *reply;
797         enum ofputil_protocol next;
798
799         request = ofputil_encode_set_protocol(*cur, want, &next);
800         if (!request) {
801             return *cur == want;
802         }
803
804         run(vconn_transact_noreply(vconn, request, &reply),
805             "talking to %s", vconn_get_name(vconn));
806         if (reply) {
807             char *s = ofp_to_string(reply->data, reply->size, 2);
808             VLOG_DBG("%s: failed to set protocol, switch replied: %s",
809                      vconn_get_name(vconn), s);
810             free(s);
811             ofpbuf_delete(reply);
812             return false;
813         }
814
815         *cur = next;
816     }
817 }
818
819 static enum ofputil_protocol
820 set_protocol_for_flow_dump(struct vconn *vconn,
821                            enum ofputil_protocol cur_protocol,
822                            enum ofputil_protocol usable_protocols)
823 {
824     char *usable_s;
825     int i;
826
827     for (i = 0; i < ofputil_n_flow_dump_protocols; i++) {
828         enum ofputil_protocol f = ofputil_flow_dump_protocols[i];
829         if (f & usable_protocols & allowed_protocols
830             && try_set_protocol(vconn, f, &cur_protocol)) {
831             return f;
832         }
833     }
834
835     usable_s = ofputil_protocols_to_string(usable_protocols);
836     if (usable_protocols & allowed_protocols) {
837         ovs_fatal(0, "switch does not support any of the usable flow "
838                   "formats (%s)", usable_s);
839     } else {
840         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
841         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
842                   "allowed flow formats (%s)", usable_s, allowed_s);
843     }
844 }
845
846 static struct vconn *
847 prepare_dump_flows(int argc, char *argv[], bool aggregate,
848                    struct ofpbuf **requestp)
849 {
850     enum ofputil_protocol usable_protocols, protocol;
851     struct ofputil_flow_stats_request fsr;
852     struct vconn *vconn;
853
854     parse_ofp_flow_stats_request_str(&fsr, aggregate, argc > 2 ? argv[2] : "");
855     usable_protocols = ofputil_flow_stats_request_usable_protocols(&fsr);
856
857     protocol = open_vconn(argv[1], &vconn);
858     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
859     *requestp = ofputil_encode_flow_stats_request(&fsr, protocol);
860     return vconn;
861 }
862
863 static void
864 ofctl_dump_flows__(int argc, char *argv[], bool aggregate)
865 {
866     struct ofpbuf *request;
867     struct vconn *vconn;
868
869     vconn = prepare_dump_flows(argc, argv, aggregate, &request);
870     dump_stats_transaction(vconn, request);
871     vconn_close(vconn);
872 }
873
874 static int
875 compare_flows(const void *afs_, const void *bfs_)
876 {
877     const struct ofputil_flow_stats *afs = afs_;
878     const struct ofputil_flow_stats *bfs = bfs_;
879     const struct match *a = &afs->match;
880     const struct match *b = &bfs->match;
881     const struct sort_criterion *sc;
882
883     for (sc = criteria; sc < &criteria[n_criteria]; sc++) {
884         const struct mf_field *f = sc->field;
885         int ret;
886
887         if (!f) {
888             unsigned int a_pri = afs->priority;
889             unsigned int b_pri = bfs->priority;
890             ret = a_pri < b_pri ? -1 : a_pri > b_pri;
891         } else {
892             bool ina, inb;
893
894             ina = mf_are_prereqs_ok(f, &a->flow) && !mf_is_all_wild(f, &a->wc);
895             inb = mf_are_prereqs_ok(f, &b->flow) && !mf_is_all_wild(f, &b->wc);
896             if (ina != inb) {
897                 /* Skip the test for sc->order, so that missing fields always
898                  * sort to the end whether we're sorting in ascending or
899                  * descending order. */
900                 return ina ? -1 : 1;
901             } else {
902                 union mf_value aval, bval;
903
904                 mf_get_value(f, &a->flow, &aval);
905                 mf_get_value(f, &b->flow, &bval);
906                 ret = memcmp(&aval, &bval, f->n_bytes);
907             }
908         }
909
910         if (ret) {
911             return sc->order == SORT_ASC ? ret : -ret;
912         }
913     }
914
915     return 0;
916 }
917
918 static void
919 ofctl_dump_flows(int argc, char *argv[])
920 {
921     if (!n_criteria) {
922         return ofctl_dump_flows__(argc, argv, false);
923     } else {
924         struct ofputil_flow_stats *fses;
925         size_t n_fses, allocated_fses;
926         struct ofpbuf *request;
927         struct ofpbuf ofpacts;
928         struct ofpbuf *reply;
929         struct vconn *vconn;
930         ovs_be32 send_xid;
931         struct ds s;
932         size_t i;
933
934         vconn = prepare_dump_flows(argc, argv, false, &request);
935         send_xid = ((struct ofp_header *) request->data)->xid;
936         send_openflow_buffer(vconn, request);
937
938         fses = NULL;
939         n_fses = allocated_fses = 0;
940         reply = NULL;
941         ofpbuf_init(&ofpacts, 0);
942         for (;;) {
943             struct ofputil_flow_stats *fs;
944
945             if (n_fses >= allocated_fses) {
946                 fses = x2nrealloc(fses, &allocated_fses, sizeof *fses);
947             }
948
949             fs = &fses[n_fses];
950             if (!recv_flow_stats_reply(vconn, send_xid, &reply, fs,
951                                        &ofpacts)) {
952                 break;
953             }
954             fs->ofpacts = xmemdup(fs->ofpacts, fs->ofpacts_len);
955             n_fses++;
956         }
957         ofpbuf_uninit(&ofpacts);
958
959         qsort(fses, n_fses, sizeof *fses, compare_flows);
960
961         ds_init(&s);
962         for (i = 0; i < n_fses; i++) {
963             ds_clear(&s);
964             ofp_print_flow_stats(&s, &fses[i]);
965             puts(ds_cstr(&s));
966         }
967         ds_destroy(&s);
968
969         for (i = 0; i < n_fses; i++) {
970             free(fses[i].ofpacts);
971         }
972         free(fses);
973
974         vconn_close(vconn);
975     }
976 }
977
978 static void
979 ofctl_dump_aggregate(int argc, char *argv[])
980 {
981     return ofctl_dump_flows__(argc, argv, true);
982 }
983
984 static void
985 ofctl_queue_stats(int argc, char *argv[])
986 {
987     struct ofpbuf *request;
988     struct vconn *vconn;
989     struct ofputil_queue_stats_request oqs;
990
991     open_vconn(argv[1], &vconn);
992
993     if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
994         oqs.port_no = str_to_port_no(argv[1], argv[2]);
995     } else {
996         oqs.port_no = OFPP_ANY;
997     }
998     if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
999         oqs.queue_id = atoi(argv[3]);
1000     } else {
1001         oqs.queue_id = OFPQ_ALL;
1002     }
1003
1004     request = ofputil_encode_queue_stats_request(vconn_get_version(vconn), &oqs);
1005     dump_stats_transaction(vconn, request);
1006     vconn_close(vconn);
1007 }
1008
1009 static enum ofputil_protocol
1010 open_vconn_for_flow_mod(const char *remote,
1011                         const struct ofputil_flow_mod *fms, size_t n_fms,
1012                         struct vconn **vconnp)
1013 {
1014     enum ofputil_protocol usable_protocols;
1015     enum ofputil_protocol cur_protocol;
1016     char *usable_s;
1017     int i;
1018
1019     /* Figure out what flow formats will work. */
1020     usable_protocols = ofputil_flow_mod_usable_protocols(fms, n_fms);
1021     if (!(usable_protocols & allowed_protocols)) {
1022         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
1023         usable_s = ofputil_protocols_to_string(usable_protocols);
1024         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
1025                   "allowed flow formats (%s)", usable_s, allowed_s);
1026     }
1027
1028     /* If the initial flow format is allowed and usable, keep it. */
1029     cur_protocol = open_vconn(remote, vconnp);
1030     if (usable_protocols & allowed_protocols & cur_protocol) {
1031         return cur_protocol;
1032     }
1033
1034     /* Otherwise try each flow format in turn. */
1035     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1036         enum ofputil_protocol f = 1 << i;
1037
1038         if (f != cur_protocol
1039             && f & usable_protocols & allowed_protocols
1040             && try_set_protocol(*vconnp, f, &cur_protocol)) {
1041             return f;
1042         }
1043     }
1044
1045     usable_s = ofputil_protocols_to_string(usable_protocols);
1046     ovs_fatal(0, "switch does not support any of the usable flow "
1047               "formats (%s)", usable_s);
1048 }
1049
1050 static void
1051 ofctl_flow_mod__(const char *remote, struct ofputil_flow_mod *fms,
1052                  size_t n_fms)
1053 {
1054     enum ofputil_protocol protocol;
1055     struct vconn *vconn;
1056     size_t i;
1057
1058     protocol = open_vconn_for_flow_mod(remote, fms, n_fms, &vconn);
1059
1060     for (i = 0; i < n_fms; i++) {
1061         struct ofputil_flow_mod *fm = &fms[i];
1062
1063         transact_noreply(vconn, ofputil_encode_flow_mod(fm, protocol));
1064         free(fm->ofpacts);
1065     }
1066     vconn_close(vconn);
1067 }
1068
1069 static void
1070 ofctl_flow_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
1071 {
1072     struct ofputil_flow_mod *fms = NULL;
1073     size_t n_fms = 0;
1074
1075     parse_ofp_flow_mod_file(argv[2], command, &fms, &n_fms);
1076     ofctl_flow_mod__(argv[1], fms, n_fms);
1077     free(fms);
1078 }
1079
1080 static void
1081 ofctl_flow_mod(int argc, char *argv[], uint16_t command)
1082 {
1083     if (argc > 2 && !strcmp(argv[2], "-")) {
1084         ofctl_flow_mod_file(argc, argv, command);
1085     } else {
1086         struct ofputil_flow_mod fm;
1087         parse_ofp_flow_mod_str(&fm, argc > 2 ? argv[2] : "", command, false);
1088         ofctl_flow_mod__(argv[1], &fm, 1);
1089     }
1090 }
1091
1092 static void
1093 ofctl_add_flow(int argc, char *argv[])
1094 {
1095     ofctl_flow_mod(argc, argv, OFPFC_ADD);
1096 }
1097
1098 static void
1099 ofctl_add_flows(int argc, char *argv[])
1100 {
1101     ofctl_flow_mod_file(argc, argv, OFPFC_ADD);
1102 }
1103
1104 static void
1105 ofctl_mod_flows(int argc, char *argv[])
1106 {
1107     ofctl_flow_mod(argc, argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
1108 }
1109
1110 static void
1111 ofctl_del_flows(int argc, char *argv[])
1112 {
1113     ofctl_flow_mod(argc, argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
1114 }
1115
1116 static void
1117 set_packet_in_format(struct vconn *vconn,
1118                      enum nx_packet_in_format packet_in_format)
1119 {
1120     struct ofpbuf *spif;
1121
1122     spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1123                                              packet_in_format);
1124     transact_noreply(vconn, spif);
1125     VLOG_DBG("%s: using user-specified packet in format %s",
1126              vconn_get_name(vconn),
1127              ofputil_packet_in_format_to_string(packet_in_format));
1128 }
1129
1130 static int
1131 monitor_set_invalid_ttl_to_controller(struct vconn *vconn)
1132 {
1133     struct ofp_switch_config config;
1134     enum ofp_config_flags flags;
1135
1136     fetch_switch_config(vconn, &config);
1137     flags = ntohs(config.flags);
1138     if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
1139         /* Set the invalid ttl config. */
1140         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
1141
1142         config.flags = htons(flags);
1143         set_switch_config(vconn, &config);
1144
1145         /* Then retrieve the configuration to see if it really took.  OpenFlow
1146          * doesn't define error reporting for bad modes, so this is all we can
1147          * do. */
1148         fetch_switch_config(vconn, &config);
1149         flags = ntohs(config.flags);
1150         if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
1151             ovs_fatal(0, "setting invalid_ttl_to_controller failed (this "
1152                       "switch probably doesn't support mode)");
1153             return -EOPNOTSUPP;
1154         }
1155     }
1156     return 0;
1157 }
1158
1159 /* Converts hex digits in 'hex' to an OpenFlow message in '*msgp'.  The
1160  * caller must free '*msgp'.  On success, returns NULL.  On failure, returns
1161  * an error message and stores NULL in '*msgp'. */
1162 static const char *
1163 openflow_from_hex(const char *hex, struct ofpbuf **msgp)
1164 {
1165     struct ofp_header *oh;
1166     struct ofpbuf *msg;
1167
1168     msg = ofpbuf_new(strlen(hex) / 2);
1169     *msgp = NULL;
1170
1171     if (ofpbuf_put_hex(msg, hex, NULL)[0] != '\0') {
1172         ofpbuf_delete(msg);
1173         return "Trailing garbage in hex data";
1174     }
1175
1176     if (msg->size < sizeof(struct ofp_header)) {
1177         ofpbuf_delete(msg);
1178         return "Message too short for OpenFlow";
1179     }
1180
1181     oh = msg->data;
1182     if (msg->size != ntohs(oh->length)) {
1183         ofpbuf_delete(msg);
1184         return "Message size does not match length in OpenFlow header";
1185     }
1186
1187     *msgp = msg;
1188     return NULL;
1189 }
1190
1191 static void
1192 ofctl_send(struct unixctl_conn *conn, int argc,
1193            const char *argv[], void *vconn_)
1194 {
1195     struct vconn *vconn = vconn_;
1196     struct ds reply;
1197     bool ok;
1198     int i;
1199
1200     ok = true;
1201     ds_init(&reply);
1202     for (i = 1; i < argc; i++) {
1203         const char *error_msg;
1204         struct ofpbuf *msg;
1205         int error;
1206
1207         error_msg = openflow_from_hex(argv[i], &msg);
1208         if (error_msg) {
1209             ds_put_format(&reply, "%s\n", error_msg);
1210             ok = false;
1211             continue;
1212         }
1213
1214         fprintf(stderr, "send: ");
1215         ofp_print(stderr, msg->data, msg->size, verbosity);
1216
1217         error = vconn_send_block(vconn, msg);
1218         if (error) {
1219             ofpbuf_delete(msg);
1220             ds_put_format(&reply, "%s\n", strerror(error));
1221             ok = false;
1222         } else {
1223             ds_put_cstr(&reply, "sent\n");
1224         }
1225     }
1226
1227     if (ok) {
1228         unixctl_command_reply(conn, ds_cstr(&reply));
1229     } else {
1230         unixctl_command_reply_error(conn, ds_cstr(&reply));
1231     }
1232     ds_destroy(&reply);
1233 }
1234
1235 struct barrier_aux {
1236     struct vconn *vconn;        /* OpenFlow connection for sending barrier. */
1237     struct unixctl_conn *conn;  /* Connection waiting for barrier response. */
1238 };
1239
1240 static void
1241 ofctl_barrier(struct unixctl_conn *conn, int argc OVS_UNUSED,
1242               const char *argv[] OVS_UNUSED, void *aux_)
1243 {
1244     struct barrier_aux *aux = aux_;
1245     struct ofpbuf *msg;
1246     int error;
1247
1248     if (aux->conn) {
1249         unixctl_command_reply_error(conn, "already waiting for barrier reply");
1250         return;
1251     }
1252
1253     msg = ofputil_encode_barrier_request(vconn_get_version(aux->vconn));
1254     error = vconn_send_block(aux->vconn, msg);
1255     if (error) {
1256         ofpbuf_delete(msg);
1257         unixctl_command_reply_error(conn, strerror(error));
1258     } else {
1259         aux->conn = conn;
1260     }
1261 }
1262
1263 static void
1264 ofctl_set_output_file(struct unixctl_conn *conn, int argc OVS_UNUSED,
1265                       const char *argv[], void *aux OVS_UNUSED)
1266 {
1267     int fd;
1268
1269     fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
1270     if (fd < 0) {
1271         unixctl_command_reply_error(conn, strerror(errno));
1272         return;
1273     }
1274
1275     fflush(stderr);
1276     dup2(fd, STDERR_FILENO);
1277     close(fd);
1278     unixctl_command_reply(conn, NULL);
1279 }
1280
1281 static void
1282 ofctl_block(struct unixctl_conn *conn, int argc OVS_UNUSED,
1283             const char *argv[] OVS_UNUSED, void *blocked_)
1284 {
1285     bool *blocked = blocked_;
1286
1287     if (!*blocked) {
1288         *blocked = true;
1289         unixctl_command_reply(conn, NULL);
1290     } else {
1291         unixctl_command_reply(conn, "already blocking");
1292     }
1293 }
1294
1295 static void
1296 ofctl_unblock(struct unixctl_conn *conn, int argc OVS_UNUSED,
1297               const char *argv[] OVS_UNUSED, void *blocked_)
1298 {
1299     bool *blocked = blocked_;
1300
1301     if (*blocked) {
1302         *blocked = false;
1303         unixctl_command_reply(conn, NULL);
1304     } else {
1305         unixctl_command_reply(conn, "already unblocked");
1306     }
1307 }
1308
1309 static void
1310 monitor_vconn(struct vconn *vconn)
1311 {
1312     struct barrier_aux barrier_aux = { vconn, NULL };
1313     struct unixctl_server *server;
1314     bool exiting = false;
1315     bool blocked = false;
1316     int error;
1317
1318     daemon_save_fd(STDERR_FILENO);
1319     daemonize_start();
1320     error = unixctl_server_create(NULL, &server);
1321     if (error) {
1322         ovs_fatal(error, "failed to create unixctl server");
1323     }
1324     unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
1325     unixctl_command_register("ofctl/send", "OFMSG...", 1, INT_MAX,
1326                              ofctl_send, vconn);
1327     unixctl_command_register("ofctl/barrier", "", 0, 0,
1328                              ofctl_barrier, &barrier_aux);
1329     unixctl_command_register("ofctl/set-output-file", "FILE", 1, 1,
1330                              ofctl_set_output_file, NULL);
1331
1332     unixctl_command_register("ofctl/block", "", 0, 0, ofctl_block, &blocked);
1333     unixctl_command_register("ofctl/unblock", "", 0, 0, ofctl_unblock,
1334                              &blocked);
1335
1336     daemonize_complete();
1337
1338     for (;;) {
1339         struct ofpbuf *b;
1340         int retval;
1341
1342         unixctl_server_run(server);
1343
1344         while (!blocked) {
1345             enum ofptype type;
1346
1347             retval = vconn_recv(vconn, &b);
1348             if (retval == EAGAIN) {
1349                 break;
1350             }
1351             run(retval, "vconn_recv");
1352
1353             if (timestamp) {
1354                 time_t now = time_wall();
1355                 char s[32];
1356
1357                 strftime(s, sizeof s, "%Y-%m-%d %H:%M:%S: ", gmtime(&now));
1358                 fputs(s, stderr);
1359             }
1360
1361             ofptype_decode(&type, b->data);
1362             ofp_print(stderr, b->data, b->size, verbosity + 2);
1363             ofpbuf_delete(b);
1364
1365             if (barrier_aux.conn && type == OFPTYPE_BARRIER_REPLY) {
1366                 unixctl_command_reply(barrier_aux.conn, NULL);
1367                 barrier_aux.conn = NULL;
1368             }
1369         }
1370
1371         if (exiting) {
1372             break;
1373         }
1374
1375         vconn_run(vconn);
1376         vconn_run_wait(vconn);
1377         if (!blocked) {
1378             vconn_recv_wait(vconn);
1379         }
1380         unixctl_server_wait(server);
1381         poll_block();
1382     }
1383     vconn_close(vconn);
1384     unixctl_server_destroy(server);
1385 }
1386
1387 static void
1388 ofctl_monitor(int argc, char *argv[])
1389 {
1390     struct vconn *vconn;
1391     int i;
1392
1393     open_vconn(argv[1], &vconn);
1394     for (i = 2; i < argc; i++) {
1395         const char *arg = argv[i];
1396
1397         if (isdigit((unsigned char) *arg)) {
1398             struct ofp_switch_config config;
1399
1400             fetch_switch_config(vconn, &config);
1401             config.miss_send_len = htons(atoi(arg));
1402             set_switch_config(vconn, &config);
1403         } else if (!strcmp(arg, "invalid_ttl")) {
1404             monitor_set_invalid_ttl_to_controller(vconn);
1405         } else if (!strncmp(arg, "watch:", 6)) {
1406             struct ofputil_flow_monitor_request fmr;
1407             struct ofpbuf *msg;
1408
1409             parse_flow_monitor_request(&fmr, arg + 6);
1410
1411             msg = ofpbuf_new(0);
1412             ofputil_append_flow_monitor_request(&fmr, msg);
1413             dump_stats_transaction(vconn, msg);
1414         } else {
1415             ovs_fatal(0, "%s: unsupported \"monitor\" argument", arg);
1416         }
1417     }
1418
1419     if (preferred_packet_in_format >= 0) {
1420         set_packet_in_format(vconn, preferred_packet_in_format);
1421     } else {
1422         struct ofpbuf *spif, *reply;
1423
1424         spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1425                                                  NXPIF_NXM);
1426         run(vconn_transact_noreply(vconn, spif, &reply),
1427             "talking to %s", vconn_get_name(vconn));
1428         if (reply) {
1429             char *s = ofp_to_string(reply->data, reply->size, 2);
1430             VLOG_DBG("%s: failed to set packet in format to nxm, controller"
1431                      " replied: %s. Falling back to the switch default.",
1432                      vconn_get_name(vconn), s);
1433             free(s);
1434             ofpbuf_delete(reply);
1435         }
1436     }
1437
1438     monitor_vconn(vconn);
1439 }
1440
1441 static void
1442 ofctl_snoop(int argc OVS_UNUSED, char *argv[])
1443 {
1444     struct vconn *vconn;
1445
1446     open_vconn__(argv[1], "snoop", &vconn);
1447     monitor_vconn(vconn);
1448 }
1449
1450 static void
1451 ofctl_dump_ports(int argc, char *argv[])
1452 {
1453     struct ofpbuf *request;
1454     struct vconn *vconn;
1455     uint16_t port;
1456
1457     open_vconn(argv[1], &vconn);
1458     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_ANY;
1459     request = ofputil_encode_dump_ports_request(vconn_get_version(vconn), port);
1460     dump_stats_transaction(vconn, request);
1461     vconn_close(vconn);
1462 }
1463
1464 static void
1465 ofctl_dump_ports_desc(int argc OVS_UNUSED, char *argv[])
1466 {
1467     dump_trivial_stats_transaction(argv[1], OFPRAW_OFPST_PORT_DESC_REQUEST);
1468 }
1469
1470 static void
1471 ofctl_probe(int argc OVS_UNUSED, char *argv[])
1472 {
1473     struct ofpbuf *request;
1474     struct vconn *vconn;
1475     struct ofpbuf *reply;
1476
1477     open_vconn(argv[1], &vconn);
1478     request = make_echo_request(vconn_get_version(vconn));
1479     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1480     if (reply->size != sizeof(struct ofp_header)) {
1481         ovs_fatal(0, "reply does not match request");
1482     }
1483     ofpbuf_delete(reply);
1484     vconn_close(vconn);
1485 }
1486
1487 static void
1488 ofctl_packet_out(int argc, char *argv[])
1489 {
1490     enum ofputil_protocol protocol;
1491     struct ofputil_packet_out po;
1492     struct ofpbuf ofpacts;
1493     struct vconn *vconn;
1494     int i;
1495
1496     ofpbuf_init(&ofpacts, 64);
1497     parse_ofpacts(argv[3], &ofpacts);
1498
1499     po.buffer_id = UINT32_MAX;
1500     po.in_port = str_to_port_no(argv[1], argv[2]);
1501     po.ofpacts = ofpacts.data;
1502     po.ofpacts_len = ofpacts.size;
1503
1504     protocol = open_vconn(argv[1], &vconn);
1505     for (i = 4; i < argc; i++) {
1506         struct ofpbuf *packet, *opo;
1507         const char *error_msg;
1508
1509         error_msg = eth_from_hex(argv[i], &packet);
1510         if (error_msg) {
1511             ovs_fatal(0, "%s", error_msg);
1512         }
1513
1514         po.packet = packet->data;
1515         po.packet_len = packet->size;
1516         opo = ofputil_encode_packet_out(&po, protocol);
1517         transact_noreply(vconn, opo);
1518         ofpbuf_delete(packet);
1519     }
1520     vconn_close(vconn);
1521     ofpbuf_uninit(&ofpacts);
1522 }
1523
1524 static void
1525 ofctl_mod_port(int argc OVS_UNUSED, char *argv[])
1526 {
1527     struct ofp_config_flag {
1528         const char *name;             /* The flag's name. */
1529         enum ofputil_port_config bit; /* Bit to turn on or off. */
1530         bool on;                      /* Value to set the bit to. */
1531     };
1532     static const struct ofp_config_flag flags[] = {
1533         { "up",          OFPUTIL_PC_PORT_DOWN,    false },
1534         { "down",        OFPUTIL_PC_PORT_DOWN,    true  },
1535         { "stp",         OFPUTIL_PC_NO_STP,       false },
1536         { "receive",     OFPUTIL_PC_NO_RECV,      false },
1537         { "receive-stp", OFPUTIL_PC_NO_RECV_STP,  false },
1538         { "flood",       OFPUTIL_PC_NO_FLOOD,     false },
1539         { "forward",     OFPUTIL_PC_NO_FWD,       false },
1540         { "packet-in",   OFPUTIL_PC_NO_PACKET_IN, false },
1541     };
1542
1543     const struct ofp_config_flag *flag;
1544     enum ofputil_protocol protocol;
1545     struct ofputil_port_mod pm;
1546     struct ofputil_phy_port pp;
1547     struct vconn *vconn;
1548     const char *command;
1549     bool not;
1550
1551     fetch_ofputil_phy_port(argv[1], argv[2], &pp);
1552
1553     pm.port_no = pp.port_no;
1554     memcpy(pm.hw_addr, pp.hw_addr, ETH_ADDR_LEN);
1555     pm.config = 0;
1556     pm.mask = 0;
1557     pm.advertise = 0;
1558
1559     if (!strncasecmp(argv[3], "no-", 3)) {
1560         command = argv[3] + 3;
1561         not = true;
1562     } else if (!strncasecmp(argv[3], "no", 2)) {
1563         command = argv[3] + 2;
1564         not = true;
1565     } else {
1566         command = argv[3];
1567         not = false;
1568     }
1569     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1570         if (!strcasecmp(command, flag->name)) {
1571             pm.mask = flag->bit;
1572             pm.config = flag->on ^ not ? flag->bit : 0;
1573             goto found;
1574         }
1575     }
1576     ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1577
1578 found:
1579     protocol = open_vconn(argv[1], &vconn);
1580     transact_noreply(vconn, ofputil_encode_port_mod(&pm, protocol));
1581     vconn_close(vconn);
1582 }
1583
1584 static void
1585 ofctl_get_frags(int argc OVS_UNUSED, char *argv[])
1586 {
1587     struct ofp_switch_config config;
1588     struct vconn *vconn;
1589
1590     open_vconn(argv[1], &vconn);
1591     fetch_switch_config(vconn, &config);
1592     puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
1593     vconn_close(vconn);
1594 }
1595
1596 static void
1597 ofctl_set_frags(int argc OVS_UNUSED, char *argv[])
1598 {
1599     struct ofp_switch_config config;
1600     enum ofp_config_flags mode;
1601     struct vconn *vconn;
1602     ovs_be16 flags;
1603
1604     if (!ofputil_frag_handling_from_string(argv[2], &mode)) {
1605         ovs_fatal(0, "%s: unknown fragment handling mode", argv[2]);
1606     }
1607
1608     open_vconn(argv[1], &vconn);
1609     fetch_switch_config(vconn, &config);
1610     flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
1611     if (flags != config.flags) {
1612         /* Set the configuration. */
1613         config.flags = flags;
1614         set_switch_config(vconn, &config);
1615
1616         /* Then retrieve the configuration to see if it really took.  OpenFlow
1617          * doesn't define error reporting for bad modes, so this is all we can
1618          * do. */
1619         fetch_switch_config(vconn, &config);
1620         if (flags != config.flags) {
1621             ovs_fatal(0, "%s: setting fragment handling mode failed (this "
1622                       "switch probably doesn't support mode \"%s\")",
1623                       argv[1], ofputil_frag_handling_to_string(mode));
1624         }
1625     }
1626     vconn_close(vconn);
1627 }
1628
1629 static void
1630 ofctl_ping(int argc, char *argv[])
1631 {
1632     size_t max_payload = 65535 - sizeof(struct ofp_header);
1633     unsigned int payload;
1634     struct vconn *vconn;
1635     int i;
1636
1637     payload = argc > 2 ? atoi(argv[2]) : 64;
1638     if (payload > max_payload) {
1639         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1640     }
1641
1642     open_vconn(argv[1], &vconn);
1643     for (i = 0; i < 10; i++) {
1644         struct timeval start, end;
1645         struct ofpbuf *request, *reply;
1646         const struct ofp_header *rpy_hdr;
1647         enum ofptype type;
1648
1649         request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
1650                                vconn_get_version(vconn), payload);
1651         random_bytes(ofpbuf_put_uninit(request, payload), payload);
1652
1653         xgettimeofday(&start);
1654         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1655         xgettimeofday(&end);
1656
1657         rpy_hdr = reply->data;
1658         if (ofptype_pull(&type, reply)
1659             || type != OFPTYPE_ECHO_REPLY
1660             || reply->size != payload
1661             || memcmp(request->l3, reply->l3, payload)) {
1662             printf("Reply does not match request.  Request:\n");
1663             ofp_print(stdout, request, request->size, verbosity + 2);
1664             printf("Reply:\n");
1665             ofp_print(stdout, reply, reply->size, verbosity + 2);
1666         }
1667         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1668                reply->size, argv[1], ntohl(rpy_hdr->xid),
1669                    (1000*(double)(end.tv_sec - start.tv_sec))
1670                    + (.001*(end.tv_usec - start.tv_usec)));
1671         ofpbuf_delete(request);
1672         ofpbuf_delete(reply);
1673     }
1674     vconn_close(vconn);
1675 }
1676
1677 static void
1678 ofctl_benchmark(int argc OVS_UNUSED, char *argv[])
1679 {
1680     size_t max_payload = 65535 - sizeof(struct ofp_header);
1681     struct timeval start, end;
1682     unsigned int payload_size, message_size;
1683     struct vconn *vconn;
1684     double duration;
1685     int count;
1686     int i;
1687
1688     payload_size = atoi(argv[2]);
1689     if (payload_size > max_payload) {
1690         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1691     }
1692     message_size = sizeof(struct ofp_header) + payload_size;
1693
1694     count = atoi(argv[3]);
1695
1696     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1697            count, message_size, count * message_size);
1698
1699     open_vconn(argv[1], &vconn);
1700     xgettimeofday(&start);
1701     for (i = 0; i < count; i++) {
1702         struct ofpbuf *request, *reply;
1703
1704         request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
1705                                vconn_get_version(vconn), payload_size);
1706         ofpbuf_put_zeros(request, payload_size);
1707         run(vconn_transact(vconn, request, &reply), "transact");
1708         ofpbuf_delete(reply);
1709     }
1710     xgettimeofday(&end);
1711     vconn_close(vconn);
1712
1713     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1714                 + (.001*(end.tv_usec - start.tv_usec)));
1715     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1716            duration, count / (duration / 1000.0),
1717            count * message_size / (duration / 1000.0));
1718 }
1719
1720 static void
1721 ofctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1722 {
1723     usage();
1724 }
1725 \f
1726 /* replace-flows and diff-flows commands. */
1727
1728 /* A flow table entry, possibly with two different versions. */
1729 struct fte {
1730     struct cls_rule rule;       /* Within a "struct classifier". */
1731     struct fte_version *versions[2];
1732 };
1733
1734 /* One version of a Flow Table Entry. */
1735 struct fte_version {
1736     ovs_be64 cookie;
1737     uint16_t idle_timeout;
1738     uint16_t hard_timeout;
1739     uint16_t flags;
1740     struct ofpact *ofpacts;
1741     size_t ofpacts_len;
1742 };
1743
1744 /* Frees 'version' and the data that it owns. */
1745 static void
1746 fte_version_free(struct fte_version *version)
1747 {
1748     if (version) {
1749         free(version->ofpacts);
1750         free(version);
1751     }
1752 }
1753
1754 /* Returns true if 'a' and 'b' are the same, false if they differ.
1755  *
1756  * Ignores differences in 'flags' because there's no way to retrieve flags from
1757  * an OpenFlow switch.  We have to assume that they are the same. */
1758 static bool
1759 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
1760 {
1761     return (a->cookie == b->cookie
1762             && a->idle_timeout == b->idle_timeout
1763             && a->hard_timeout == b->hard_timeout
1764             && ofpacts_equal(a->ofpacts, a->ofpacts_len,
1765                              b->ofpacts, b->ofpacts_len));
1766 }
1767
1768 /* Clears 's', then if 's' has a version 'index', formats 'fte' and version
1769  * 'index' into 's', followed by a new-line. */
1770 static void
1771 fte_version_format(const struct fte *fte, int index, struct ds *s)
1772 {
1773     const struct fte_version *version = fte->versions[index];
1774
1775     ds_clear(s);
1776     if (!version) {
1777         return;
1778     }
1779
1780     cls_rule_format(&fte->rule, s);
1781     if (version->cookie != htonll(0)) {
1782         ds_put_format(s, " cookie=0x%"PRIx64, ntohll(version->cookie));
1783     }
1784     if (version->idle_timeout != OFP_FLOW_PERMANENT) {
1785         ds_put_format(s, " idle_timeout=%"PRIu16, version->idle_timeout);
1786     }
1787     if (version->hard_timeout != OFP_FLOW_PERMANENT) {
1788         ds_put_format(s, " hard_timeout=%"PRIu16, version->hard_timeout);
1789     }
1790
1791     ds_put_char(s, ' ');
1792     ofpacts_format(version->ofpacts, version->ofpacts_len, s);
1793
1794     ds_put_char(s, '\n');
1795 }
1796
1797 static struct fte *
1798 fte_from_cls_rule(const struct cls_rule *cls_rule)
1799 {
1800     return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
1801 }
1802
1803 /* Frees 'fte' and its versions. */
1804 static void
1805 fte_free(struct fte *fte)
1806 {
1807     if (fte) {
1808         fte_version_free(fte->versions[0]);
1809         fte_version_free(fte->versions[1]);
1810         cls_rule_destroy(&fte->rule);
1811         free(fte);
1812     }
1813 }
1814
1815 /* Frees all of the FTEs within 'cls'. */
1816 static void
1817 fte_free_all(struct classifier *cls)
1818 {
1819     struct cls_cursor cursor;
1820     struct fte *fte, *next;
1821
1822     cls_cursor_init(&cursor, cls, NULL);
1823     CLS_CURSOR_FOR_EACH_SAFE (fte, next, rule, &cursor) {
1824         classifier_remove(cls, &fte->rule);
1825         fte_free(fte);
1826     }
1827     classifier_destroy(cls);
1828 }
1829
1830 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
1831  * necessary.  Sets 'version' as the version of that rule with the given
1832  * 'index', replacing any existing version, if any.
1833  *
1834  * Takes ownership of 'version'. */
1835 static void
1836 fte_insert(struct classifier *cls, const struct match *match,
1837            unsigned int priority, struct fte_version *version, int index)
1838 {
1839     struct fte *old, *fte;
1840
1841     fte = xzalloc(sizeof *fte);
1842     cls_rule_init(&fte->rule, match, priority);
1843     fte->versions[index] = version;
1844
1845     old = fte_from_cls_rule(classifier_replace(cls, &fte->rule));
1846     if (old) {
1847         fte_version_free(old->versions[index]);
1848         fte->versions[!index] = old->versions[!index];
1849         cls_rule_destroy(&old->rule);
1850         free(old);
1851     }
1852 }
1853
1854 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
1855  * with the specified 'index'.  Returns the flow formats able to represent the
1856  * flows that were read. */
1857 static enum ofputil_protocol
1858 read_flows_from_file(const char *filename, struct classifier *cls, int index)
1859 {
1860     enum ofputil_protocol usable_protocols;
1861     struct ds s;
1862     FILE *file;
1863
1864     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
1865     if (file == NULL) {
1866         ovs_fatal(errno, "%s: open", filename);
1867     }
1868
1869     ds_init(&s);
1870     usable_protocols = OFPUTIL_P_ANY;
1871     while (!ds_get_preprocessed_line(&s, file)) {
1872         struct fte_version *version;
1873         struct ofputil_flow_mod fm;
1874
1875         parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), true);
1876
1877         version = xmalloc(sizeof *version);
1878         version->cookie = fm.new_cookie;
1879         version->idle_timeout = fm.idle_timeout;
1880         version->hard_timeout = fm.hard_timeout;
1881         version->flags = fm.flags & (OFPFF_SEND_FLOW_REM | OFPFF10_EMERG);
1882         version->ofpacts = fm.ofpacts;
1883         version->ofpacts_len = fm.ofpacts_len;
1884
1885         usable_protocols &= ofputil_usable_protocols(&fm.match);
1886
1887         fte_insert(cls, &fm.match, fm.priority, version, index);
1888     }
1889     ds_destroy(&s);
1890
1891     if (file != stdin) {
1892         fclose(file);
1893     }
1894
1895     return usable_protocols;
1896 }
1897
1898 static bool
1899 recv_flow_stats_reply(struct vconn *vconn, ovs_be32 send_xid,
1900                       struct ofpbuf **replyp,
1901                       struct ofputil_flow_stats *fs, struct ofpbuf *ofpacts)
1902 {
1903     struct ofpbuf *reply = *replyp;
1904
1905     for (;;) {
1906         int retval;
1907         bool more;
1908
1909         /* Get a flow stats reply message, if we don't already have one. */
1910         if (!reply) {
1911             enum ofptype type;
1912             enum ofperr error;
1913
1914             do {
1915                 run(vconn_recv_block(vconn, &reply),
1916                     "OpenFlow packet receive failed");
1917             } while (((struct ofp_header *) reply->data)->xid != send_xid);
1918
1919             error = ofptype_decode(&type, reply->data);
1920             if (error || type != OFPTYPE_FLOW_STATS_REPLY) {
1921                 ovs_fatal(0, "received bad reply: %s",
1922                           ofp_to_string(reply->data, reply->size,
1923                                         verbosity + 1));
1924             }
1925         }
1926
1927         /* Pull an individual flow stats reply out of the message. */
1928         retval = ofputil_decode_flow_stats_reply(fs, reply, false, ofpacts);
1929         switch (retval) {
1930         case 0:
1931             *replyp = reply;
1932             return true;
1933
1934         case EOF:
1935             more = ofpmp_more(reply->l2);
1936             ofpbuf_delete(reply);
1937             reply = NULL;
1938             if (!more) {
1939                 *replyp = NULL;
1940                 return false;
1941             }
1942             break;
1943
1944         default:
1945             ovs_fatal(0, "parse error in reply (%s)",
1946                       ofperr_to_string(retval));
1947         }
1948     }
1949 }
1950
1951 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
1952  * format 'protocol', and adds them as flow table entries in 'cls' for the
1953  * version with the specified 'index'. */
1954 static void
1955 read_flows_from_switch(struct vconn *vconn,
1956                        enum ofputil_protocol protocol,
1957                        struct classifier *cls, int index)
1958 {
1959     struct ofputil_flow_stats_request fsr;
1960     struct ofputil_flow_stats fs;
1961     struct ofpbuf *request;
1962     struct ofpbuf ofpacts;
1963     struct ofpbuf *reply;
1964     ovs_be32 send_xid;
1965
1966     fsr.aggregate = false;
1967     match_init_catchall(&fsr.match);
1968     fsr.out_port = OFPP_ANY;
1969     fsr.table_id = 0xff;
1970     fsr.cookie = fsr.cookie_mask = htonll(0);
1971     request = ofputil_encode_flow_stats_request(&fsr, protocol);
1972     send_xid = ((struct ofp_header *) request->data)->xid;
1973     send_openflow_buffer(vconn, request);
1974
1975     reply = NULL;
1976     ofpbuf_init(&ofpacts, 0);
1977     while (recv_flow_stats_reply(vconn, send_xid, &reply, &fs, &ofpacts)) {
1978         struct fte_version *version;
1979
1980         version = xmalloc(sizeof *version);
1981         version->cookie = fs.cookie;
1982         version->idle_timeout = fs.idle_timeout;
1983         version->hard_timeout = fs.hard_timeout;
1984         version->flags = 0;
1985         version->ofpacts_len = fs.ofpacts_len;
1986         version->ofpacts = xmemdup(fs.ofpacts, fs.ofpacts_len);
1987
1988         fte_insert(cls, &fs.match, fs.priority, version, index);
1989     }
1990     ofpbuf_uninit(&ofpacts);
1991 }
1992
1993 static void
1994 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
1995                   enum ofputil_protocol protocol, struct list *packets)
1996 {
1997     const struct fte_version *version = fte->versions[index];
1998     struct ofputil_flow_mod fm;
1999     struct ofpbuf *ofm;
2000
2001     minimatch_expand(&fte->rule.match, &fm.match);
2002     fm.priority = fte->rule.priority;
2003     fm.cookie = htonll(0);
2004     fm.cookie_mask = htonll(0);
2005     fm.new_cookie = version->cookie;
2006     fm.table_id = 0xff;
2007     fm.command = command;
2008     fm.idle_timeout = version->idle_timeout;
2009     fm.hard_timeout = version->hard_timeout;
2010     fm.buffer_id = UINT32_MAX;
2011     fm.out_port = OFPP_ANY;
2012     fm.flags = version->flags;
2013     if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
2014         command == OFPFC_MODIFY_STRICT) {
2015         fm.ofpacts = version->ofpacts;
2016         fm.ofpacts_len = version->ofpacts_len;
2017     } else {
2018         fm.ofpacts = NULL;
2019         fm.ofpacts_len = 0;
2020     }
2021
2022     ofm = ofputil_encode_flow_mod(&fm, protocol);
2023     list_push_back(packets, &ofm->list_node);
2024 }
2025
2026 static void
2027 ofctl_replace_flows(int argc OVS_UNUSED, char *argv[])
2028 {
2029     enum { FILE_IDX = 0, SWITCH_IDX = 1 };
2030     enum ofputil_protocol usable_protocols, protocol;
2031     struct cls_cursor cursor;
2032     struct classifier cls;
2033     struct list requests;
2034     struct vconn *vconn;
2035     struct fte *fte;
2036
2037     classifier_init(&cls);
2038     usable_protocols = read_flows_from_file(argv[2], &cls, FILE_IDX);
2039
2040     protocol = open_vconn(argv[1], &vconn);
2041     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
2042
2043     read_flows_from_switch(vconn, protocol, &cls, SWITCH_IDX);
2044
2045     list_init(&requests);
2046
2047     /* Delete flows that exist on the switch but not in the file. */
2048     cls_cursor_init(&cursor, &cls, NULL);
2049     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
2050         struct fte_version *file_ver = fte->versions[FILE_IDX];
2051         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
2052
2053         if (sw_ver && !file_ver) {
2054             fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
2055                               protocol, &requests);
2056         }
2057     }
2058
2059     /* Add flows that exist in the file but not on the switch.
2060      * Update flows that exist in both places but differ. */
2061     cls_cursor_init(&cursor, &cls, NULL);
2062     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
2063         struct fte_version *file_ver = fte->versions[FILE_IDX];
2064         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
2065
2066         if (file_ver
2067             && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
2068             fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, protocol, &requests);
2069         }
2070     }
2071     transact_multiple_noreply(vconn, &requests);
2072     vconn_close(vconn);
2073
2074     fte_free_all(&cls);
2075 }
2076
2077 static void
2078 read_flows_from_source(const char *source, struct classifier *cls, int index)
2079 {
2080     struct stat s;
2081
2082     if (source[0] == '/' || source[0] == '.'
2083         || (!strchr(source, ':') && !stat(source, &s))) {
2084         read_flows_from_file(source, cls, index);
2085     } else {
2086         enum ofputil_protocol protocol;
2087         struct vconn *vconn;
2088
2089         protocol = open_vconn(source, &vconn);
2090         protocol = set_protocol_for_flow_dump(vconn, protocol, OFPUTIL_P_ANY);
2091         read_flows_from_switch(vconn, protocol, cls, index);
2092         vconn_close(vconn);
2093     }
2094 }
2095
2096 static void
2097 ofctl_diff_flows(int argc OVS_UNUSED, char *argv[])
2098 {
2099     bool differences = false;
2100     struct cls_cursor cursor;
2101     struct classifier cls;
2102     struct ds a_s, b_s;
2103     struct fte *fte;
2104
2105     classifier_init(&cls);
2106     read_flows_from_source(argv[1], &cls, 0);
2107     read_flows_from_source(argv[2], &cls, 1);
2108
2109     ds_init(&a_s);
2110     ds_init(&b_s);
2111
2112     cls_cursor_init(&cursor, &cls, NULL);
2113     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
2114         struct fte_version *a = fte->versions[0];
2115         struct fte_version *b = fte->versions[1];
2116
2117         if (!a || !b || !fte_version_equals(a, b)) {
2118             fte_version_format(fte, 0, &a_s);
2119             fte_version_format(fte, 1, &b_s);
2120             if (strcmp(ds_cstr(&a_s), ds_cstr(&b_s))) {
2121                 if (a_s.length) {
2122                     printf("-%s", ds_cstr(&a_s));
2123                 }
2124                 if (b_s.length) {
2125                     printf("+%s", ds_cstr(&b_s));
2126                 }
2127                 differences = true;
2128             }
2129         }
2130     }
2131
2132     ds_destroy(&a_s);
2133     ds_destroy(&b_s);
2134
2135     fte_free_all(&cls);
2136
2137     if (differences) {
2138         exit(2);
2139     }
2140 }
2141 \f
2142 /* Undocumented commands for unit testing. */
2143
2144 static void
2145 ofctl_parse_flows__(struct ofputil_flow_mod *fms, size_t n_fms)
2146 {
2147     enum ofputil_protocol usable_protocols;
2148     enum ofputil_protocol protocol = 0;
2149     char *usable_s;
2150     size_t i;
2151
2152     usable_protocols = ofputil_flow_mod_usable_protocols(fms, n_fms);
2153     usable_s = ofputil_protocols_to_string(usable_protocols);
2154     printf("usable protocols: %s\n", usable_s);
2155     free(usable_s);
2156
2157     if (!(usable_protocols & allowed_protocols)) {
2158         ovs_fatal(0, "no usable protocol");
2159     }
2160     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
2161         protocol = 1 << i;
2162         if (protocol & usable_protocols & allowed_protocols) {
2163             break;
2164         }
2165     }
2166     assert(IS_POW2(protocol));
2167
2168     printf("chosen protocol: %s\n", ofputil_protocol_to_string(protocol));
2169
2170     for (i = 0; i < n_fms; i++) {
2171         struct ofputil_flow_mod *fm = &fms[i];
2172         struct ofpbuf *msg;
2173
2174         msg = ofputil_encode_flow_mod(fm, protocol);
2175         ofp_print(stdout, msg->data, msg->size, verbosity);
2176         ofpbuf_delete(msg);
2177
2178         free(fm->ofpacts);
2179     }
2180 }
2181
2182 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
2183  * it back to stdout.  */
2184 static void
2185 ofctl_parse_flow(int argc OVS_UNUSED, char *argv[])
2186 {
2187     struct ofputil_flow_mod fm;
2188
2189     parse_ofp_flow_mod_str(&fm, argv[1], OFPFC_ADD, false);
2190     ofctl_parse_flows__(&fm, 1);
2191 }
2192
2193 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
2194  * add-flows) and prints each of the flows back to stdout.  */
2195 static void
2196 ofctl_parse_flows(int argc OVS_UNUSED, char *argv[])
2197 {
2198     struct ofputil_flow_mod *fms = NULL;
2199     size_t n_fms = 0;
2200
2201     parse_ofp_flow_mod_file(argv[1], OFPFC_ADD, &fms, &n_fms);
2202     ofctl_parse_flows__(fms, n_fms);
2203     free(fms);
2204 }
2205
2206 static void
2207 ofctl_parse_nxm__(bool oxm)
2208 {
2209     struct ds in;
2210
2211     ds_init(&in);
2212     while (!ds_get_test_line(&in, stdin)) {
2213         struct ofpbuf nx_match;
2214         struct match match;
2215         ovs_be64 cookie, cookie_mask;
2216         enum ofperr error;
2217         int match_len;
2218
2219         /* Convert string to nx_match. */
2220         ofpbuf_init(&nx_match, 0);
2221         if (oxm) {
2222             match_len = oxm_match_from_string(ds_cstr(&in), &nx_match);
2223         } else {
2224             match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
2225         }
2226
2227         /* Convert nx_match to match. */
2228         if (strict) {
2229             if (oxm) {
2230                 error = oxm_pull_match(&nx_match, &match);
2231             } else {
2232                 error = nx_pull_match(&nx_match, match_len, &match,
2233                                       &cookie, &cookie_mask);
2234             }
2235         } else {
2236             if (oxm) {
2237                 error = oxm_pull_match_loose(&nx_match, &match);
2238             } else {
2239                 error = nx_pull_match_loose(&nx_match, match_len, &match,
2240                                             &cookie, &cookie_mask);
2241             }
2242         }
2243
2244
2245         if (!error) {
2246             char *out;
2247
2248             /* Convert match back to nx_match. */
2249             ofpbuf_uninit(&nx_match);
2250             ofpbuf_init(&nx_match, 0);
2251             if (oxm) {
2252                 match_len = oxm_put_match(&nx_match, &match);
2253                 out = oxm_match_to_string(nx_match.data, match_len);
2254             } else {
2255                 match_len = nx_put_match(&nx_match, &match,
2256                                          cookie, cookie_mask);
2257                 out = nx_match_to_string(nx_match.data, match_len);
2258             }
2259
2260             puts(out);
2261             free(out);
2262         } else {
2263             printf("nx_pull_match() returned error %s\n",
2264                    ofperr_get_name(error));
2265         }
2266
2267         ofpbuf_uninit(&nx_match);
2268     }
2269     ds_destroy(&in);
2270 }
2271
2272 /* "parse-nxm": reads a series of NXM nx_match specifications as strings from
2273  * stdin, does some internal fussing with them, and then prints them back as
2274  * strings on stdout. */
2275 static void
2276 ofctl_parse_nxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2277 {
2278     return ofctl_parse_nxm__(false);
2279 }
2280
2281 /* "parse-oxm": reads a series of OXM nx_match specifications as strings from
2282  * stdin, does some internal fussing with them, and then prints them back as
2283  * strings on stdout. */
2284 static void
2285 ofctl_parse_oxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2286 {
2287     return ofctl_parse_nxm__(true);
2288 }
2289
2290 static void
2291 print_differences(const char *prefix,
2292                   const void *a_, size_t a_len,
2293                   const void *b_, size_t b_len)
2294 {
2295     const uint8_t *a = a_;
2296     const uint8_t *b = b_;
2297     size_t i;
2298
2299     for (i = 0; i < MIN(a_len, b_len); i++) {
2300         if (a[i] != b[i]) {
2301             printf("%s%2zu: %02"PRIx8" -> %02"PRIx8"\n",
2302                    prefix, i, a[i], b[i]);
2303         }
2304     }
2305     for (i = a_len; i < b_len; i++) {
2306         printf("%s%2zu: (none) -> %02"PRIx8"\n", prefix, i, b[i]);
2307     }
2308     for (i = b_len; i < a_len; i++) {
2309         printf("%s%2zu: %02"PRIx8" -> (none)\n", prefix, i, a[i]);
2310     }
2311 }
2312
2313 /* "parse-ofp10-actions": reads a series of OpenFlow 1.0 action specifications
2314  * as hex bytes from stdin, converts them to ofpacts, prints them as strings
2315  * on stdout, and then converts them back to hex bytes and prints any
2316  * differences from the input. */
2317 static void
2318 ofctl_parse_ofp10_actions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2319 {
2320     struct ds in;
2321
2322     ds_init(&in);
2323     while (!ds_get_preprocessed_line(&in, stdin)) {
2324         struct ofpbuf of10_out;
2325         struct ofpbuf of10_in;
2326         struct ofpbuf ofpacts;
2327         enum ofperr error;
2328         size_t size;
2329         struct ds s;
2330
2331         /* Parse hex bytes. */
2332         ofpbuf_init(&of10_in, 0);
2333         if (ofpbuf_put_hex(&of10_in, ds_cstr(&in), NULL)[0] != '\0') {
2334             ovs_fatal(0, "Trailing garbage in hex data");
2335         }
2336
2337         /* Convert to ofpacts. */
2338         ofpbuf_init(&ofpacts, 0);
2339         size = of10_in.size;
2340         error = ofpacts_pull_openflow10(&of10_in, of10_in.size, &ofpacts);
2341         if (error) {
2342             printf("bad OF1.1 actions: %s\n\n", ofperr_get_name(error));
2343             ofpbuf_uninit(&ofpacts);
2344             ofpbuf_uninit(&of10_in);
2345             continue;
2346         }
2347         ofpbuf_push_uninit(&of10_in, size);
2348
2349         /* Print cls_rule. */
2350         ds_init(&s);
2351         ofpacts_format(ofpacts.data, ofpacts.size, &s);
2352         puts(ds_cstr(&s));
2353         ds_destroy(&s);
2354
2355         /* Convert back to ofp10 actions and print differences from input. */
2356         ofpbuf_init(&of10_out, 0);
2357         ofpacts_put_openflow10(ofpacts.data, ofpacts.size, &of10_out);
2358
2359         print_differences("", of10_in.data, of10_in.size,
2360                           of10_out.data, of10_out.size);
2361         putchar('\n');
2362
2363         ofpbuf_uninit(&ofpacts);
2364         ofpbuf_uninit(&of10_in);
2365         ofpbuf_uninit(&of10_out);
2366     }
2367     ds_destroy(&in);
2368 }
2369
2370 /* "parse-ofp10-match": reads a series of ofp10_match specifications as hex
2371  * bytes from stdin, converts them to cls_rules, prints them as strings on
2372  * stdout, and then converts them back to hex bytes and prints any differences
2373  * from the input.
2374  *
2375  * The input hex bytes may contain "x"s to represent "don't-cares", bytes whose
2376  * values are ignored in the input and will be set to zero when OVS converts
2377  * them back to hex bytes.  ovs-ofctl actually sets "x"s to random bits when
2378  * it does the conversion to hex, to ensure that in fact they are ignored. */
2379 static void
2380 ofctl_parse_ofp10_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2381 {
2382     struct ds expout;
2383     struct ds in;
2384
2385     ds_init(&in);
2386     ds_init(&expout);
2387     while (!ds_get_preprocessed_line(&in, stdin)) {
2388         struct ofpbuf match_in, match_expout;
2389         struct ofp10_match match_out;
2390         struct ofp10_match match_normal;
2391         struct match match;
2392         char *p;
2393
2394         /* Parse hex bytes to use for expected output. */
2395         ds_clear(&expout);
2396         ds_put_cstr(&expout, ds_cstr(&in));
2397         for (p = ds_cstr(&expout); *p; p++) {
2398             if (*p == 'x') {
2399                 *p = '0';
2400             }
2401         }
2402         ofpbuf_init(&match_expout, 0);
2403         if (ofpbuf_put_hex(&match_expout, ds_cstr(&expout), NULL)[0] != '\0') {
2404             ovs_fatal(0, "Trailing garbage in hex data");
2405         }
2406         if (match_expout.size != sizeof(struct ofp10_match)) {
2407             ovs_fatal(0, "Input is %zu bytes, expected %zu",
2408                       match_expout.size, sizeof(struct ofp10_match));
2409         }
2410
2411         /* Parse hex bytes for input. */
2412         for (p = ds_cstr(&in); *p; p++) {
2413             if (*p == 'x') {
2414                 *p = "0123456789abcdef"[random_uint32() & 0xf];
2415             }
2416         }
2417         ofpbuf_init(&match_in, 0);
2418         if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
2419             ovs_fatal(0, "Trailing garbage in hex data");
2420         }
2421         if (match_in.size != sizeof(struct ofp10_match)) {
2422             ovs_fatal(0, "Input is %zu bytes, expected %zu",
2423                       match_in.size, sizeof(struct ofp10_match));
2424         }
2425
2426         /* Convert to cls_rule and print. */
2427         ofputil_match_from_ofp10_match(match_in.data, &match);
2428         match_print(&match);
2429
2430         /* Convert back to ofp10_match and print differences from input. */
2431         ofputil_match_to_ofp10_match(&match, &match_out);
2432         print_differences("", match_expout.data, match_expout.size,
2433                           &match_out, sizeof match_out);
2434
2435         /* Normalize, then convert and compare again. */
2436         ofputil_normalize_match(&match);
2437         ofputil_match_to_ofp10_match(&match, &match_normal);
2438         print_differences("normal: ", &match_out, sizeof match_out,
2439                           &match_normal, sizeof match_normal);
2440         putchar('\n');
2441
2442         ofpbuf_uninit(&match_in);
2443         ofpbuf_uninit(&match_expout);
2444     }
2445     ds_destroy(&in);
2446     ds_destroy(&expout);
2447 }
2448
2449 /* "parse-ofp11-match": reads a series of ofp11_match specifications as hex
2450  * bytes from stdin, converts them to "struct match"es, prints them as strings
2451  * on stdout, and then converts them back to hex bytes and prints any
2452  * differences from the input. */
2453 static void
2454 ofctl_parse_ofp11_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2455 {
2456     struct ds in;
2457
2458     ds_init(&in);
2459     while (!ds_get_preprocessed_line(&in, stdin)) {
2460         struct ofpbuf match_in;
2461         struct ofp11_match match_out;
2462         struct match match;
2463         enum ofperr error;
2464
2465         /* Parse hex bytes. */
2466         ofpbuf_init(&match_in, 0);
2467         if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
2468             ovs_fatal(0, "Trailing garbage in hex data");
2469         }
2470         if (match_in.size != sizeof(struct ofp11_match)) {
2471             ovs_fatal(0, "Input is %zu bytes, expected %zu",
2472                       match_in.size, sizeof(struct ofp11_match));
2473         }
2474
2475         /* Convert to match. */
2476         error = ofputil_match_from_ofp11_match(match_in.data, &match);
2477         if (error) {
2478             printf("bad ofp11_match: %s\n\n", ofperr_get_name(error));
2479             ofpbuf_uninit(&match_in);
2480             continue;
2481         }
2482
2483         /* Print match. */
2484         match_print(&match);
2485
2486         /* Convert back to ofp11_match and print differences from input. */
2487         ofputil_match_to_ofp11_match(&match, &match_out);
2488
2489         print_differences("", match_in.data, match_in.size,
2490                           &match_out, sizeof match_out);
2491         putchar('\n');
2492
2493         ofpbuf_uninit(&match_in);
2494     }
2495     ds_destroy(&in);
2496 }
2497
2498 /* "parse-ofp11-actions": reads a series of OpenFlow 1.1 action specifications
2499  * as hex bytes from stdin, converts them to ofpacts, prints them as strings
2500  * on stdout, and then converts them back to hex bytes and prints any
2501  * differences from the input. */
2502 static void
2503 ofctl_parse_ofp11_actions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2504 {
2505     struct ds in;
2506
2507     ds_init(&in);
2508     while (!ds_get_preprocessed_line(&in, stdin)) {
2509         struct ofpbuf of11_out;
2510         struct ofpbuf of11_in;
2511         struct ofpbuf ofpacts;
2512         enum ofperr error;
2513         size_t size;
2514         struct ds s;
2515
2516         /* Parse hex bytes. */
2517         ofpbuf_init(&of11_in, 0);
2518         if (ofpbuf_put_hex(&of11_in, ds_cstr(&in), NULL)[0] != '\0') {
2519             ovs_fatal(0, "Trailing garbage in hex data");
2520         }
2521
2522         /* Convert to ofpacts. */
2523         ofpbuf_init(&ofpacts, 0);
2524         size = of11_in.size;
2525         error = ofpacts_pull_openflow11_actions(&of11_in, of11_in.size,
2526                                                 &ofpacts);
2527         if (error) {
2528             printf("bad OF1.1 actions: %s\n\n", ofperr_get_name(error));
2529             ofpbuf_uninit(&ofpacts);
2530             ofpbuf_uninit(&of11_in);
2531             continue;
2532         }
2533         ofpbuf_push_uninit(&of11_in, size);
2534
2535         /* Print cls_rule. */
2536         ds_init(&s);
2537         ofpacts_format(ofpacts.data, ofpacts.size, &s);
2538         puts(ds_cstr(&s));
2539         ds_destroy(&s);
2540
2541         /* Convert back to ofp11 actions and print differences from input. */
2542         ofpbuf_init(&of11_out, 0);
2543         ofpacts_put_openflow11_actions(ofpacts.data, ofpacts.size, &of11_out);
2544
2545         print_differences("", of11_in.data, of11_in.size,
2546                           of11_out.data, of11_out.size);
2547         putchar('\n');
2548
2549         ofpbuf_uninit(&ofpacts);
2550         ofpbuf_uninit(&of11_in);
2551         ofpbuf_uninit(&of11_out);
2552     }
2553     ds_destroy(&in);
2554 }
2555
2556 /* "parse-ofp11-instructions": reads a series of OpenFlow 1.1 instruction
2557  * specifications as hex bytes from stdin, converts them to ofpacts, prints
2558  * them as strings on stdout, and then converts them back to hex bytes and
2559  * prints any differences from the input. */
2560 static void
2561 ofctl_parse_ofp11_instructions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2562 {
2563     struct ds in;
2564
2565     ds_init(&in);
2566     while (!ds_get_preprocessed_line(&in, stdin)) {
2567         struct ofpbuf of11_out;
2568         struct ofpbuf of11_in;
2569         struct ofpbuf ofpacts;
2570         enum ofperr error;
2571         size_t size;
2572         struct ds s;
2573
2574         /* Parse hex bytes. */
2575         ofpbuf_init(&of11_in, 0);
2576         if (ofpbuf_put_hex(&of11_in, ds_cstr(&in), NULL)[0] != '\0') {
2577             ovs_fatal(0, "Trailing garbage in hex data");
2578         }
2579
2580         /* Convert to ofpacts. */
2581         ofpbuf_init(&ofpacts, 0);
2582         size = of11_in.size;
2583         error = ofpacts_pull_openflow11_instructions(&of11_in, of11_in.size,
2584                                                      &ofpacts);
2585         if (error) {
2586             printf("bad OF1.1 instructions: %s\n\n", ofperr_get_name(error));
2587             ofpbuf_uninit(&ofpacts);
2588             ofpbuf_uninit(&of11_in);
2589             continue;
2590         }
2591         ofpbuf_push_uninit(&of11_in, size);
2592
2593         /* Print cls_rule. */
2594         ds_init(&s);
2595         ofpacts_format(ofpacts.data, ofpacts.size, &s);
2596         puts(ds_cstr(&s));
2597         ds_destroy(&s);
2598
2599         /* Convert back to ofp11 instructions and print differences from
2600          * input. */
2601         ofpbuf_init(&of11_out, 0);
2602         ofpacts_put_openflow11_instructions(ofpacts.data, ofpacts.size,
2603                                             &of11_out);
2604
2605         print_differences("", of11_in.data, of11_in.size,
2606                           of11_out.data, of11_out.size);
2607         putchar('\n');
2608
2609         ofpbuf_uninit(&ofpacts);
2610         ofpbuf_uninit(&of11_in);
2611         ofpbuf_uninit(&of11_out);
2612     }
2613     ds_destroy(&in);
2614 }
2615
2616 /* "check-vlan VLAN_TCI VLAN_TCI_MASK": converts the specified vlan_tci and
2617  * mask values to and from various formats and prints the results. */
2618 static void
2619 ofctl_check_vlan(int argc OVS_UNUSED, char *argv[])
2620 {
2621     struct match match;
2622
2623     char *string_s;
2624     struct ofputil_flow_mod fm;
2625
2626     struct ofpbuf nxm;
2627     struct match nxm_match;
2628     int nxm_match_len;
2629     char *nxm_s;
2630
2631     struct ofp10_match of10_raw;
2632     struct match of10_match;
2633
2634     struct ofp11_match of11_raw;
2635     struct match of11_match;
2636
2637     enum ofperr error;
2638
2639     match_init_catchall(&match);
2640     match.flow.vlan_tci = htons(strtoul(argv[1], NULL, 16));
2641     match.wc.masks.vlan_tci = htons(strtoul(argv[2], NULL, 16));
2642
2643     /* Convert to and from string. */
2644     string_s = match_to_string(&match, OFP_DEFAULT_PRIORITY);
2645     printf("%s -> ", string_s);
2646     fflush(stdout);
2647     parse_ofp_str(&fm, -1, string_s, false);
2648     printf("%04"PRIx16"/%04"PRIx16"\n",
2649            ntohs(fm.match.flow.vlan_tci),
2650            ntohs(fm.match.wc.masks.vlan_tci));
2651     free(string_s);
2652
2653     /* Convert to and from NXM. */
2654     ofpbuf_init(&nxm, 0);
2655     nxm_match_len = nx_put_match(&nxm, &match, htonll(0), htonll(0));
2656     nxm_s = nx_match_to_string(nxm.data, nxm_match_len);
2657     error = nx_pull_match(&nxm, nxm_match_len, &nxm_match, NULL, NULL);
2658     printf("NXM: %s -> ", nxm_s);
2659     if (error) {
2660         printf("%s\n", ofperr_to_string(error));
2661     } else {
2662         printf("%04"PRIx16"/%04"PRIx16"\n",
2663                ntohs(nxm_match.flow.vlan_tci),
2664                ntohs(nxm_match.wc.masks.vlan_tci));
2665     }
2666     free(nxm_s);
2667     ofpbuf_uninit(&nxm);
2668
2669     /* Convert to and from OXM. */
2670     ofpbuf_init(&nxm, 0);
2671     nxm_match_len = oxm_put_match(&nxm, &match);
2672     nxm_s = oxm_match_to_string(nxm.data, nxm_match_len);
2673     error = oxm_pull_match(&nxm, &nxm_match);
2674     printf("OXM: %s -> ", nxm_s);
2675     if (error) {
2676         printf("%s\n", ofperr_to_string(error));
2677     } else {
2678         uint16_t vid = ntohs(nxm_match.flow.vlan_tci) &
2679             (VLAN_VID_MASK | VLAN_CFI);
2680         uint16_t mask = ntohs(nxm_match.wc.masks.vlan_tci) &
2681             (VLAN_VID_MASK | VLAN_CFI);
2682
2683         printf("%04"PRIx16"/%04"PRIx16",", vid, mask);
2684         if (vid && vlan_tci_to_pcp(nxm_match.wc.masks.vlan_tci)) {
2685             printf("%02"PRIx8"\n", vlan_tci_to_pcp(nxm_match.flow.vlan_tci));
2686         } else {
2687             printf("--\n");
2688         }
2689     }
2690     free(nxm_s);
2691     ofpbuf_uninit(&nxm);
2692
2693     /* Convert to and from OpenFlow 1.0. */
2694     ofputil_match_to_ofp10_match(&match, &of10_raw);
2695     ofputil_match_from_ofp10_match(&of10_raw, &of10_match);
2696     printf("OF1.0: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
2697            ntohs(of10_raw.dl_vlan),
2698            (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN)) != 0,
2699            of10_raw.dl_vlan_pcp,
2700            (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN_PCP)) != 0,
2701            ntohs(of10_match.flow.vlan_tci),
2702            ntohs(of10_match.wc.masks.vlan_tci));
2703
2704     /* Convert to and from OpenFlow 1.1. */
2705     ofputil_match_to_ofp11_match(&match, &of11_raw);
2706     ofputil_match_from_ofp11_match(&of11_raw, &of11_match);
2707     printf("OF1.1: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
2708            ntohs(of11_raw.dl_vlan),
2709            (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN)) != 0,
2710            of11_raw.dl_vlan_pcp,
2711            (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN_PCP)) != 0,
2712            ntohs(of11_match.flow.vlan_tci),
2713            ntohs(of11_match.wc.masks.vlan_tci));
2714 }
2715
2716 /* "print-error ENUM": Prints the type and code of ENUM for every OpenFlow
2717  * version. */
2718 static void
2719 ofctl_print_error(int argc OVS_UNUSED, char *argv[])
2720 {
2721     enum ofperr error;
2722     int version;
2723
2724     error = ofperr_from_name(argv[1]);
2725     if (!error) {
2726         ovs_fatal(0, "unknown error \"%s\"", argv[1]);
2727     }
2728
2729     for (version = 0; version <= UINT8_MAX; version++) {
2730         const char *name = ofperr_domain_get_name(version);
2731         if (!name) {
2732             continue;
2733         }
2734         printf("%s: %d,%d\n",
2735                ofperr_domain_get_name(version),
2736                ofperr_get_type(error, version),
2737                ofperr_get_code(error, version));
2738     }
2739 }
2740
2741 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
2742  * binary data, interpreting them as an OpenFlow message, and prints the
2743  * OpenFlow message on stdout, at VERBOSITY (level 2 by default).  */
2744 static void
2745 ofctl_ofp_print(int argc, char *argv[])
2746 {
2747     struct ofpbuf packet;
2748
2749     ofpbuf_init(&packet, strlen(argv[1]) / 2);
2750     if (ofpbuf_put_hex(&packet, argv[1], NULL)[0] != '\0') {
2751         ovs_fatal(0, "trailing garbage following hex bytes");
2752     }
2753     ofp_print(stdout, packet.data, packet.size, argc > 2 ? atoi(argv[2]) : 2);
2754     ofpbuf_uninit(&packet);
2755 }
2756
2757 /* "encode-hello BITMAP...": Encodes each BITMAP as an OpenFlow hello message
2758  * and dumps each message in hex.  */
2759 static void
2760 ofctl_encode_hello(int argc OVS_UNUSED, char *argv[])
2761 {
2762     uint32_t bitmap = strtol(argv[1], NULL, 0);
2763     struct ofpbuf *hello;
2764
2765     hello = ofputil_encode_hello(bitmap);
2766     ovs_hex_dump(stdout, hello->data, hello->size, 0, false);
2767     ofp_print(stdout, hello->data, hello->size, verbosity);
2768     ofpbuf_delete(hello);
2769 }
2770
2771 static const struct command all_commands[] = {
2772     { "show", 1, 1, ofctl_show },
2773     { "monitor", 1, 3, ofctl_monitor },
2774     { "snoop", 1, 1, ofctl_snoop },
2775     { "dump-desc", 1, 1, ofctl_dump_desc },
2776     { "dump-tables", 1, 1, ofctl_dump_tables },
2777     { "dump-flows", 1, 2, ofctl_dump_flows },
2778     { "dump-aggregate", 1, 2, ofctl_dump_aggregate },
2779     { "queue-stats", 1, 3, ofctl_queue_stats },
2780     { "add-flow", 2, 2, ofctl_add_flow },
2781     { "add-flows", 2, 2, ofctl_add_flows },
2782     { "mod-flows", 2, 2, ofctl_mod_flows },
2783     { "del-flows", 1, 2, ofctl_del_flows },
2784     { "replace-flows", 2, 2, ofctl_replace_flows },
2785     { "diff-flows", 2, 2, ofctl_diff_flows },
2786     { "packet-out", 4, INT_MAX, ofctl_packet_out },
2787     { "dump-ports", 1, 2, ofctl_dump_ports },
2788     { "dump-ports-desc", 1, 1, ofctl_dump_ports_desc },
2789     { "mod-port", 3, 3, ofctl_mod_port },
2790     { "get-frags", 1, 1, ofctl_get_frags },
2791     { "set-frags", 2, 2, ofctl_set_frags },
2792     { "probe", 1, 1, ofctl_probe },
2793     { "ping", 1, 2, ofctl_ping },
2794     { "benchmark", 3, 3, ofctl_benchmark },
2795     { "help", 0, INT_MAX, ofctl_help },
2796
2797     /* Undocumented commands for testing. */
2798     { "parse-flow", 1, 1, ofctl_parse_flow },
2799     { "parse-flows", 1, 1, ofctl_parse_flows },
2800     { "parse-nx-match", 0, 0, ofctl_parse_nxm },
2801     { "parse-nxm", 0, 0, ofctl_parse_nxm },
2802     { "parse-oxm", 0, 0, ofctl_parse_oxm },
2803     { "parse-ofp10-actions", 0, 0, ofctl_parse_ofp10_actions },
2804     { "parse-ofp10-match", 0, 0, ofctl_parse_ofp10_match },
2805     { "parse-ofp11-match", 0, 0, ofctl_parse_ofp11_match },
2806     { "parse-ofp11-actions", 0, 0, ofctl_parse_ofp11_actions },
2807     { "parse-ofp11-instructions", 0, 0, ofctl_parse_ofp11_instructions },
2808     { "check-vlan", 2, 2, ofctl_check_vlan },
2809     { "print-error", 1, 1, ofctl_print_error },
2810     { "ofp-print", 1, 2, ofctl_ofp_print },
2811     { "encode-hello", 1, 1, ofctl_encode_hello },
2812
2813     { NULL, 0, 0, NULL },
2814 };