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