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