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