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