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