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