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