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