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