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