7b20ba097ab957775a43672110b2a61a02619ac0
[sliver-openvswitch.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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/stat.h>
28 #include <sys/time.h>
29
30 #include "byte-order.h"
31 #include "classifier.h"
32 #include "command-line.h"
33 #include "compiler.h"
34 #include "dirs.h"
35 #include "dynamic-string.h"
36 #include "netlink.h"
37 #include "nx-match.h"
38 #include "odp-util.h"
39 #include "ofp-parse.h"
40 #include "ofp-print.h"
41 #include "ofp-util.h"
42 #include "ofpbuf.h"
43 #include "ofproto/ofproto.h"
44 #include "openflow/nicira-ext.h"
45 #include "openflow/openflow.h"
46 #include "random.h"
47 #include "stream-ssl.h"
48 #include "timeval.h"
49 #include "util.h"
50 #include "vconn.h"
51 #include "vlog.h"
52
53 VLOG_DEFINE_THIS_MODULE(ofctl);
54
55 /* --strict: Use strict matching for flow mod commands? */
56 static bool strict;
57
58 /* --readd: If ture, on replace-flows, re-add even flows that have not changed
59  * (to reset flow counters). */
60 static bool readd;
61
62 /* -F, --flow-format: Flow format to use.  Either one of NXFF_* to force a
63  * particular flow format or -1 to let ovs-ofctl choose intelligently. */
64 static int preferred_flow_format = -1;
65
66 /* -m, --more: Additional verbosity for ofp-print functions. */
67 static int verbosity;
68
69 static const struct command all_commands[];
70
71 static void usage(void) NO_RETURN;
72 static void parse_options(int argc, char *argv[]);
73
74 int
75 main(int argc, char *argv[])
76 {
77     set_program_name(argv[0]);
78     parse_options(argc, argv);
79     signal(SIGPIPE, SIG_IGN);
80     run_command(argc - optind, argv + optind, all_commands);
81     return 0;
82 }
83
84 static void
85 parse_options(int argc, char *argv[])
86 {
87     enum {
88         OPT_STRICT = UCHAR_MAX + 1,
89         OPT_READD,
90         VLOG_OPTION_ENUMS
91     };
92     static struct option long_options[] = {
93         {"timeout", required_argument, NULL, 't'},
94         {"strict", no_argument, NULL, OPT_STRICT},
95         {"readd", no_argument, NULL, OPT_READD},
96         {"flow-format", required_argument, NULL, 'F'},
97         {"more", no_argument, NULL, 'm'},
98         {"help", no_argument, NULL, 'h'},
99         {"version", no_argument, NULL, 'V'},
100         VLOG_LONG_OPTIONS,
101         STREAM_SSL_LONG_OPTIONS,
102         {NULL, 0, NULL, 0},
103     };
104     char *short_options = long_options_to_short_options(long_options);
105
106     for (;;) {
107         unsigned long int timeout;
108         int c;
109
110         c = getopt_long(argc, argv, short_options, long_options, NULL);
111         if (c == -1) {
112             break;
113         }
114
115         switch (c) {
116         case 't':
117             timeout = strtoul(optarg, NULL, 10);
118             if (timeout <= 0) {
119                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
120                           optarg);
121             } else {
122                 time_alarm(timeout);
123             }
124             break;
125
126         case 'F':
127             preferred_flow_format = ofputil_flow_format_from_string(optarg);
128             if (preferred_flow_format < 0) {
129                 ovs_fatal(0, "unknown flow format `%s'", optarg);
130             }
131             break;
132
133         case 'm':
134             verbosity++;
135             break;
136
137         case 'h':
138             usage();
139
140         case 'V':
141             ovs_print_version(OFP_VERSION, OFP_VERSION);
142             exit(EXIT_SUCCESS);
143
144         case OPT_STRICT:
145             strict = true;
146             break;
147
148         case OPT_READD:
149             readd = true;
150             break;
151
152         VLOG_OPTION_HANDLERS
153         STREAM_SSL_OPTION_HANDLERS
154
155         case '?':
156             exit(EXIT_FAILURE);
157
158         default:
159             abort();
160         }
161     }
162     free(short_options);
163 }
164
165 static void
166 usage(void)
167 {
168     printf("%s: OpenFlow switch management utility\n"
169            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
170            "\nFor OpenFlow switches:\n"
171            "  show SWITCH                 show OpenFlow information\n"
172            "  dump-desc SWITCH            print switch description\n"
173            "  dump-tables SWITCH          print table stats\n"
174            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
175            "  get-frags SWITCH            print fragment handling behavior\n"
176            "  set-frags SWITCH FRAG_MODE  set fragment handling behavior\n"
177            "  dump-ports SWITCH [PORT]    print port statistics\n"
178            "  dump-flows SWITCH           print all flow entries\n"
179            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
180            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
181            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
182            "  queue-stats SWITCH [PORT [QUEUE]]  dump queue stats\n"
183            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
184            "  add-flows SWITCH FILE       add flows from FILE\n"
185            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
186            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
187            "  replace-flows SWITCH FILE   replace flows with those in FILE\n"
188            "  monitor SWITCH [MISSLEN]    print packets received from SWITCH\n"
189            "\nFor OpenFlow switches and controllers:\n"
190            "  probe TARGET                probe whether TARGET is up\n"
191            "  ping TARGET [N]             latency of N-byte echos\n"
192            "  benchmark TARGET N COUNT    bandwidth of COUNT N-byte echos\n"
193            "where SWITCH or TARGET is an active OpenFlow connection method.\n",
194            program_name, program_name);
195     vconn_usage(true, false, false);
196     vlog_usage();
197     printf("\nOther options:\n"
198            "  --strict                    use strict match for flow commands\n"
199            "  --readd                     replace flows that haven't changed\n"
200            "  -F, --flow-format=FORMAT    force particular flow format\n"
201            "  -m, --more                  be more verbose printing OpenFlow\n"
202            "  -t, --timeout=SECS          give up after SECS seconds\n"
203            "  -h, --help                  display this help message\n"
204            "  -V, --version               display version information\n");
205     exit(EXIT_SUCCESS);
206 }
207
208 static void run(int retval, const char *message, ...)
209     PRINTF_FORMAT(2, 3);
210
211 static void run(int retval, const char *message, ...)
212 {
213     if (retval) {
214         va_list args;
215
216         va_start(args, message);
217         ovs_fatal_valist(retval, message, args);
218     }
219 }
220 \f
221 /* Generic commands. */
222
223 static void
224 open_vconn_socket(const char *name, struct vconn **vconnp)
225 {
226     char *vconn_name = xasprintf("unix:%s", name);
227     VLOG_DBG("connecting to %s", vconn_name);
228     run(vconn_open_block(vconn_name, OFP_VERSION, vconnp),
229         "connecting to %s", vconn_name);
230     free(vconn_name);
231 }
232
233 static void
234 open_vconn__(const char *name, const char *default_suffix,
235              struct vconn **vconnp)
236 {
237     char *datapath_name, *datapath_type, *socket_name;
238     char *bridge_path;
239     struct stat s;
240
241     bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, default_suffix);
242
243     ofproto_parse_name(name, &datapath_name, &datapath_type);
244     socket_name = xasprintf("%s/%s.%s",
245                             ovs_rundir(), datapath_name, default_suffix);
246     free(datapath_name);
247     free(datapath_type);
248
249     if (strchr(name, ':')) {
250         run(vconn_open_block(name, OFP_VERSION, vconnp),
251             "connecting to %s", name);
252     } else if (!stat(name, &s) && S_ISSOCK(s.st_mode)) {
253         open_vconn_socket(name, vconnp);
254     } else if (!stat(bridge_path, &s) && S_ISSOCK(s.st_mode)) {
255         open_vconn_socket(bridge_path, vconnp);
256     } else if (!stat(socket_name, &s)) {
257         if (!S_ISSOCK(s.st_mode)) {
258             ovs_fatal(0, "cannot connect to %s: %s is not a socket",
259                       name, socket_name);
260         }
261         open_vconn_socket(socket_name, vconnp);
262     } else {
263         ovs_fatal(0, "%s is not a bridge or a socket", name);
264     }
265
266     free(bridge_path);
267     free(socket_name);
268 }
269
270 static void
271 open_vconn(const char *name, struct vconn **vconnp)
272 {
273     return open_vconn__(name, "mgmt", vconnp);
274 }
275
276 static void *
277 alloc_stats_request(size_t rq_len, uint16_t type, struct ofpbuf **bufferp)
278 {
279     struct ofp_stats_msg *rq;
280
281     rq = make_openflow(rq_len, OFPT_STATS_REQUEST, bufferp);
282     rq->type = htons(type);
283     rq->flags = htons(0);
284     return rq;
285 }
286
287 static void
288 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
289 {
290     update_openflow_length(buffer);
291     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
292 }
293
294 static void
295 dump_transaction(const char *vconn_name, struct ofpbuf *request)
296 {
297     struct vconn *vconn;
298     struct ofpbuf *reply;
299
300     update_openflow_length(request);
301     open_vconn(vconn_name, &vconn);
302     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
303     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
304     vconn_close(vconn);
305 }
306
307 static void
308 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
309 {
310     struct ofpbuf *request;
311     make_openflow(sizeof(struct ofp_header), request_type, &request);
312     dump_transaction(vconn_name, request);
313 }
314
315 static void
316 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
317 {
318     ovs_be32 send_xid = ((struct ofp_header *) request->data)->xid;
319     struct vconn *vconn;
320     bool done = false;
321
322     open_vconn(vconn_name, &vconn);
323     send_openflow_buffer(vconn, request);
324     while (!done) {
325         ovs_be32 recv_xid;
326         struct ofpbuf *reply;
327
328         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
329         recv_xid = ((struct ofp_header *) reply->data)->xid;
330         if (send_xid == recv_xid) {
331             struct ofp_stats_msg *osm;
332
333             ofp_print(stdout, reply->data, reply->size, verbosity + 1);
334
335             osm = ofpbuf_at(reply, 0, sizeof *osm);
336             done = !osm || !(ntohs(osm->flags) & OFPSF_REPLY_MORE);
337         } else {
338             VLOG_DBG("received reply with xid %08"PRIx32" "
339                      "!= expected %08"PRIx32, recv_xid, send_xid);
340         }
341         ofpbuf_delete(reply);
342     }
343     vconn_close(vconn);
344 }
345
346 static void
347 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
348 {
349     struct ofpbuf *request;
350     alloc_stats_request(sizeof(struct ofp_stats_msg), stats_type, &request);
351     dump_stats_transaction(vconn_name, request);
352 }
353
354 /* Sends 'request', which should be a request that only has a reply if an error
355  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
356  * it and exits with an error.
357  *
358  * Destroys all of the 'requests'. */
359 static void
360 transact_multiple_noreply(struct vconn *vconn, struct list *requests)
361 {
362     struct ofpbuf *request, *reply;
363
364     LIST_FOR_EACH (request, list_node, requests) {
365         update_openflow_length(request);
366     }
367
368     run(vconn_transact_multiple_noreply(vconn, requests, &reply),
369         "talking to %s", vconn_get_name(vconn));
370     if (reply) {
371         ofp_print(stderr, reply->data, reply->size, verbosity + 2);
372         exit(1);
373     }
374     ofpbuf_delete(reply);
375 }
376
377 /* Sends 'request', which should be a request that only has a reply if an error
378  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
379  * it and exits with an error.
380  *
381  * Destroys 'request'. */
382 static void
383 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
384 {
385     struct list requests;
386
387     list_init(&requests);
388     list_push_back(&requests, &request->list_node);
389     transact_multiple_noreply(vconn, &requests);
390 }
391
392 static void
393 fetch_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
394 {
395     struct ofp_switch_config *config;
396     struct ofp_header *header;
397     struct ofpbuf *request;
398     struct ofpbuf *reply;
399
400     make_openflow(sizeof(struct ofp_header), OFPT_GET_CONFIG_REQUEST,
401                   &request);
402     run(vconn_transact(vconn, request, &reply),
403         "talking to %s", vconn_get_name(vconn));
404
405     header = reply->data;
406     if (header->type != OFPT_GET_CONFIG_REPLY ||
407         header->length != htons(sizeof *config)) {
408         ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
409     }
410
411     config = reply->data;
412     *config_ = *config;
413 }
414
415 static void
416 set_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
417 {
418     struct ofp_switch_config *config;
419     struct ofp_header save_header;
420     struct ofpbuf *request;
421
422     config = make_openflow(sizeof *config, OFPT_SET_CONFIG, &request);
423     save_header = config->header;
424     *config = *config_;
425     config->header = save_header;
426
427     transact_noreply(vconn, request);
428 }
429
430 static void
431 do_show(int argc OVS_UNUSED, char *argv[])
432 {
433     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
434     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
435 }
436
437 static void
438 do_dump_desc(int argc OVS_UNUSED, char *argv[])
439 {
440     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
441 }
442
443 static void
444 do_dump_tables(int argc OVS_UNUSED, char *argv[])
445 {
446     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
447 }
448
449 /* Opens a connection to 'vconn_name', fetches the ofp_phy_port structure for
450  * 'port_name' (which may be a port name or number), and copies it into
451  * '*oppp'. */
452 static void
453 fetch_ofp_phy_port(const char *vconn_name, const char *port_name,
454                    struct ofp_phy_port *oppp)
455 {
456     struct ofpbuf *request, *reply;
457     struct ofp_switch_features *osf;
458     unsigned int port_no;
459     struct vconn *vconn;
460     int n_ports;
461     int port_idx;
462
463     /* Try to interpret the argument as a port number. */
464     if (!str_to_uint(port_name, 10, &port_no)) {
465         port_no = UINT_MAX;
466     }
467
468     /* Fetch the switch's ofp_switch_features. */
469     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
470     open_vconn(vconn_name, &vconn);
471     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
472
473     osf = reply->data;
474     if (reply->size < sizeof *osf) {
475         ovs_fatal(0, "%s: received too-short features reply (only %zu bytes)",
476                   vconn_name, reply->size);
477     }
478     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
479
480     for (port_idx = 0; port_idx < n_ports; port_idx++) {
481         const struct ofp_phy_port *opp = &osf->ports[port_idx];
482
483         if (port_no != UINT_MAX
484             ? htons(port_no) == opp->port_no
485             : !strncmp(opp->name, port_name, sizeof opp->name)) {
486             *oppp = *opp;
487             ofpbuf_delete(reply);
488             vconn_close(vconn);
489             return;
490         }
491     }
492     ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
493 }
494
495 /* Returns the port number corresponding to 'port_name' (which may be a port
496  * name or number) within the switch 'vconn_name'. */
497 static uint16_t
498 str_to_port_no(const char *vconn_name, const char *port_name)
499 {
500     unsigned int port_no;
501
502     if (str_to_uint(port_name, 10, &port_no)) {
503         return port_no;
504     } else {
505         struct ofp_phy_port opp;
506
507         fetch_ofp_phy_port(vconn_name, port_name, &opp);
508         return ntohs(opp.port_no);
509     }
510 }
511
512 static bool
513 try_set_flow_format(struct vconn *vconn, enum nx_flow_format flow_format)
514 {
515     struct ofpbuf *sff, *reply;
516
517     sff = ofputil_make_set_flow_format(flow_format);
518     run(vconn_transact_noreply(vconn, sff, &reply),
519         "talking to %s", vconn_get_name(vconn));
520     if (reply) {
521         char *s = ofp_to_string(reply->data, reply->size, 2);
522         VLOG_DBG("%s: failed to set flow format %s, controller replied: %s",
523                  vconn_get_name(vconn),
524                  ofputil_flow_format_to_string(flow_format),
525                  s);
526         free(s);
527         ofpbuf_delete(reply);
528         return false;
529     }
530     return true;
531 }
532
533 static void
534 set_flow_format(struct vconn *vconn, enum nx_flow_format flow_format)
535 {
536     struct ofpbuf *sff = ofputil_make_set_flow_format(flow_format);
537     transact_noreply(vconn, sff);
538     VLOG_DBG("%s: using user-specified flow format %s",
539              vconn_get_name(vconn),
540              ofputil_flow_format_to_string(flow_format));
541 }
542
543 static enum nx_flow_format
544 negotiate_highest_flow_format(struct vconn *vconn,
545                               enum nx_flow_format min_format)
546 {
547     if (preferred_flow_format != -1) {
548         if (preferred_flow_format < min_format) {
549             ovs_fatal(0, "%s: cannot use requested flow format %s for "
550                       "specified flow", vconn_get_name(vconn),
551                       ofputil_flow_format_to_string(min_format));
552         }
553
554         set_flow_format(vconn, preferred_flow_format);
555         return preferred_flow_format;
556     } else {
557         enum nx_flow_format flow_format;
558
559         if (try_set_flow_format(vconn, NXFF_NXM)) {
560             flow_format = NXFF_NXM;
561         } else {
562             flow_format = NXFF_OPENFLOW10;
563         }
564
565         if (flow_format < min_format) {
566             ovs_fatal(0, "%s: cannot use switch's most advanced flow format "
567                       "%s for specified flow", vconn_get_name(vconn),
568                       ofputil_flow_format_to_string(min_format));
569         }
570
571         VLOG_DBG("%s: negotiated flow format %s", vconn_get_name(vconn),
572                  ofputil_flow_format_to_string(flow_format));
573         return flow_format;
574     }
575 }
576
577 static void
578 do_dump_flows__(int argc, char *argv[], bool aggregate)
579 {
580     enum nx_flow_format min_flow_format, flow_format;
581     struct ofputil_flow_stats_request fsr;
582     struct ofpbuf *request;
583     struct vconn *vconn;
584
585     parse_ofp_flow_stats_request_str(&fsr, aggregate, argc > 2 ? argv[2] : "");
586
587     open_vconn(argv[1], &vconn);
588     min_flow_format = ofputil_min_flow_format(&fsr.match);
589     if (fsr.cookie_mask != htonll(0)) {
590         min_flow_format = NXFF_NXM;
591     }
592     flow_format = negotiate_highest_flow_format(vconn, min_flow_format);
593     request = ofputil_encode_flow_stats_request(&fsr, flow_format);
594     dump_stats_transaction(argv[1], request);
595     vconn_close(vconn);
596 }
597
598 static void
599 do_dump_flows(int argc, char *argv[])
600 {
601     return do_dump_flows__(argc, argv, false);
602 }
603
604 static void
605 do_dump_aggregate(int argc, char *argv[])
606 {
607     return do_dump_flows__(argc, argv, true);
608 }
609
610 static void
611 do_queue_stats(int argc, char *argv[])
612 {
613     struct ofp_queue_stats_request *req;
614     struct ofpbuf *request;
615
616     req = alloc_stats_request(sizeof *req, OFPST_QUEUE, &request);
617
618     if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
619         req->port_no = htons(str_to_port_no(argv[1], argv[2]));
620     } else {
621         req->port_no = htons(OFPP_ALL);
622     }
623     if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
624         req->queue_id = htonl(atoi(argv[3]));
625     } else {
626         req->queue_id = htonl(OFPQ_ALL);
627     }
628
629     memset(req->pad, 0, sizeof req->pad);
630
631     dump_stats_transaction(argv[1], request);
632 }
633
634 /* Sets up the flow format for a vconn that will be used to modify the flow
635  * table.  Returns the flow format used, after possibly adding an OpenFlow
636  * request to 'requests'.
637  *
638  * If 'preferred_flow_format' is -1, returns NXFF_OPENFLOW10 without modifying
639  * 'requests', since NXFF_OPENFLOW10 is the default flow format for any
640  * OpenFlow connection.
641  *
642  * If 'preferred_flow_format' is a specific format, adds a request to set that
643  * format to 'requests' and returns the format. */
644 static enum nx_flow_format
645 set_initial_format_for_flow_mod(struct list *requests)
646 {
647     if (preferred_flow_format < 0) {
648         return NXFF_OPENFLOW10;
649     } else {
650         struct ofpbuf *sff;
651
652         sff = ofputil_make_set_flow_format(preferred_flow_format);
653         list_push_back(requests, &sff->list_node);
654         return preferred_flow_format;
655     }
656 }
657
658 /* Checks that 'flow_format' is acceptable as a flow format after a flow_mod
659  * operation, given the global 'preferred_flow_format'. */
660 static void
661 check_final_format_for_flow_mod(enum nx_flow_format flow_format)
662 {
663     if (preferred_flow_format >= 0 && flow_format > preferred_flow_format) {
664         ovs_fatal(0, "flow cannot be expressed in flow format %s "
665                   "(flow format %s or better is required)",
666                   ofputil_flow_format_to_string(preferred_flow_format),
667                   ofputil_flow_format_to_string(flow_format));
668     }
669 }
670
671 static void
672 do_flow_mod_file__(int argc OVS_UNUSED, char *argv[], uint16_t command)
673 {
674     enum nx_flow_format flow_format;
675     bool flow_mod_table_id;
676     struct list requests;
677     struct vconn *vconn;
678     FILE *file;
679
680     file = !strcmp(argv[2], "-") ? stdin : fopen(argv[2], "r");
681     if (file == NULL) {
682         ovs_fatal(errno, "%s: open", argv[2]);
683     }
684
685     list_init(&requests);
686     flow_format = set_initial_format_for_flow_mod(&requests);
687     flow_mod_table_id = false;
688
689     open_vconn(argv[1], &vconn);
690     while (parse_ofp_flow_mod_file(&requests, &flow_format, &flow_mod_table_id,
691                                    file, command)) {
692         check_final_format_for_flow_mod(flow_format);
693         transact_multiple_noreply(vconn, &requests);
694     }
695     vconn_close(vconn);
696
697     if (file != stdin) {
698         fclose(file);
699     }
700 }
701
702 static void
703 do_flow_mod__(int argc, char *argv[], uint16_t command)
704 {
705     enum nx_flow_format flow_format;
706     bool flow_mod_table_id;
707     struct list requests;
708     struct vconn *vconn;
709
710     if (argc > 2 && !strcmp(argv[2], "-")) {
711         do_flow_mod_file__(argc, argv, command);
712         return;
713     }
714
715     list_init(&requests);
716     flow_format = set_initial_format_for_flow_mod(&requests);
717     flow_mod_table_id = false;
718
719     parse_ofp_flow_mod_str(&requests, &flow_format, &flow_mod_table_id,
720                            argc > 2 ? argv[2] : "", command, false);
721     check_final_format_for_flow_mod(flow_format);
722
723     open_vconn(argv[1], &vconn);
724     transact_multiple_noreply(vconn, &requests);
725     vconn_close(vconn);
726 }
727
728 static void
729 do_add_flow(int argc, char *argv[])
730 {
731     do_flow_mod__(argc, argv, OFPFC_ADD);
732 }
733
734 static void
735 do_add_flows(int argc, char *argv[])
736 {
737     do_flow_mod_file__(argc, argv, OFPFC_ADD);
738 }
739
740 static void
741 do_mod_flows(int argc, char *argv[])
742 {
743     do_flow_mod__(argc, argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
744 }
745
746 static void
747 do_del_flows(int argc, char *argv[])
748 {
749     do_flow_mod__(argc, argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
750 }
751
752 static void
753 monitor_vconn(struct vconn *vconn)
754 {
755     for (;;) {
756         struct ofpbuf *b;
757         run(vconn_recv_block(vconn, &b), "vconn_recv");
758         ofp_print(stderr, b->data, b->size, verbosity + 2);
759         ofpbuf_delete(b);
760     }
761 }
762
763 static void
764 do_monitor(int argc, char *argv[])
765 {
766     struct vconn *vconn;
767
768     open_vconn(argv[1], &vconn);
769     if (argc > 2) {
770         struct ofp_switch_config config;
771
772         fetch_switch_config(vconn, &config);
773         config.miss_send_len = htons(atoi(argv[2]));
774         set_switch_config(vconn, &config);
775     }
776     monitor_vconn(vconn);
777 }
778
779 static void
780 do_snoop(int argc OVS_UNUSED, char *argv[])
781 {
782     struct vconn *vconn;
783
784     open_vconn__(argv[1], "snoop", &vconn);
785     monitor_vconn(vconn);
786 }
787
788 static void
789 do_dump_ports(int argc, char *argv[])
790 {
791     struct ofp_port_stats_request *req;
792     struct ofpbuf *request;
793     uint16_t port;
794
795     req = alloc_stats_request(sizeof *req, OFPST_PORT, &request);
796     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_NONE;
797     req->port_no = htons(port);
798     dump_stats_transaction(argv[1], request);
799 }
800
801 static void
802 do_probe(int argc OVS_UNUSED, char *argv[])
803 {
804     struct ofpbuf *request;
805     struct vconn *vconn;
806     struct ofpbuf *reply;
807
808     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
809     open_vconn(argv[1], &vconn);
810     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
811     if (reply->size != sizeof(struct ofp_header)) {
812         ovs_fatal(0, "reply does not match request");
813     }
814     ofpbuf_delete(reply);
815     vconn_close(vconn);
816 }
817
818 static void
819 do_mod_port(int argc OVS_UNUSED, char *argv[])
820 {
821     struct ofp_port_mod *opm;
822     struct ofp_phy_port opp;
823     struct ofpbuf *request;
824     struct vconn *vconn;
825
826     fetch_ofp_phy_port(argv[1], argv[2], &opp);
827
828     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
829     opm->port_no = opp.port_no;
830     memcpy(opm->hw_addr, opp.hw_addr, sizeof opm->hw_addr);
831     opm->config = htonl(0);
832     opm->mask = htonl(0);
833     opm->advertise = htonl(0);
834
835     if (!strcasecmp(argv[3], "up")) {
836         opm->mask |= htonl(OFPPC_PORT_DOWN);
837     } else if (!strcasecmp(argv[3], "down")) {
838         opm->mask |= htonl(OFPPC_PORT_DOWN);
839         opm->config |= htonl(OFPPC_PORT_DOWN);
840     } else if (!strcasecmp(argv[3], "flood")) {
841         opm->mask |= htonl(OFPPC_NO_FLOOD);
842     } else if (!strcasecmp(argv[3], "noflood")) {
843         opm->mask |= htonl(OFPPC_NO_FLOOD);
844         opm->config |= htonl(OFPPC_NO_FLOOD);
845     } else if (!strcasecmp(argv[3], "forward")) {
846         opm->mask |= htonl(OFPPC_NO_FWD);
847     } else if (!strcasecmp(argv[3], "noforward")) {
848         opm->mask |= htonl(OFPPC_NO_FWD);
849         opm->config |= htonl(OFPPC_NO_FWD);
850     } else {
851         ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
852     }
853
854     open_vconn(argv[1], &vconn);
855     transact_noreply(vconn, request);
856     vconn_close(vconn);
857 }
858
859 static void
860 do_get_frags(int argc OVS_UNUSED, char *argv[])
861 {
862     struct ofp_switch_config config;
863     struct vconn *vconn;
864
865     open_vconn(argv[1], &vconn);
866     fetch_switch_config(vconn, &config);
867     puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
868     vconn_close(vconn);
869 }
870
871 static void
872 do_set_frags(int argc OVS_UNUSED, char *argv[])
873 {
874     struct ofp_switch_config config;
875     enum ofp_config_flags mode;
876     struct vconn *vconn;
877     ovs_be16 flags;
878
879     if (!ofputil_frag_handling_from_string(argv[2], &mode)) {
880         ovs_fatal(0, "%s: unknown fragment handling mode", argv[2]);
881     }
882
883     open_vconn(argv[1], &vconn);
884     fetch_switch_config(vconn, &config);
885     flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
886     if (flags != config.flags) {
887         /* Set the configuration. */
888         config.flags = flags;
889         set_switch_config(vconn, &config);
890
891         /* Then retrieve the configuration to see if it really took.  OpenFlow
892          * doesn't define error reporting for bad modes, so this is all we can
893          * do. */
894         fetch_switch_config(vconn, &config);
895         if (flags != config.flags) {
896             ovs_fatal(0, "%s: setting fragment handling mode failed (this "
897                       "switch probably doesn't support mode \"%s\")",
898                       argv[1], ofputil_frag_handling_to_string(mode));
899         }
900     }
901     vconn_close(vconn);
902 }
903
904 static void
905 do_ping(int argc, char *argv[])
906 {
907     size_t max_payload = 65535 - sizeof(struct ofp_header);
908     unsigned int payload;
909     struct vconn *vconn;
910     int i;
911
912     payload = argc > 2 ? atoi(argv[2]) : 64;
913     if (payload > max_payload) {
914         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
915     }
916
917     open_vconn(argv[1], &vconn);
918     for (i = 0; i < 10; i++) {
919         struct timeval start, end;
920         struct ofpbuf *request, *reply;
921         struct ofp_header *rq_hdr, *rpy_hdr;
922
923         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
924                                OFPT_ECHO_REQUEST, &request);
925         random_bytes(rq_hdr + 1, payload);
926
927         xgettimeofday(&start);
928         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
929         xgettimeofday(&end);
930
931         rpy_hdr = reply->data;
932         if (reply->size != request->size
933             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
934             || rpy_hdr->xid != rq_hdr->xid
935             || rpy_hdr->type != OFPT_ECHO_REPLY) {
936             printf("Reply does not match request.  Request:\n");
937             ofp_print(stdout, request, request->size, verbosity + 2);
938             printf("Reply:\n");
939             ofp_print(stdout, reply, reply->size, verbosity + 2);
940         }
941         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
942                reply->size - sizeof *rpy_hdr, argv[1], ntohl(rpy_hdr->xid),
943                    (1000*(double)(end.tv_sec - start.tv_sec))
944                    + (.001*(end.tv_usec - start.tv_usec)));
945         ofpbuf_delete(request);
946         ofpbuf_delete(reply);
947     }
948     vconn_close(vconn);
949 }
950
951 static void
952 do_benchmark(int argc OVS_UNUSED, char *argv[])
953 {
954     size_t max_payload = 65535 - sizeof(struct ofp_header);
955     struct timeval start, end;
956     unsigned int payload_size, message_size;
957     struct vconn *vconn;
958     double duration;
959     int count;
960     int i;
961
962     payload_size = atoi(argv[2]);
963     if (payload_size > max_payload) {
964         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
965     }
966     message_size = sizeof(struct ofp_header) + payload_size;
967
968     count = atoi(argv[3]);
969
970     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
971            count, message_size, count * message_size);
972
973     open_vconn(argv[1], &vconn);
974     xgettimeofday(&start);
975     for (i = 0; i < count; i++) {
976         struct ofpbuf *request, *reply;
977         struct ofp_header *rq_hdr;
978
979         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
980         memset(rq_hdr + 1, 0, payload_size);
981         run(vconn_transact(vconn, request, &reply), "transact");
982         ofpbuf_delete(reply);
983     }
984     xgettimeofday(&end);
985     vconn_close(vconn);
986
987     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
988                 + (.001*(end.tv_usec - start.tv_usec)));
989     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
990            duration, count / (duration / 1000.0),
991            count * message_size / (duration / 1000.0));
992 }
993
994 static void
995 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
996 {
997     usage();
998 }
999 \f
1000 /* replace-flows and diff-flows commands. */
1001
1002 /* A flow table entry, possibly with two different versions. */
1003 struct fte {
1004     struct cls_rule rule;       /* Within a "struct classifier". */
1005     struct fte_version *versions[2];
1006 };
1007
1008 /* One version of a Flow Table Entry. */
1009 struct fte_version {
1010     ovs_be64 cookie;
1011     uint16_t idle_timeout;
1012     uint16_t hard_timeout;
1013     uint16_t flags;
1014     union ofp_action *actions;
1015     size_t n_actions;
1016 };
1017
1018 /* Frees 'version' and the data that it owns. */
1019 static void
1020 fte_version_free(struct fte_version *version)
1021 {
1022     if (version) {
1023         free(version->actions);
1024         free(version);
1025     }
1026 }
1027
1028 /* Returns true if 'a' and 'b' are the same, false if they differ.
1029  *
1030  * Ignores differences in 'flags' because there's no way to retrieve flags from
1031  * an OpenFlow switch.  We have to assume that they are the same. */
1032 static bool
1033 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
1034 {
1035     return (a->cookie == b->cookie
1036             && a->idle_timeout == b->idle_timeout
1037             && a->hard_timeout == b->hard_timeout
1038             && a->n_actions == b->n_actions
1039             && !memcmp(a->actions, b->actions,
1040                        a->n_actions * sizeof *a->actions));
1041 }
1042
1043 /* Prints 'version' on stdout.  Expects the caller to have printed the rule
1044  * associated with the version. */
1045 static void
1046 fte_version_print(const struct fte_version *version)
1047 {
1048     struct ds s;
1049
1050     if (version->cookie != htonll(0)) {
1051         printf(" cookie=0x%"PRIx64, ntohll(version->cookie));
1052     }
1053     if (version->idle_timeout != OFP_FLOW_PERMANENT) {
1054         printf(" idle_timeout=%"PRIu16, version->idle_timeout);
1055     }
1056     if (version->hard_timeout != OFP_FLOW_PERMANENT) {
1057         printf(" hard_timeout=%"PRIu16, version->hard_timeout);
1058     }
1059
1060     ds_init(&s);
1061     ofp_print_actions(&s, version->actions, version->n_actions);
1062     printf(" %s\n", ds_cstr(&s));
1063     ds_destroy(&s);
1064 }
1065
1066 static struct fte *
1067 fte_from_cls_rule(const struct cls_rule *cls_rule)
1068 {
1069     return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
1070 }
1071
1072 /* Frees 'fte' and its versions. */
1073 static void
1074 fte_free(struct fte *fte)
1075 {
1076     if (fte) {
1077         fte_version_free(fte->versions[0]);
1078         fte_version_free(fte->versions[1]);
1079         free(fte);
1080     }
1081 }
1082
1083 /* Frees all of the FTEs within 'cls'. */
1084 static void
1085 fte_free_all(struct classifier *cls)
1086 {
1087     struct cls_cursor cursor;
1088     struct fte *fte, *next;
1089
1090     cls_cursor_init(&cursor, cls, NULL);
1091     CLS_CURSOR_FOR_EACH_SAFE (fte, next, rule, &cursor) {
1092         classifier_remove(cls, &fte->rule);
1093         fte_free(fte);
1094     }
1095 }
1096
1097 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
1098  * necessary.  Sets 'version' as the version of that rule with the given
1099  * 'index', replacing any existing version, if any.
1100  *
1101  * Takes ownership of 'version'. */
1102 static void
1103 fte_insert(struct classifier *cls, const struct cls_rule *rule,
1104            struct fte_version *version, int index)
1105 {
1106     struct fte *old, *fte;
1107
1108     fte = xzalloc(sizeof *fte);
1109     fte->rule = *rule;
1110     fte->versions[index] = version;
1111
1112     old = fte_from_cls_rule(classifier_replace(cls, &fte->rule));
1113     if (old) {
1114         fte_version_free(old->versions[index]);
1115         fte->versions[!index] = old->versions[!index];
1116         free(old);
1117     }
1118 }
1119
1120 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
1121  * with the specified 'index'.  Returns the minimum flow format required to
1122  * represent the flows that were read. */
1123 static enum nx_flow_format
1124 read_flows_from_file(const char *filename, struct classifier *cls, int index)
1125 {
1126     enum nx_flow_format min_flow_format;
1127     struct ds s;
1128     FILE *file;
1129
1130     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
1131     if (file == NULL) {
1132         ovs_fatal(errno, "%s: open", filename);
1133     }
1134
1135     ds_init(&s);
1136     min_flow_format = NXFF_OPENFLOW10;
1137     while (!ds_get_preprocessed_line(&s, file)) {
1138         struct fte_version *version;
1139         struct ofputil_flow_mod fm;
1140         enum nx_flow_format min_ff;
1141
1142         parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), true);
1143
1144         version = xmalloc(sizeof *version);
1145         version->cookie = fm.cookie;
1146         version->idle_timeout = fm.idle_timeout;
1147         version->hard_timeout = fm.hard_timeout;
1148         version->flags = fm.flags & (OFPFF_SEND_FLOW_REM | OFPFF_EMERG);
1149         version->actions = fm.actions;
1150         version->n_actions = fm.n_actions;
1151
1152         min_ff = ofputil_min_flow_format(&fm.cr);
1153         min_flow_format = MAX(min_flow_format, min_ff);
1154         check_final_format_for_flow_mod(min_flow_format);
1155
1156         fte_insert(cls, &fm.cr, version, index);
1157     }
1158     ds_destroy(&s);
1159
1160     if (file != stdin) {
1161         fclose(file);
1162     }
1163
1164     return min_flow_format;
1165 }
1166
1167 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
1168  * format 'flow_format', and adds them as flow table entries in 'cls' for the
1169  * version with the specified 'index'. */
1170 static void
1171 read_flows_from_switch(struct vconn *vconn, enum nx_flow_format flow_format,
1172                        struct classifier *cls, int index)
1173 {
1174     struct ofputil_flow_stats_request fsr;
1175     struct ofpbuf *request;
1176     ovs_be32 send_xid;
1177     bool done;
1178
1179     fsr.aggregate = false;
1180     cls_rule_init_catchall(&fsr.match, 0);
1181     fsr.out_port = OFPP_NONE;
1182     fsr.table_id = 0xff;
1183     fsr.cookie = fsr.cookie_mask = htonll(0);
1184     request = ofputil_encode_flow_stats_request(&fsr, flow_format);
1185     send_xid = ((struct ofp_header *) request->data)->xid;
1186     send_openflow_buffer(vconn, request);
1187
1188     done = false;
1189     while (!done) {
1190         ovs_be32 recv_xid;
1191         struct ofpbuf *reply;
1192
1193         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
1194         recv_xid = ((struct ofp_header *) reply->data)->xid;
1195         if (send_xid == recv_xid) {
1196             const struct ofputil_msg_type *type;
1197             const struct ofp_stats_msg *osm;
1198             enum ofputil_msg_code code;
1199
1200             ofputil_decode_msg_type(reply->data, &type);
1201             code = ofputil_msg_type_code(type);
1202             if (code != OFPUTIL_OFPST_FLOW_REPLY &&
1203                 code != OFPUTIL_NXST_FLOW_REPLY) {
1204                 ovs_fatal(0, "received bad reply: %s",
1205                           ofp_to_string(reply->data, reply->size,
1206                                         verbosity + 1));
1207             }
1208
1209             osm = reply->data;
1210             if (!(osm->flags & htons(OFPSF_REPLY_MORE))) {
1211                 done = true;
1212             }
1213
1214             for (;;) {
1215                 struct fte_version *version;
1216                 struct ofputil_flow_stats fs;
1217                 int retval;
1218
1219                 retval = ofputil_decode_flow_stats_reply(&fs, reply);
1220                 if (retval) {
1221                     if (retval != EOF) {
1222                         ovs_fatal(0, "parse error in reply");
1223                     }
1224                     break;
1225                 }
1226
1227                 version = xmalloc(sizeof *version);
1228                 version->cookie = fs.cookie;
1229                 version->idle_timeout = fs.idle_timeout;
1230                 version->hard_timeout = fs.hard_timeout;
1231                 version->flags = 0;
1232                 version->n_actions = fs.n_actions;
1233                 version->actions = xmemdup(fs.actions,
1234                                            fs.n_actions * sizeof *fs.actions);
1235
1236                 fte_insert(cls, &fs.rule, version, index);
1237             }
1238         } else {
1239             VLOG_DBG("received reply with xid %08"PRIx32" "
1240                      "!= expected %08"PRIx32, recv_xid, send_xid);
1241         }
1242         ofpbuf_delete(reply);
1243     }
1244 }
1245
1246 static void
1247 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
1248                   enum nx_flow_format flow_format, struct list *packets)
1249 {
1250     const struct fte_version *version = fte->versions[index];
1251     struct ofputil_flow_mod fm;
1252     struct ofpbuf *ofm;
1253
1254     fm.cr = fte->rule;
1255     fm.cookie = version->cookie;
1256     fm.table_id = 0xff;
1257     fm.command = command;
1258     fm.idle_timeout = version->idle_timeout;
1259     fm.hard_timeout = version->hard_timeout;
1260     fm.buffer_id = UINT32_MAX;
1261     fm.out_port = OFPP_NONE;
1262     fm.flags = version->flags;
1263     if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
1264         command == OFPFC_MODIFY_STRICT) {
1265         fm.actions = version->actions;
1266         fm.n_actions = version->n_actions;
1267     } else {
1268         fm.actions = NULL;
1269         fm.n_actions = 0;
1270     }
1271
1272     ofm = ofputil_encode_flow_mod(&fm, flow_format, false);
1273     list_push_back(packets, &ofm->list_node);
1274 }
1275
1276 static void
1277 do_replace_flows(int argc OVS_UNUSED, char *argv[])
1278 {
1279     enum { FILE_IDX = 0, SWITCH_IDX = 1 };
1280     enum nx_flow_format min_flow_format, flow_format;
1281     struct cls_cursor cursor;
1282     struct classifier cls;
1283     struct list requests;
1284     struct vconn *vconn;
1285     struct fte *fte;
1286
1287     classifier_init(&cls);
1288     min_flow_format = read_flows_from_file(argv[2], &cls, FILE_IDX);
1289
1290     open_vconn(argv[1], &vconn);
1291     flow_format = negotiate_highest_flow_format(vconn, min_flow_format);
1292     read_flows_from_switch(vconn, flow_format, &cls, SWITCH_IDX);
1293
1294     list_init(&requests);
1295
1296     /* Delete flows that exist on the switch but not in the file. */
1297     cls_cursor_init(&cursor, &cls, NULL);
1298     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1299         struct fte_version *file_ver = fte->versions[FILE_IDX];
1300         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1301
1302         if (sw_ver && !file_ver) {
1303             fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
1304                               flow_format, &requests);
1305         }
1306     }
1307
1308     /* Add flows that exist in the file but not on the switch.
1309      * Update flows that exist in both places but differ. */
1310     cls_cursor_init(&cursor, &cls, NULL);
1311     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1312         struct fte_version *file_ver = fte->versions[FILE_IDX];
1313         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1314
1315         if (file_ver
1316             && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
1317             fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, flow_format,
1318                               &requests);
1319         }
1320     }
1321     transact_multiple_noreply(vconn, &requests);
1322     vconn_close(vconn);
1323
1324     fte_free_all(&cls);
1325 }
1326
1327 static void
1328 read_flows_from_source(const char *source, struct classifier *cls, int index)
1329 {
1330     struct stat s;
1331
1332     if (source[0] == '/' || source[0] == '.'
1333         || (!strchr(source, ':') && !stat(source, &s))) {
1334         read_flows_from_file(source, cls, index);
1335     } else {
1336         enum nx_flow_format flow_format;
1337         struct vconn *vconn;
1338
1339         open_vconn(source, &vconn);
1340         flow_format = negotiate_highest_flow_format(vconn, NXFF_OPENFLOW10);
1341         read_flows_from_switch(vconn, flow_format, cls, index);
1342         vconn_close(vconn);
1343     }
1344 }
1345
1346 static void
1347 do_diff_flows(int argc OVS_UNUSED, char *argv[])
1348 {
1349     bool differences = false;
1350     struct cls_cursor cursor;
1351     struct classifier cls;
1352     struct fte *fte;
1353
1354     classifier_init(&cls);
1355     read_flows_from_source(argv[1], &cls, 0);
1356     read_flows_from_source(argv[2], &cls, 1);
1357
1358     cls_cursor_init(&cursor, &cls, NULL);
1359     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1360         struct fte_version *a = fte->versions[0];
1361         struct fte_version *b = fte->versions[1];
1362
1363         if (!a || !b || !fte_version_equals(a, b)) {
1364             char *rule_s = cls_rule_to_string(&fte->rule);
1365             if (a) {
1366                 printf("-%s", rule_s);
1367                 fte_version_print(a);
1368             }
1369             if (b) {
1370                 printf("+%s", rule_s);
1371                 fte_version_print(b);
1372             }
1373             free(rule_s);
1374
1375             differences = true;
1376         }
1377     }
1378
1379     fte_free_all(&cls);
1380
1381     if (differences) {
1382         exit(2);
1383     }
1384 }
1385 \f
1386 /* Undocumented commands for unit testing. */
1387
1388 static void
1389 print_packet_list(struct list *packets)
1390 {
1391     struct ofpbuf *packet, *next;
1392
1393     LIST_FOR_EACH_SAFE (packet, next, list_node, packets) {
1394         ofp_print(stdout, packet->data, packet->size, verbosity);
1395         list_remove(&packet->list_node);
1396         ofpbuf_delete(packet);
1397     }
1398 }
1399
1400 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
1401  * it back to stdout.  */
1402 static void
1403 do_parse_flow(int argc OVS_UNUSED, char *argv[])
1404 {
1405     enum nx_flow_format flow_format;
1406     bool flow_mod_table_id;
1407     struct list packets;
1408
1409     flow_format = NXFF_OPENFLOW10;
1410     if (preferred_flow_format > 0) {
1411         flow_format = preferred_flow_format;
1412     }
1413     flow_mod_table_id = false;
1414
1415     list_init(&packets);
1416     parse_ofp_flow_mod_str(&packets, &flow_format, &flow_mod_table_id,
1417                            argv[1], OFPFC_ADD, false);
1418     print_packet_list(&packets);
1419 }
1420
1421 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
1422  * add-flows) and prints each of the flows back to stdout.  */
1423 static void
1424 do_parse_flows(int argc OVS_UNUSED, char *argv[])
1425 {
1426     enum nx_flow_format flow_format;
1427     bool flow_mod_table_id;
1428     struct list packets;
1429     FILE *file;
1430
1431     file = fopen(argv[1], "r");
1432     if (file == NULL) {
1433         ovs_fatal(errno, "%s: open", argv[1]);
1434     }
1435
1436     flow_format = NXFF_OPENFLOW10;
1437     if (preferred_flow_format > 0) {
1438         flow_format = preferred_flow_format;
1439     }
1440     flow_mod_table_id = false;
1441
1442     list_init(&packets);
1443     while (parse_ofp_flow_mod_file(&packets, &flow_format, &flow_mod_table_id,
1444                                    file, OFPFC_ADD)) {
1445         print_packet_list(&packets);
1446     }
1447     fclose(file);
1448 }
1449
1450 /* "parse-nx-match": reads a series of nx_match specifications as strings from
1451  * stdin, does some internal fussing with them, and then prints them back as
1452  * strings on stdout. */
1453 static void
1454 do_parse_nx_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1455 {
1456     struct ds in;
1457
1458     ds_init(&in);
1459     while (!ds_get_line(&in, stdin)) {
1460         struct ofpbuf nx_match;
1461         struct cls_rule rule;
1462         ovs_be64 cookie, cookie_mask;
1463         int match_len;
1464         int error;
1465         char *s;
1466
1467         /* Delete comments, skip blank lines. */
1468         s = ds_cstr(&in);
1469         if (*s == '#') {
1470             puts(s);
1471             continue;
1472         }
1473         if (strchr(s, '#')) {
1474             *strchr(s, '#') = '\0';
1475         }
1476         if (s[strspn(s, " ")] == '\0') {
1477             putchar('\n');
1478             continue;
1479         }
1480
1481         /* Convert string to nx_match. */
1482         ofpbuf_init(&nx_match, 0);
1483         match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
1484
1485         /* Convert nx_match to cls_rule. */
1486         error = nx_pull_match(&nx_match, match_len, 0, &rule,
1487                               &cookie, &cookie_mask);
1488         if (!error) {
1489             char *out;
1490
1491             /* Convert cls_rule back to nx_match. */
1492             ofpbuf_uninit(&nx_match);
1493             ofpbuf_init(&nx_match, 0);
1494             match_len = nx_put_match(&nx_match, &rule, cookie, cookie_mask);
1495
1496             /* Convert nx_match to string. */
1497             out = nx_match_to_string(nx_match.data, match_len);
1498             puts(out);
1499             free(out);
1500         } else {
1501             printf("nx_pull_match() returned error %x (%s)\n", error,
1502                    ofputil_error_to_string(error));
1503         }
1504
1505         ofpbuf_uninit(&nx_match);
1506     }
1507     ds_destroy(&in);
1508 }
1509
1510 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
1511  * binary data, interpreting them as an OpenFlow message, and prints the
1512  * OpenFlow message on stdout, at VERBOSITY (level 2 by default).  */
1513 static void
1514 do_ofp_print(int argc, char *argv[])
1515 {
1516     struct ofpbuf packet;
1517
1518     ofpbuf_init(&packet, strlen(argv[1]) / 2);
1519     if (ofpbuf_put_hex(&packet, argv[1], NULL)[0] != '\0') {
1520         ovs_fatal(0, "trailing garbage following hex bytes");
1521     }
1522     ofp_print(stdout, packet.data, packet.size, argc > 2 ? atoi(argv[2]) : 2);
1523     ofpbuf_uninit(&packet);
1524 }
1525
1526 static const struct command all_commands[] = {
1527     { "show", 1, 1, do_show },
1528     { "monitor", 1, 2, do_monitor },
1529     { "snoop", 1, 1, do_snoop },
1530     { "dump-desc", 1, 1, do_dump_desc },
1531     { "dump-tables", 1, 1, do_dump_tables },
1532     { "dump-flows", 1, 2, do_dump_flows },
1533     { "dump-aggregate", 1, 2, do_dump_aggregate },
1534     { "queue-stats", 1, 3, do_queue_stats },
1535     { "add-flow", 2, 2, do_add_flow },
1536     { "add-flows", 2, 2, do_add_flows },
1537     { "mod-flows", 2, 2, do_mod_flows },
1538     { "del-flows", 1, 2, do_del_flows },
1539     { "replace-flows", 2, 2, do_replace_flows },
1540     { "diff-flows", 2, 2, do_diff_flows },
1541     { "dump-ports", 1, 2, do_dump_ports },
1542     { "mod-port", 3, 3, do_mod_port },
1543     { "get-frags", 1, 1, do_get_frags },
1544     { "set-frags", 2, 2, do_set_frags },
1545     { "probe", 1, 1, do_probe },
1546     { "ping", 1, 2, do_ping },
1547     { "benchmark", 3, 3, do_benchmark },
1548     { "help", 0, INT_MAX, do_help },
1549
1550     /* Undocumented commands for testing. */
1551     { "parse-flow", 1, 1, do_parse_flow },
1552     { "parse-flows", 1, 1, do_parse_flows },
1553     { "parse-nx-match", 0, 0, do_parse_nx_match },
1554     { "ofp-print", 1, 2, do_ofp_print },
1555
1556     { NULL, 0, 0, NULL },
1557 };