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