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