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