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