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