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