ofp-util: Implement translation to and from OpenFlow 1.1 ofp_match.
[sliver-openvswitch.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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/fcntl.h>
28 #include <sys/stat.h>
29 #include <sys/time.h>
30
31 #include "byte-order.h"
32 #include "classifier.h"
33 #include "command-line.h"
34 #include "daemon.h"
35 #include "compiler.h"
36 #include "dirs.h"
37 #include "dynamic-string.h"
38 #include "netlink.h"
39 #include "nx-match.h"
40 #include "odp-util.h"
41 #include "ofp-errors.h"
42 #include "ofp-parse.h"
43 #include "ofp-print.h"
44 #include "ofp-util.h"
45 #include "ofpbuf.h"
46 #include "ofproto/ofproto.h"
47 #include "openflow/nicira-ext.h"
48 #include "openflow/openflow.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "random.h"
52 #include "stream-ssl.h"
53 #include "timeval.h"
54 #include "unixctl.h"
55 #include "util.h"
56 #include "vconn.h"
57 #include "vlog.h"
58
59 VLOG_DEFINE_THIS_MODULE(ofctl);
60
61 /* --strict: Use strict matching for flow mod commands?  Additionally governs
62  * use of nx_pull_match() instead of nx_pull_match_loose() in parse-nx-match.
63  */
64 static bool strict;
65
66 /* --readd: If true, on replace-flows, re-add even flows that have not changed
67  * (to reset flow counters). */
68 static bool readd;
69
70 /* -F, --flow-format: Allowed protocols.  By default, any protocol is
71  * allowed. */
72 static enum ofputil_protocol allowed_protocols = OFPUTIL_P_ANY;
73
74 /* -P, --packet-in-format: Packet IN format to use in monitor and snoop
75  * commands.  Either one of NXPIF_* to force a particular packet_in format, or
76  * -1 to let ovs-ofctl choose the default. */
77 static int preferred_packet_in_format = -1;
78
79 /* -m, --more: Additional verbosity for ofp-print functions. */
80 static int verbosity;
81
82 /* --timestamp: Print a timestamp before each received packet on "monitor" and
83  * "snoop" command? */
84 static bool timestamp;
85
86 static const struct command all_commands[];
87
88 static void usage(void) NO_RETURN;
89 static void parse_options(int argc, char *argv[]);
90
91 int
92 main(int argc, char *argv[])
93 {
94     set_program_name(argv[0]);
95     parse_options(argc, argv);
96     signal(SIGPIPE, SIG_IGN);
97     run_command(argc - optind, argv + optind, all_commands);
98     return 0;
99 }
100
101 static void
102 parse_options(int argc, char *argv[])
103 {
104     enum {
105         OPT_STRICT = UCHAR_MAX + 1,
106         OPT_READD,
107         OPT_TIMESTAMP,
108         DAEMON_OPTION_ENUMS,
109         VLOG_OPTION_ENUMS
110     };
111     static struct option long_options[] = {
112         {"timeout", required_argument, NULL, 't'},
113         {"strict", no_argument, NULL, OPT_STRICT},
114         {"readd", no_argument, NULL, OPT_READD},
115         {"flow-format", required_argument, NULL, 'F'},
116         {"packet-in-format", required_argument, NULL, 'P'},
117         {"more", no_argument, NULL, 'm'},
118         {"timestamp", no_argument, NULL, OPT_TIMESTAMP},
119         {"help", no_argument, NULL, 'h'},
120         {"version", no_argument, NULL, 'V'},
121         DAEMON_LONG_OPTIONS,
122         VLOG_LONG_OPTIONS,
123         STREAM_SSL_LONG_OPTIONS,
124         {NULL, 0, NULL, 0},
125     };
126     char *short_options = long_options_to_short_options(long_options);
127
128     for (;;) {
129         unsigned long int timeout;
130         int c;
131
132         c = getopt_long(argc, argv, short_options, long_options, NULL);
133         if (c == -1) {
134             break;
135         }
136
137         switch (c) {
138         case 't':
139             timeout = strtoul(optarg, NULL, 10);
140             if (timeout <= 0) {
141                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
142                           optarg);
143             } else {
144                 time_alarm(timeout);
145             }
146             break;
147
148         case 'F':
149             allowed_protocols = ofputil_protocols_from_string(optarg);
150             if (!allowed_protocols) {
151                 ovs_fatal(0, "%s: invalid flow format(s)", optarg);
152             }
153             break;
154
155         case 'P':
156             preferred_packet_in_format =
157                 ofputil_packet_in_format_from_string(optarg);
158             if (preferred_packet_in_format < 0) {
159                 ovs_fatal(0, "unknown packet-in format `%s'", optarg);
160             }
161             break;
162
163         case 'm':
164             verbosity++;
165             break;
166
167         case 'h':
168             usage();
169
170         case 'V':
171             ovs_print_version(OFP10_VERSION, OFP10_VERSION);
172             exit(EXIT_SUCCESS);
173
174         case OPT_STRICT:
175             strict = true;
176             break;
177
178         case OPT_READD:
179             readd = true;
180             break;
181
182         case OPT_TIMESTAMP:
183             timestamp = true;
184             break;
185
186         DAEMON_OPTION_HANDLERS
187         VLOG_OPTION_HANDLERS
188         STREAM_SSL_OPTION_HANDLERS
189
190         case '?':
191             exit(EXIT_FAILURE);
192
193         default:
194             abort();
195         }
196     }
197     free(short_options);
198 }
199
200 static void
201 usage(void)
202 {
203     printf("%s: OpenFlow switch management utility\n"
204            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
205            "\nFor OpenFlow switches:\n"
206            "  show SWITCH                 show OpenFlow information\n"
207            "  dump-desc SWITCH            print switch description\n"
208            "  dump-tables SWITCH          print table stats\n"
209            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
210            "  get-frags SWITCH            print fragment handling behavior\n"
211            "  set-frags SWITCH FRAG_MODE  set fragment handling behavior\n"
212            "  dump-ports SWITCH [PORT]    print port statistics\n"
213            "  dump-ports-desc SWITCH      print port descriptions\n"
214            "  dump-flows SWITCH           print all flow entries\n"
215            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
216            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
217            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
218            "  queue-stats SWITCH [PORT [QUEUE]]  dump queue stats\n"
219            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
220            "  add-flows SWITCH FILE       add flows from FILE\n"
221            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
222            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
223            "  replace-flows SWITCH FILE   replace flows with those in FILE\n"
224            "  diff-flows SOURCE1 SOURCE2  compare flows from two sources\n"
225            "  packet-out SWITCH IN_PORT ACTIONS PACKET...\n"
226            "                              execute ACTIONS on PACKET\n"
227            "  monitor SWITCH [MISSLEN] [invalid_ttl]\n"
228            "                              print packets received from SWITCH\n"
229            "  snoop SWITCH                snoop on SWITCH and its controller\n"
230            "\nFor OpenFlow switches and controllers:\n"
231            "  probe TARGET                probe whether TARGET is up\n"
232            "  ping TARGET [N]             latency of N-byte echos\n"
233            "  benchmark TARGET N COUNT    bandwidth of COUNT N-byte echos\n"
234            "where SWITCH or TARGET is an active OpenFlow connection method.\n",
235            program_name, program_name);
236     vconn_usage(true, false, false);
237     daemon_usage();
238     vlog_usage();
239     printf("\nOther options:\n"
240            "  --strict                    use strict match for flow commands\n"
241            "  --readd                     replace flows that haven't changed\n"
242            "  -F, --flow-format=FORMAT    force particular flow format\n"
243            "  -P, --packet-in-format=FRMT force particular packet in format\n"
244            "  -m, --more                  be more verbose printing OpenFlow\n"
245            "  --timestamp                 (monitor, snoop) print timestamps\n"
246            "  -t, --timeout=SECS          give up after SECS seconds\n"
247            "  -h, --help                  display this help message\n"
248            "  -V, --version               display version information\n");
249     exit(EXIT_SUCCESS);
250 }
251
252 static void
253 ofctl_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
254            const char *argv[] OVS_UNUSED, void *exiting_)
255 {
256     bool *exiting = exiting_;
257     *exiting = true;
258     unixctl_command_reply(conn, NULL);
259 }
260
261 static void run(int retval, const char *message, ...)
262     PRINTF_FORMAT(2, 3);
263
264 static void run(int retval, const char *message, ...)
265 {
266     if (retval) {
267         va_list args;
268
269         va_start(args, message);
270         ovs_fatal_valist(retval, message, args);
271     }
272 }
273 \f
274 /* Generic commands. */
275
276 static void
277 open_vconn_socket(const char *name, struct vconn **vconnp)
278 {
279     char *vconn_name = xasprintf("unix:%s", name);
280     VLOG_DBG("connecting to %s", vconn_name);
281     run(vconn_open_block(vconn_name, OFP10_VERSION, vconnp),
282         "connecting to %s", vconn_name);
283     free(vconn_name);
284 }
285
286 static enum ofputil_protocol
287 open_vconn__(const char *name, const char *default_suffix,
288              struct vconn **vconnp)
289 {
290     char *datapath_name, *datapath_type, *socket_name;
291     enum ofputil_protocol protocol;
292     char *bridge_path;
293     int ofp_version;
294     struct stat s;
295
296     bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, default_suffix);
297
298     ofproto_parse_name(name, &datapath_name, &datapath_type);
299     socket_name = xasprintf("%s/%s.%s",
300                             ovs_rundir(), datapath_name, default_suffix);
301     free(datapath_name);
302     free(datapath_type);
303
304     if (strchr(name, ':')) {
305         run(vconn_open_block(name, OFP10_VERSION, vconnp),
306             "connecting to %s", name);
307     } else if (!stat(name, &s) && S_ISSOCK(s.st_mode)) {
308         open_vconn_socket(name, vconnp);
309     } else if (!stat(bridge_path, &s) && S_ISSOCK(s.st_mode)) {
310         open_vconn_socket(bridge_path, vconnp);
311     } else if (!stat(socket_name, &s)) {
312         if (!S_ISSOCK(s.st_mode)) {
313             ovs_fatal(0, "cannot connect to %s: %s is not a socket",
314                       name, socket_name);
315         }
316         open_vconn_socket(socket_name, vconnp);
317     } else {
318         ovs_fatal(0, "%s is not a bridge or a socket", name);
319     }
320
321     free(bridge_path);
322     free(socket_name);
323
324     ofp_version = vconn_get_version(*vconnp);
325     protocol = ofputil_protocol_from_ofp_version(ofp_version);
326     if (!protocol) {
327         ovs_fatal(0, "%s: unsupported OpenFlow version 0x%02x",
328                   name, ofp_version);
329     }
330     return protocol;
331 }
332
333 static enum ofputil_protocol
334 open_vconn(const char *name, struct vconn **vconnp)
335 {
336     return open_vconn__(name, "mgmt", vconnp);
337 }
338
339 static void *
340 alloc_stats_request(size_t rq_len, uint16_t type, struct ofpbuf **bufferp)
341 {
342     struct ofp_stats_msg *rq;
343
344     rq = make_openflow(rq_len, OFPT10_STATS_REQUEST, bufferp);
345     rq->type = htons(type);
346     rq->flags = htons(0);
347     return rq;
348 }
349
350 static void
351 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
352 {
353     update_openflow_length(buffer);
354     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
355 }
356
357 static void
358 dump_transaction(const char *vconn_name, struct ofpbuf *request)
359 {
360     struct vconn *vconn;
361     struct ofpbuf *reply;
362
363     update_openflow_length(request);
364     open_vconn(vconn_name, &vconn);
365     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
366     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
367     ofpbuf_delete(reply);
368     vconn_close(vconn);
369 }
370
371 static void
372 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
373 {
374     struct ofpbuf *request;
375     make_openflow(sizeof(struct ofp_header), request_type, &request);
376     dump_transaction(vconn_name, request);
377 }
378
379 static void
380 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
381 {
382     ovs_be32 send_xid = ((struct ofp_header *) request->data)->xid;
383     struct vconn *vconn;
384     bool done = false;
385
386     open_vconn(vconn_name, &vconn);
387     send_openflow_buffer(vconn, request);
388     while (!done) {
389         ovs_be32 recv_xid;
390         struct ofpbuf *reply;
391
392         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
393         recv_xid = ((struct ofp_header *) reply->data)->xid;
394         if (send_xid == recv_xid) {
395             struct ofp_stats_msg *osm;
396
397             ofp_print(stdout, reply->data, reply->size, verbosity + 1);
398
399             osm = ofpbuf_at(reply, 0, sizeof *osm);
400             done = !osm || !(ntohs(osm->flags) & OFPSF_REPLY_MORE);
401         } else {
402             VLOG_DBG("received reply with xid %08"PRIx32" "
403                      "!= expected %08"PRIx32, recv_xid, send_xid);
404         }
405         ofpbuf_delete(reply);
406     }
407     vconn_close(vconn);
408 }
409
410 static void
411 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
412 {
413     struct ofpbuf *request;
414     alloc_stats_request(sizeof(struct ofp_stats_msg), stats_type, &request);
415     dump_stats_transaction(vconn_name, request);
416 }
417
418 /* Sends 'request', which should be a request that only has a reply if an error
419  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
420  * it and exits with an error.
421  *
422  * Destroys all of the 'requests'. */
423 static void
424 transact_multiple_noreply(struct vconn *vconn, struct list *requests)
425 {
426     struct ofpbuf *request, *reply;
427
428     LIST_FOR_EACH (request, list_node, requests) {
429         update_openflow_length(request);
430     }
431
432     run(vconn_transact_multiple_noreply(vconn, requests, &reply),
433         "talking to %s", vconn_get_name(vconn));
434     if (reply) {
435         ofp_print(stderr, reply->data, reply->size, verbosity + 2);
436         exit(1);
437     }
438     ofpbuf_delete(reply);
439 }
440
441 /* Sends 'request', which should be a request that only has a reply if an error
442  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
443  * it and exits with an error.
444  *
445  * Destroys 'request'. */
446 static void
447 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
448 {
449     struct list requests;
450
451     list_init(&requests);
452     list_push_back(&requests, &request->list_node);
453     transact_multiple_noreply(vconn, &requests);
454 }
455
456 static void
457 fetch_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
458 {
459     struct ofp_switch_config *config;
460     struct ofp_header *header;
461     struct ofpbuf *request;
462     struct ofpbuf *reply;
463
464     make_openflow(sizeof(struct ofp_header), OFPT_GET_CONFIG_REQUEST,
465                   &request);
466     run(vconn_transact(vconn, request, &reply),
467         "talking to %s", vconn_get_name(vconn));
468
469     header = reply->data;
470     if (header->type != OFPT_GET_CONFIG_REPLY ||
471         header->length != htons(sizeof *config)) {
472         ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
473     }
474
475     config = reply->data;
476     *config_ = *config;
477
478     ofpbuf_delete(reply);
479 }
480
481 static void
482 set_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
483 {
484     struct ofp_switch_config *config;
485     struct ofp_header save_header;
486     struct ofpbuf *request;
487
488     config = make_openflow(sizeof *config, OFPT_SET_CONFIG, &request);
489     save_header = config->header;
490     *config = *config_;
491     config->header = save_header;
492
493     transact_noreply(vconn, request);
494 }
495
496 static void
497 do_show(int argc OVS_UNUSED, char *argv[])
498 {
499     const char *vconn_name = argv[1];
500     struct vconn *vconn;
501     struct ofpbuf *request;
502     struct ofpbuf *reply;
503     bool trunc;
504
505     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST,
506                   &request);
507     open_vconn(vconn_name, &vconn);
508     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
509
510     trunc = ofputil_switch_features_ports_trunc(reply);
511     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
512
513     ofpbuf_delete(reply);
514     vconn_close(vconn);
515
516     if (trunc) {
517         /* The Features Reply may not contain all the ports, so send a
518          * Port Description stats request, which doesn't have size
519          * constraints. */
520         dump_trivial_stats_transaction(vconn_name, OFPST_PORT_DESC);
521     }
522     dump_trivial_transaction(vconn_name, OFPT_GET_CONFIG_REQUEST);
523 }
524
525 static void
526 do_dump_desc(int argc OVS_UNUSED, char *argv[])
527 {
528     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
529 }
530
531 static void
532 do_dump_tables(int argc OVS_UNUSED, char *argv[])
533 {
534     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
535 }
536
537 static bool
538 fetch_port_by_features(const char *vconn_name,
539                        const char *port_name, unsigned int port_no,
540                        struct ofputil_phy_port *pp, bool *trunc)
541 {
542     struct ofputil_switch_features features;
543     const struct ofp_switch_features *osf;
544     struct ofpbuf *request, *reply;
545     struct vconn *vconn;
546     enum ofperr error;
547     struct ofpbuf b;
548     bool found = false;
549
550     /* Fetch the switch's ofp_switch_features. */
551     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
552     open_vconn(vconn_name, &vconn);
553     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
554     vconn_close(vconn);
555
556     osf = reply->data;
557     if (reply->size < sizeof *osf) {
558         ovs_fatal(0, "%s: received too-short features reply (only %zu bytes)",
559                   vconn_name, reply->size);
560     }
561
562     *trunc = false;
563     if (ofputil_switch_features_ports_trunc(reply)) {
564         *trunc = true;
565         goto exit;
566     }
567
568     error = ofputil_decode_switch_features(osf, &features, &b);
569     if (error) {
570         ovs_fatal(0, "%s: failed to decode features reply (%s)",
571                   vconn_name, ofperr_to_string(error));
572     }
573
574     while (!ofputil_pull_phy_port(osf->header.version, &b, pp)) {
575         if (port_no != UINT_MAX
576             ? port_no == pp->port_no
577             : !strcmp(pp->name, port_name)) {
578             found = true;
579             goto exit;
580         }
581     }
582
583 exit:
584     ofpbuf_delete(reply);
585     return found;
586 }
587
588 static bool
589 fetch_port_by_stats(const char *vconn_name,
590                     const char *port_name, unsigned int port_no,
591                     struct ofputil_phy_port *pp)
592 {
593     struct ofpbuf *request;
594     struct vconn *vconn;
595     ovs_be32 send_xid;
596     struct ofpbuf b;
597     bool done = false;
598     bool found = false;
599
600     alloc_stats_request(sizeof(struct ofp_stats_msg), OFPST_PORT_DESC,
601                         &request);
602     send_xid = ((struct ofp_header *) request->data)->xid;
603
604     open_vconn(vconn_name, &vconn);
605     send_openflow_buffer(vconn, request);
606     while (!done) {
607         ovs_be32 recv_xid;
608         struct ofpbuf *reply;
609
610         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
611         recv_xid = ((struct ofp_header *) reply->data)->xid;
612         if (send_xid == recv_xid) {
613             const struct ofputil_msg_type *type;
614             struct ofp_stats_msg *osm;
615
616             ofputil_decode_msg_type(reply->data, &type);
617             if (ofputil_msg_type_code(type) != OFPUTIL_OFPST_PORT_DESC_REPLY) {
618                 ovs_fatal(0, "received bad reply: %s",
619                           ofp_to_string(reply->data, reply->size,
620                                         verbosity + 1));
621             }
622
623             osm = ofpbuf_at_assert(reply, 0, sizeof *osm);
624             done = !(ntohs(osm->flags) & OFPSF_REPLY_MORE);
625
626             if (found) {
627                 /* We've already found the port, but we need to drain
628                  * the queue of any other replies for this request. */
629                 continue;
630             }
631
632             ofpbuf_use_const(&b, &osm->header, ntohs(osm->header.length));
633             ofpbuf_pull(&b, sizeof(struct ofp_stats_msg));
634
635             while (!ofputil_pull_phy_port(osm->header.version, &b, pp)) {
636                 if (port_no != UINT_MAX ? port_no == pp->port_no
637                                         : !strcmp(pp->name, port_name)) {
638                     found = true;
639                     break;
640                 }
641             }
642         } else {
643             VLOG_DBG("received reply with xid %08"PRIx32" "
644                      "!= expected %08"PRIx32, recv_xid, send_xid);
645         }
646         ofpbuf_delete(reply);
647     }
648     vconn_close(vconn);
649
650     return found;
651 }
652
653
654 /* Opens a connection to 'vconn_name', fetches the port structure for
655  * 'port_name' (which may be a port name or number), and copies it into
656  * '*pp'. */
657 static void
658 fetch_ofputil_phy_port(const char *vconn_name, const char *port_name,
659                        struct ofputil_phy_port *pp)
660 {
661     unsigned int port_no;
662     bool found;
663     bool trunc;
664
665     /* Try to interpret the argument as a port number. */
666     if (!str_to_uint(port_name, 10, &port_no)) {
667         port_no = UINT_MAX;
668     }
669
670     /* Try to find the port based on the Features Reply.  If it looks
671      * like the results may be truncated, then use the Port Description
672      * stats message introduced in OVS 1.7. */
673     found = fetch_port_by_features(vconn_name, port_name, port_no, pp,
674                                    &trunc);
675     if (trunc) {
676         found = fetch_port_by_stats(vconn_name, port_name, port_no, pp);
677     }
678
679     if (!found) {
680         ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
681     }
682 }
683
684 /* Returns the port number corresponding to 'port_name' (which may be a port
685  * name or number) within the switch 'vconn_name'. */
686 static uint16_t
687 str_to_port_no(const char *vconn_name, const char *port_name)
688 {
689     unsigned int port_no;
690
691     if (str_to_uint(port_name, 10, &port_no)) {
692         return port_no;
693     } else {
694         struct ofputil_phy_port pp;
695
696         fetch_ofputil_phy_port(vconn_name, port_name, &pp);
697         return pp.port_no;
698     }
699 }
700
701 static bool
702 try_set_protocol(struct vconn *vconn, enum ofputil_protocol want,
703                  enum ofputil_protocol *cur)
704 {
705     for (;;) {
706         struct ofpbuf *request, *reply;
707         enum ofputil_protocol next;
708
709         request = ofputil_encode_set_protocol(*cur, want, &next);
710         if (!request) {
711             return true;
712         }
713
714         run(vconn_transact_noreply(vconn, request, &reply),
715             "talking to %s", vconn_get_name(vconn));
716         if (reply) {
717             char *s = ofp_to_string(reply->data, reply->size, 2);
718             VLOG_DBG("%s: failed to set protocol, switch replied: %s",
719                      vconn_get_name(vconn), s);
720             free(s);
721             ofpbuf_delete(reply);
722             return false;
723         }
724
725         *cur = next;
726     }
727 }
728
729 static enum ofputil_protocol
730 set_protocol_for_flow_dump(struct vconn *vconn,
731                            enum ofputil_protocol cur_protocol,
732                            enum ofputil_protocol usable_protocols)
733 {
734     char *usable_s;
735     int i;
736
737     for (i = 0; i < ofputil_n_flow_dump_protocols; i++) {
738         enum ofputil_protocol f = ofputil_flow_dump_protocols[i];
739         if (f & usable_protocols & allowed_protocols
740             && try_set_protocol(vconn, f, &cur_protocol)) {
741             return f;
742         }
743     }
744
745     usable_s = ofputil_protocols_to_string(usable_protocols);
746     if (usable_protocols & allowed_protocols) {
747         ovs_fatal(0, "switch does not support any of the usable flow "
748                   "formats (%s)", usable_s);
749     } else {
750         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
751         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
752                   "allowed flow formats (%s)", usable_s, allowed_s);
753     }
754 }
755
756 static void
757 do_dump_flows__(int argc, char *argv[], bool aggregate)
758 {
759     enum ofputil_protocol usable_protocols, protocol;
760     struct ofputil_flow_stats_request fsr;
761     struct ofpbuf *request;
762     struct vconn *vconn;
763
764     parse_ofp_flow_stats_request_str(&fsr, aggregate, argc > 2 ? argv[2] : "");
765     usable_protocols = ofputil_flow_stats_request_usable_protocols(&fsr);
766
767     protocol = open_vconn(argv[1], &vconn);
768     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
769     request = ofputil_encode_flow_stats_request(&fsr, protocol);
770     dump_stats_transaction(argv[1], request);
771     vconn_close(vconn);
772 }
773
774 static void
775 do_dump_flows(int argc, char *argv[])
776 {
777     return do_dump_flows__(argc, argv, false);
778 }
779
780 static void
781 do_dump_aggregate(int argc, char *argv[])
782 {
783     return do_dump_flows__(argc, argv, true);
784 }
785
786 static void
787 do_queue_stats(int argc, char *argv[])
788 {
789     struct ofp_queue_stats_request *req;
790     struct ofpbuf *request;
791
792     req = alloc_stats_request(sizeof *req, OFPST_QUEUE, &request);
793
794     if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
795         req->port_no = htons(str_to_port_no(argv[1], argv[2]));
796     } else {
797         req->port_no = htons(OFPP_ALL);
798     }
799     if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
800         req->queue_id = htonl(atoi(argv[3]));
801     } else {
802         req->queue_id = htonl(OFPQ_ALL);
803     }
804
805     memset(req->pad, 0, sizeof req->pad);
806
807     dump_stats_transaction(argv[1], request);
808 }
809
810 static enum ofputil_protocol
811 open_vconn_for_flow_mod(const char *remote,
812                         const struct ofputil_flow_mod *fms, size_t n_fms,
813                         struct vconn **vconnp)
814 {
815     enum ofputil_protocol usable_protocols;
816     enum ofputil_protocol cur_protocol;
817     char *usable_s;
818     int i;
819
820     /* Figure out what flow formats will work. */
821     usable_protocols = ofputil_flow_mod_usable_protocols(fms, n_fms);
822     if (!(usable_protocols & allowed_protocols)) {
823         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
824         usable_s = ofputil_protocols_to_string(usable_protocols);
825         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
826                   "allowed flow formats (%s)", usable_s, allowed_s);
827     }
828
829     /* If the initial flow format is allowed and usable, keep it. */
830     cur_protocol = open_vconn(remote, vconnp);
831     if (usable_protocols & allowed_protocols & cur_protocol) {
832         return cur_protocol;
833     }
834
835     /* Otherwise try each flow format in turn. */
836     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
837         enum ofputil_protocol f = 1 << i;
838
839         if (f != cur_protocol
840             && f & usable_protocols & allowed_protocols
841             && try_set_protocol(*vconnp, f, &cur_protocol)) {
842             return f;
843         }
844     }
845
846     usable_s = ofputil_protocols_to_string(usable_protocols);
847     ovs_fatal(0, "switch does not support any of the usable flow "
848               "formats (%s)", usable_s);
849 }
850
851 static void
852 do_flow_mod__(const char *remote, struct ofputil_flow_mod *fms, size_t n_fms)
853 {
854     enum ofputil_protocol protocol;
855     struct vconn *vconn;
856     size_t i;
857
858     protocol = open_vconn_for_flow_mod(remote, fms, n_fms, &vconn);
859
860     for (i = 0; i < n_fms; i++) {
861         struct ofputil_flow_mod *fm = &fms[i];
862
863         transact_noreply(vconn, ofputil_encode_flow_mod(fm, protocol));
864         free(fm->actions);
865     }
866     vconn_close(vconn);
867 }
868
869 static void
870 do_flow_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
871 {
872     struct ofputil_flow_mod *fms = NULL;
873     size_t n_fms = 0;
874
875     parse_ofp_flow_mod_file(argv[2], command, &fms, &n_fms);
876     do_flow_mod__(argv[1], fms, n_fms);
877     free(fms);
878 }
879
880 static void
881 do_flow_mod(int argc, char *argv[], uint16_t command)
882 {
883     if (argc > 2 && !strcmp(argv[2], "-")) {
884         do_flow_mod_file(argc, argv, command);
885     } else {
886         struct ofputil_flow_mod fm;
887         parse_ofp_flow_mod_str(&fm, argc > 2 ? argv[2] : "", command, false);
888         do_flow_mod__(argv[1], &fm, 1);
889     }
890 }
891
892 static void
893 do_add_flow(int argc, char *argv[])
894 {
895     do_flow_mod(argc, argv, OFPFC_ADD);
896 }
897
898 static void
899 do_add_flows(int argc, char *argv[])
900 {
901     do_flow_mod_file(argc, argv, OFPFC_ADD);
902 }
903
904 static void
905 do_mod_flows(int argc, char *argv[])
906 {
907     do_flow_mod(argc, argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
908 }
909
910 static void
911 do_del_flows(int argc, char *argv[])
912 {
913     do_flow_mod(argc, argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
914 }
915
916 static void
917 set_packet_in_format(struct vconn *vconn,
918                      enum nx_packet_in_format packet_in_format)
919 {
920     struct ofpbuf *spif = ofputil_make_set_packet_in_format(packet_in_format);
921     transact_noreply(vconn, spif);
922     VLOG_DBG("%s: using user-specified packet in format %s",
923              vconn_get_name(vconn),
924              ofputil_packet_in_format_to_string(packet_in_format));
925 }
926
927 static int
928 monitor_set_invalid_ttl_to_controller(struct vconn *vconn)
929 {
930     struct ofp_switch_config config;
931     enum ofp_config_flags flags;
932
933     fetch_switch_config(vconn, &config);
934     flags = ntohs(config.flags);
935     if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
936         /* Set the invalid ttl config. */
937         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
938
939         config.flags = htons(flags);
940         set_switch_config(vconn, &config);
941
942         /* Then retrieve the configuration to see if it really took.  OpenFlow
943          * doesn't define error reporting for bad modes, so this is all we can
944          * do. */
945         fetch_switch_config(vconn, &config);
946         flags = ntohs(config.flags);
947         if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
948             ovs_fatal(0, "setting invalid_ttl_to_controller failed (this "
949                       "switch probably doesn't support mode)");
950             return -EOPNOTSUPP;
951         }
952     }
953     return 0;
954 }
955
956 /* Converts hex digits in 'hex' to an OpenFlow message in '*msgp'.  The
957  * caller must free '*msgp'.  On success, returns NULL.  On failure, returns
958  * an error message and stores NULL in '*msgp'. */
959 static const char *
960 openflow_from_hex(const char *hex, struct ofpbuf **msgp)
961 {
962     struct ofp_header *oh;
963     struct ofpbuf *msg;
964
965     msg = ofpbuf_new(strlen(hex) / 2);
966     *msgp = NULL;
967
968     if (ofpbuf_put_hex(msg, hex, NULL)[0] != '\0') {
969         ofpbuf_delete(msg);
970         return "Trailing garbage in hex data";
971     }
972
973     if (msg->size < sizeof(struct ofp_header)) {
974         ofpbuf_delete(msg);
975         return "Message too short for OpenFlow";
976     }
977
978     oh = msg->data;
979     if (msg->size != ntohs(oh->length)) {
980         ofpbuf_delete(msg);
981         return "Message size does not match length in OpenFlow header";
982     }
983
984     *msgp = msg;
985     return NULL;
986 }
987
988 static void
989 ofctl_send(struct unixctl_conn *conn, int argc,
990            const char *argv[], void *vconn_)
991 {
992     struct vconn *vconn = vconn_;
993     struct ds reply;
994     bool ok;
995     int i;
996
997     ok = true;
998     ds_init(&reply);
999     for (i = 1; i < argc; i++) {
1000         const char *error_msg;
1001         struct ofpbuf *msg;
1002         int error;
1003
1004         error_msg = openflow_from_hex(argv[i], &msg);
1005         if (error_msg) {
1006             ds_put_format(&reply, "%s\n", error_msg);
1007             ok = false;
1008             continue;
1009         }
1010
1011         fprintf(stderr, "send: ");
1012         ofp_print(stderr, msg->data, msg->size, verbosity);
1013
1014         error = vconn_send_block(vconn, msg);
1015         if (error) {
1016             ofpbuf_delete(msg);
1017             ds_put_format(&reply, "%s\n", strerror(error));
1018             ok = false;
1019         } else {
1020             ds_put_cstr(&reply, "sent\n");
1021         }
1022     }
1023
1024     if (ok) {
1025         unixctl_command_reply(conn, ds_cstr(&reply));
1026     } else {
1027         unixctl_command_reply_error(conn, ds_cstr(&reply));
1028     }
1029     ds_destroy(&reply);
1030 }
1031
1032 struct barrier_aux {
1033     struct vconn *vconn;        /* OpenFlow connection for sending barrier. */
1034     struct unixctl_conn *conn;  /* Connection waiting for barrier response. */
1035 };
1036
1037 static void
1038 ofctl_barrier(struct unixctl_conn *conn, int argc OVS_UNUSED,
1039               const char *argv[] OVS_UNUSED, void *aux_)
1040 {
1041     struct barrier_aux *aux = aux_;
1042     struct ofpbuf *msg;
1043     int error;
1044
1045     if (aux->conn) {
1046         unixctl_command_reply_error(conn, "already waiting for barrier reply");
1047         return;
1048     }
1049
1050     msg = ofputil_encode_barrier_request();
1051     error = vconn_send_block(aux->vconn, msg);
1052     if (error) {
1053         ofpbuf_delete(msg);
1054         unixctl_command_reply_error(conn, strerror(error));
1055     } else {
1056         aux->conn = conn;
1057     }
1058 }
1059
1060 static void
1061 ofctl_set_output_file(struct unixctl_conn *conn, int argc OVS_UNUSED,
1062                       const char *argv[], void *aux OVS_UNUSED)
1063 {
1064     int fd;
1065
1066     fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
1067     if (fd < 0) {
1068         unixctl_command_reply_error(conn, strerror(errno));
1069         return;
1070     }
1071
1072     fflush(stderr);
1073     dup2(fd, STDERR_FILENO);
1074     close(fd);
1075     unixctl_command_reply(conn, NULL);
1076 }
1077
1078 static void
1079 monitor_vconn(struct vconn *vconn)
1080 {
1081     struct barrier_aux barrier_aux = { vconn, NULL };
1082     struct unixctl_server *server;
1083     bool exiting = false;
1084     int error;
1085
1086     daemon_save_fd(STDERR_FILENO);
1087     daemonize_start();
1088     error = unixctl_server_create(NULL, &server);
1089     if (error) {
1090         ovs_fatal(error, "failed to create unixctl server");
1091     }
1092     unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
1093     unixctl_command_register("ofctl/send", "OFMSG...", 1, INT_MAX,
1094                              ofctl_send, vconn);
1095     unixctl_command_register("ofctl/barrier", "", 0, 0,
1096                              ofctl_barrier, &barrier_aux);
1097     unixctl_command_register("ofctl/set-output-file", "FILE", 1, 1,
1098                              ofctl_set_output_file, NULL);
1099     daemonize_complete();
1100
1101     for (;;) {
1102         struct ofpbuf *b;
1103         int retval;
1104
1105         unixctl_server_run(server);
1106
1107         for (;;) {
1108             uint8_t msg_type;
1109
1110             retval = vconn_recv(vconn, &b);
1111             if (retval == EAGAIN) {
1112                 break;
1113             }
1114             run(retval, "vconn_recv");
1115
1116             if (timestamp) {
1117                 time_t now = time_wall();
1118                 char s[32];
1119
1120                 strftime(s, sizeof s, "%Y-%m-%d %H:%M:%S: ", localtime(&now));
1121                 fputs(s, stderr);
1122             }
1123
1124             msg_type = ((const struct ofp_header *) b->data)->type;
1125             ofp_print(stderr, b->data, b->size, verbosity + 2);
1126             ofpbuf_delete(b);
1127
1128             if (barrier_aux.conn && msg_type == OFPT10_BARRIER_REPLY) {
1129                 unixctl_command_reply(barrier_aux.conn, NULL);
1130                 barrier_aux.conn = NULL;
1131             }
1132         }
1133
1134         if (exiting) {
1135             break;
1136         }
1137
1138         vconn_run(vconn);
1139         vconn_run_wait(vconn);
1140         vconn_recv_wait(vconn);
1141         unixctl_server_wait(server);
1142         poll_block();
1143     }
1144     vconn_close(vconn);
1145     unixctl_server_destroy(server);
1146 }
1147
1148 static void
1149 do_monitor(int argc, char *argv[])
1150 {
1151     struct vconn *vconn;
1152
1153     open_vconn(argv[1], &vconn);
1154     if (argc > 2) {
1155         struct ofp_switch_config config;
1156
1157         fetch_switch_config(vconn, &config);
1158         config.miss_send_len = htons(atoi(argv[2]));
1159         set_switch_config(vconn, &config);
1160     }
1161     if (argc > 3) {
1162         if (!strcmp(argv[3], "invalid_ttl")) {
1163             monitor_set_invalid_ttl_to_controller(vconn);
1164         }
1165     }
1166     if (preferred_packet_in_format >= 0) {
1167         set_packet_in_format(vconn, preferred_packet_in_format);
1168     } else {
1169         struct ofpbuf *spif, *reply;
1170
1171         spif = ofputil_make_set_packet_in_format(NXPIF_NXM);
1172         run(vconn_transact_noreply(vconn, spif, &reply),
1173             "talking to %s", vconn_get_name(vconn));
1174         if (reply) {
1175             char *s = ofp_to_string(reply->data, reply->size, 2);
1176             VLOG_DBG("%s: failed to set packet in format to nxm, controller"
1177                      " replied: %s. Falling back to the switch default.",
1178                      vconn_get_name(vconn), s);
1179             free(s);
1180             ofpbuf_delete(reply);
1181         }
1182     }
1183
1184     monitor_vconn(vconn);
1185 }
1186
1187 static void
1188 do_snoop(int argc OVS_UNUSED, char *argv[])
1189 {
1190     struct vconn *vconn;
1191
1192     open_vconn__(argv[1], "snoop", &vconn);
1193     monitor_vconn(vconn);
1194 }
1195
1196 static void
1197 do_dump_ports(int argc, char *argv[])
1198 {
1199     struct ofp_port_stats_request *req;
1200     struct ofpbuf *request;
1201     uint16_t port;
1202
1203     req = alloc_stats_request(sizeof *req, OFPST_PORT, &request);
1204     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_NONE;
1205     req->port_no = htons(port);
1206     dump_stats_transaction(argv[1], request);
1207 }
1208
1209 static void
1210 do_dump_ports_desc(int argc OVS_UNUSED, char *argv[])
1211 {
1212     dump_trivial_stats_transaction(argv[1], OFPST_PORT_DESC);
1213 }
1214
1215 static void
1216 do_probe(int argc OVS_UNUSED, char *argv[])
1217 {
1218     struct ofpbuf *request;
1219     struct vconn *vconn;
1220     struct ofpbuf *reply;
1221
1222     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
1223     open_vconn(argv[1], &vconn);
1224     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1225     if (reply->size != sizeof(struct ofp_header)) {
1226         ovs_fatal(0, "reply does not match request");
1227     }
1228     ofpbuf_delete(reply);
1229     vconn_close(vconn);
1230 }
1231
1232 static void
1233 do_packet_out(int argc, char *argv[])
1234 {
1235     struct ofputil_packet_out po;
1236     struct ofpbuf actions;
1237     struct vconn *vconn;
1238     int i;
1239
1240     ofpbuf_init(&actions, sizeof(union ofp_action));
1241     parse_ofp_actions(argv[3], &actions);
1242
1243     po.buffer_id = UINT32_MAX;
1244     po.in_port = (!strcasecmp(argv[2], "none") ? OFPP_NONE
1245                   : !strcasecmp(argv[2], "local") ? OFPP_LOCAL
1246                   : str_to_port_no(argv[1], argv[2]));
1247     po.actions = actions.data;
1248     po.n_actions = actions.size / sizeof(union ofp_action);
1249
1250     open_vconn(argv[1], &vconn);
1251     for (i = 4; i < argc; i++) {
1252         struct ofpbuf *packet, *opo;
1253         const char *error_msg;
1254
1255         error_msg = eth_from_hex(argv[i], &packet);
1256         if (error_msg) {
1257             ovs_fatal(0, "%s", error_msg);
1258         }
1259
1260         po.packet = packet->data;
1261         po.packet_len = packet->size;
1262         opo = ofputil_encode_packet_out(&po);
1263         transact_noreply(vconn, opo);
1264         ofpbuf_delete(packet);
1265     }
1266     vconn_close(vconn);
1267     ofpbuf_uninit(&actions);
1268 }
1269
1270 static void
1271 do_mod_port(int argc OVS_UNUSED, char *argv[])
1272 {
1273     struct ofp_config_flag {
1274         const char *name;             /* The flag's name. */
1275         enum ofputil_port_config bit; /* Bit to turn on or off. */
1276         bool on;                      /* Value to set the bit to. */
1277     };
1278     static const struct ofp_config_flag flags[] = {
1279         { "up",          OFPUTIL_PC_PORT_DOWN,    false },
1280         { "down",        OFPUTIL_PC_PORT_DOWN,    true  },
1281         { "stp",         OFPUTIL_PC_NO_STP,       false },
1282         { "receive",     OFPUTIL_PC_NO_RECV,      false },
1283         { "receive-stp", OFPUTIL_PC_NO_RECV_STP,  false },
1284         { "flood",       OFPUTIL_PC_NO_FLOOD,     false },
1285         { "forward",     OFPUTIL_PC_NO_FWD,       false },
1286         { "packet-in",   OFPUTIL_PC_NO_PACKET_IN, false },
1287     };
1288
1289     const struct ofp_config_flag *flag;
1290     enum ofputil_protocol protocol;
1291     struct ofputil_port_mod pm;
1292     struct ofputil_phy_port pp;
1293     struct vconn *vconn;
1294     const char *command;
1295     bool not;
1296
1297     fetch_ofputil_phy_port(argv[1], argv[2], &pp);
1298
1299     pm.port_no = pp.port_no;
1300     memcpy(pm.hw_addr, pp.hw_addr, ETH_ADDR_LEN);
1301     pm.config = 0;
1302     pm.mask = 0;
1303     pm.advertise = 0;
1304
1305     if (!strncasecmp(argv[3], "no-", 3)) {
1306         command = argv[3] + 3;
1307         not = true;
1308     } else if (!strncasecmp(argv[3], "no", 2)) {
1309         command = argv[3] + 2;
1310         not = true;
1311     } else {
1312         command = argv[3];
1313         not = false;
1314     }
1315     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1316         if (!strcasecmp(command, flag->name)) {
1317             pm.mask = flag->bit;
1318             pm.config = flag->on ^ not ? flag->bit : 0;
1319             goto found;
1320         }
1321     }
1322     ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1323
1324 found:
1325     protocol = open_vconn(argv[1], &vconn);
1326     transact_noreply(vconn, ofputil_encode_port_mod(&pm, protocol));
1327     vconn_close(vconn);
1328 }
1329
1330 static void
1331 do_get_frags(int argc OVS_UNUSED, char *argv[])
1332 {
1333     struct ofp_switch_config config;
1334     struct vconn *vconn;
1335
1336     open_vconn(argv[1], &vconn);
1337     fetch_switch_config(vconn, &config);
1338     puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
1339     vconn_close(vconn);
1340 }
1341
1342 static void
1343 do_set_frags(int argc OVS_UNUSED, char *argv[])
1344 {
1345     struct ofp_switch_config config;
1346     enum ofp_config_flags mode;
1347     struct vconn *vconn;
1348     ovs_be16 flags;
1349
1350     if (!ofputil_frag_handling_from_string(argv[2], &mode)) {
1351         ovs_fatal(0, "%s: unknown fragment handling mode", argv[2]);
1352     }
1353
1354     open_vconn(argv[1], &vconn);
1355     fetch_switch_config(vconn, &config);
1356     flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
1357     if (flags != config.flags) {
1358         /* Set the configuration. */
1359         config.flags = flags;
1360         set_switch_config(vconn, &config);
1361
1362         /* Then retrieve the configuration to see if it really took.  OpenFlow
1363          * doesn't define error reporting for bad modes, so this is all we can
1364          * do. */
1365         fetch_switch_config(vconn, &config);
1366         if (flags != config.flags) {
1367             ovs_fatal(0, "%s: setting fragment handling mode failed (this "
1368                       "switch probably doesn't support mode \"%s\")",
1369                       argv[1], ofputil_frag_handling_to_string(mode));
1370         }
1371     }
1372     vconn_close(vconn);
1373 }
1374
1375 static void
1376 do_ping(int argc, char *argv[])
1377 {
1378     size_t max_payload = 65535 - sizeof(struct ofp_header);
1379     unsigned int payload;
1380     struct vconn *vconn;
1381     int i;
1382
1383     payload = argc > 2 ? atoi(argv[2]) : 64;
1384     if (payload > max_payload) {
1385         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1386     }
1387
1388     open_vconn(argv[1], &vconn);
1389     for (i = 0; i < 10; i++) {
1390         struct timeval start, end;
1391         struct ofpbuf *request, *reply;
1392         struct ofp_header *rq_hdr, *rpy_hdr;
1393
1394         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1395                                OFPT_ECHO_REQUEST, &request);
1396         random_bytes(rq_hdr + 1, payload);
1397
1398         xgettimeofday(&start);
1399         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1400         xgettimeofday(&end);
1401
1402         rpy_hdr = reply->data;
1403         if (reply->size != request->size
1404             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1405             || rpy_hdr->xid != rq_hdr->xid
1406             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1407             printf("Reply does not match request.  Request:\n");
1408             ofp_print(stdout, request, request->size, verbosity + 2);
1409             printf("Reply:\n");
1410             ofp_print(stdout, reply, reply->size, verbosity + 2);
1411         }
1412         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1413                reply->size - sizeof *rpy_hdr, argv[1], ntohl(rpy_hdr->xid),
1414                    (1000*(double)(end.tv_sec - start.tv_sec))
1415                    + (.001*(end.tv_usec - start.tv_usec)));
1416         ofpbuf_delete(request);
1417         ofpbuf_delete(reply);
1418     }
1419     vconn_close(vconn);
1420 }
1421
1422 static void
1423 do_benchmark(int argc OVS_UNUSED, char *argv[])
1424 {
1425     size_t max_payload = 65535 - sizeof(struct ofp_header);
1426     struct timeval start, end;
1427     unsigned int payload_size, message_size;
1428     struct vconn *vconn;
1429     double duration;
1430     int count;
1431     int i;
1432
1433     payload_size = atoi(argv[2]);
1434     if (payload_size > max_payload) {
1435         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1436     }
1437     message_size = sizeof(struct ofp_header) + payload_size;
1438
1439     count = atoi(argv[3]);
1440
1441     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1442            count, message_size, count * message_size);
1443
1444     open_vconn(argv[1], &vconn);
1445     xgettimeofday(&start);
1446     for (i = 0; i < count; i++) {
1447         struct ofpbuf *request, *reply;
1448         struct ofp_header *rq_hdr;
1449
1450         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1451         memset(rq_hdr + 1, 0, payload_size);
1452         run(vconn_transact(vconn, request, &reply), "transact");
1453         ofpbuf_delete(reply);
1454     }
1455     xgettimeofday(&end);
1456     vconn_close(vconn);
1457
1458     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1459                 + (.001*(end.tv_usec - start.tv_usec)));
1460     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1461            duration, count / (duration / 1000.0),
1462            count * message_size / (duration / 1000.0));
1463 }
1464
1465 static void
1466 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1467 {
1468     usage();
1469 }
1470 \f
1471 /* replace-flows and diff-flows commands. */
1472
1473 /* A flow table entry, possibly with two different versions. */
1474 struct fte {
1475     struct cls_rule rule;       /* Within a "struct classifier". */
1476     struct fte_version *versions[2];
1477 };
1478
1479 /* One version of a Flow Table Entry. */
1480 struct fte_version {
1481     ovs_be64 cookie;
1482     uint16_t idle_timeout;
1483     uint16_t hard_timeout;
1484     uint16_t flags;
1485     union ofp_action *actions;
1486     size_t n_actions;
1487 };
1488
1489 /* Frees 'version' and the data that it owns. */
1490 static void
1491 fte_version_free(struct fte_version *version)
1492 {
1493     if (version) {
1494         free(version->actions);
1495         free(version);
1496     }
1497 }
1498
1499 /* Returns true if 'a' and 'b' are the same, false if they differ.
1500  *
1501  * Ignores differences in 'flags' because there's no way to retrieve flags from
1502  * an OpenFlow switch.  We have to assume that they are the same. */
1503 static bool
1504 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
1505 {
1506     return (a->cookie == b->cookie
1507             && a->idle_timeout == b->idle_timeout
1508             && a->hard_timeout == b->hard_timeout
1509             && a->n_actions == b->n_actions
1510             && !memcmp(a->actions, b->actions,
1511                        a->n_actions * sizeof *a->actions));
1512 }
1513
1514 /* Prints 'version' on stdout.  Expects the caller to have printed the rule
1515  * associated with the version. */
1516 static void
1517 fte_version_print(const struct fte_version *version)
1518 {
1519     struct ds s;
1520
1521     if (version->cookie != htonll(0)) {
1522         printf(" cookie=0x%"PRIx64, ntohll(version->cookie));
1523     }
1524     if (version->idle_timeout != OFP_FLOW_PERMANENT) {
1525         printf(" idle_timeout=%"PRIu16, version->idle_timeout);
1526     }
1527     if (version->hard_timeout != OFP_FLOW_PERMANENT) {
1528         printf(" hard_timeout=%"PRIu16, version->hard_timeout);
1529     }
1530
1531     ds_init(&s);
1532     ofp_print_actions(&s, version->actions, version->n_actions);
1533     printf(" %s\n", ds_cstr(&s));
1534     ds_destroy(&s);
1535 }
1536
1537 static struct fte *
1538 fte_from_cls_rule(const struct cls_rule *cls_rule)
1539 {
1540     return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
1541 }
1542
1543 /* Frees 'fte' and its versions. */
1544 static void
1545 fte_free(struct fte *fte)
1546 {
1547     if (fte) {
1548         fte_version_free(fte->versions[0]);
1549         fte_version_free(fte->versions[1]);
1550         free(fte);
1551     }
1552 }
1553
1554 /* Frees all of the FTEs within 'cls'. */
1555 static void
1556 fte_free_all(struct classifier *cls)
1557 {
1558     struct cls_cursor cursor;
1559     struct fte *fte, *next;
1560
1561     cls_cursor_init(&cursor, cls, NULL);
1562     CLS_CURSOR_FOR_EACH_SAFE (fte, next, rule, &cursor) {
1563         classifier_remove(cls, &fte->rule);
1564         fte_free(fte);
1565     }
1566     classifier_destroy(cls);
1567 }
1568
1569 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
1570  * necessary.  Sets 'version' as the version of that rule with the given
1571  * 'index', replacing any existing version, if any.
1572  *
1573  * Takes ownership of 'version'. */
1574 static void
1575 fte_insert(struct classifier *cls, const struct cls_rule *rule,
1576            struct fte_version *version, int index)
1577 {
1578     struct fte *old, *fte;
1579
1580     fte = xzalloc(sizeof *fte);
1581     fte->rule = *rule;
1582     fte->versions[index] = version;
1583
1584     old = fte_from_cls_rule(classifier_replace(cls, &fte->rule));
1585     if (old) {
1586         fte_version_free(old->versions[index]);
1587         fte->versions[!index] = old->versions[!index];
1588         free(old);
1589     }
1590 }
1591
1592 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
1593  * with the specified 'index'.  Returns the flow formats able to represent the
1594  * flows that were read. */
1595 static enum ofputil_protocol
1596 read_flows_from_file(const char *filename, struct classifier *cls, int index)
1597 {
1598     enum ofputil_protocol usable_protocols;
1599     struct ds s;
1600     FILE *file;
1601
1602     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
1603     if (file == NULL) {
1604         ovs_fatal(errno, "%s: open", filename);
1605     }
1606
1607     ds_init(&s);
1608     usable_protocols = OFPUTIL_P_ANY;
1609     while (!ds_get_preprocessed_line(&s, file)) {
1610         struct fte_version *version;
1611         struct ofputil_flow_mod fm;
1612
1613         parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), true);
1614
1615         version = xmalloc(sizeof *version);
1616         version->cookie = fm.new_cookie;
1617         version->idle_timeout = fm.idle_timeout;
1618         version->hard_timeout = fm.hard_timeout;
1619         version->flags = fm.flags & (OFPFF_SEND_FLOW_REM | OFPFF_EMERG);
1620         version->actions = fm.actions;
1621         version->n_actions = fm.n_actions;
1622
1623         usable_protocols &= ofputil_usable_protocols(&fm.cr);
1624
1625         fte_insert(cls, &fm.cr, version, index);
1626     }
1627     ds_destroy(&s);
1628
1629     if (file != stdin) {
1630         fclose(file);
1631     }
1632
1633     return usable_protocols;
1634 }
1635
1636 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
1637  * format 'protocol', and adds them as flow table entries in 'cls' for the
1638  * version with the specified 'index'. */
1639 static void
1640 read_flows_from_switch(struct vconn *vconn,
1641                        enum ofputil_protocol protocol,
1642                        struct classifier *cls, int index)
1643 {
1644     struct ofputil_flow_stats_request fsr;
1645     struct ofpbuf *request;
1646     ovs_be32 send_xid;
1647     bool done;
1648
1649     fsr.aggregate = false;
1650     cls_rule_init_catchall(&fsr.match, 0);
1651     fsr.out_port = OFPP_NONE;
1652     fsr.table_id = 0xff;
1653     fsr.cookie = fsr.cookie_mask = htonll(0);
1654     request = ofputil_encode_flow_stats_request(&fsr, protocol);
1655     send_xid = ((struct ofp_header *) request->data)->xid;
1656     send_openflow_buffer(vconn, request);
1657
1658     done = false;
1659     while (!done) {
1660         ovs_be32 recv_xid;
1661         struct ofpbuf *reply;
1662
1663         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
1664         recv_xid = ((struct ofp_header *) reply->data)->xid;
1665         if (send_xid == recv_xid) {
1666             const struct ofputil_msg_type *type;
1667             const struct ofp_stats_msg *osm;
1668             enum ofputil_msg_code code;
1669
1670             ofputil_decode_msg_type(reply->data, &type);
1671             code = ofputil_msg_type_code(type);
1672             if (code != OFPUTIL_OFPST_FLOW_REPLY &&
1673                 code != OFPUTIL_NXST_FLOW_REPLY) {
1674                 ovs_fatal(0, "received bad reply: %s",
1675                           ofp_to_string(reply->data, reply->size,
1676                                         verbosity + 1));
1677             }
1678
1679             osm = reply->data;
1680             if (!(osm->flags & htons(OFPSF_REPLY_MORE))) {
1681                 done = true;
1682             }
1683
1684             for (;;) {
1685                 struct fte_version *version;
1686                 struct ofputil_flow_stats fs;
1687                 int retval;
1688
1689                 retval = ofputil_decode_flow_stats_reply(&fs, reply, false);
1690                 if (retval) {
1691                     if (retval != EOF) {
1692                         ovs_fatal(0, "parse error in reply");
1693                     }
1694                     break;
1695                 }
1696
1697                 version = xmalloc(sizeof *version);
1698                 version->cookie = fs.cookie;
1699                 version->idle_timeout = fs.idle_timeout;
1700                 version->hard_timeout = fs.hard_timeout;
1701                 version->flags = 0;
1702                 version->n_actions = fs.n_actions;
1703                 version->actions = xmemdup(fs.actions,
1704                                            fs.n_actions * sizeof *fs.actions);
1705
1706                 fte_insert(cls, &fs.rule, version, index);
1707             }
1708         } else {
1709             VLOG_DBG("received reply with xid %08"PRIx32" "
1710                      "!= expected %08"PRIx32, recv_xid, send_xid);
1711         }
1712         ofpbuf_delete(reply);
1713     }
1714 }
1715
1716 static void
1717 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
1718                   enum ofputil_protocol protocol, struct list *packets)
1719 {
1720     const struct fte_version *version = fte->versions[index];
1721     struct ofputil_flow_mod fm;
1722     struct ofpbuf *ofm;
1723
1724     fm.cr = fte->rule;
1725     fm.cookie = htonll(0);
1726     fm.cookie_mask = htonll(0);
1727     fm.new_cookie = version->cookie;
1728     fm.table_id = 0xff;
1729     fm.command = command;
1730     fm.idle_timeout = version->idle_timeout;
1731     fm.hard_timeout = version->hard_timeout;
1732     fm.buffer_id = UINT32_MAX;
1733     fm.out_port = OFPP_NONE;
1734     fm.flags = version->flags;
1735     if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
1736         command == OFPFC_MODIFY_STRICT) {
1737         fm.actions = version->actions;
1738         fm.n_actions = version->n_actions;
1739     } else {
1740         fm.actions = NULL;
1741         fm.n_actions = 0;
1742     }
1743
1744     ofm = ofputil_encode_flow_mod(&fm, protocol);
1745     list_push_back(packets, &ofm->list_node);
1746 }
1747
1748 static void
1749 do_replace_flows(int argc OVS_UNUSED, char *argv[])
1750 {
1751     enum { FILE_IDX = 0, SWITCH_IDX = 1 };
1752     enum ofputil_protocol usable_protocols, protocol;
1753     struct cls_cursor cursor;
1754     struct classifier cls;
1755     struct list requests;
1756     struct vconn *vconn;
1757     struct fte *fte;
1758
1759     classifier_init(&cls);
1760     usable_protocols = read_flows_from_file(argv[2], &cls, FILE_IDX);
1761
1762     protocol = open_vconn(argv[1], &vconn);
1763     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
1764
1765     read_flows_from_switch(vconn, protocol, &cls, SWITCH_IDX);
1766
1767     list_init(&requests);
1768
1769     /* Delete flows that exist on the switch but not in the file. */
1770     cls_cursor_init(&cursor, &cls, NULL);
1771     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1772         struct fte_version *file_ver = fte->versions[FILE_IDX];
1773         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1774
1775         if (sw_ver && !file_ver) {
1776             fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
1777                               protocol, &requests);
1778         }
1779     }
1780
1781     /* Add flows that exist in the file but not on the switch.
1782      * Update flows that exist in both places but differ. */
1783     cls_cursor_init(&cursor, &cls, NULL);
1784     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1785         struct fte_version *file_ver = fte->versions[FILE_IDX];
1786         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1787
1788         if (file_ver
1789             && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
1790             fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, protocol, &requests);
1791         }
1792     }
1793     transact_multiple_noreply(vconn, &requests);
1794     vconn_close(vconn);
1795
1796     fte_free_all(&cls);
1797 }
1798
1799 static void
1800 read_flows_from_source(const char *source, struct classifier *cls, int index)
1801 {
1802     struct stat s;
1803
1804     if (source[0] == '/' || source[0] == '.'
1805         || (!strchr(source, ':') && !stat(source, &s))) {
1806         read_flows_from_file(source, cls, index);
1807     } else {
1808         enum ofputil_protocol protocol;
1809         struct vconn *vconn;
1810
1811         protocol = open_vconn(source, &vconn);
1812         protocol = set_protocol_for_flow_dump(vconn, protocol, OFPUTIL_P_ANY);
1813         read_flows_from_switch(vconn, protocol, cls, index);
1814         vconn_close(vconn);
1815     }
1816 }
1817
1818 static void
1819 do_diff_flows(int argc OVS_UNUSED, char *argv[])
1820 {
1821     bool differences = false;
1822     struct cls_cursor cursor;
1823     struct classifier cls;
1824     struct fte *fte;
1825
1826     classifier_init(&cls);
1827     read_flows_from_source(argv[1], &cls, 0);
1828     read_flows_from_source(argv[2], &cls, 1);
1829
1830     cls_cursor_init(&cursor, &cls, NULL);
1831     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1832         struct fte_version *a = fte->versions[0];
1833         struct fte_version *b = fte->versions[1];
1834
1835         if (!a || !b || !fte_version_equals(a, b)) {
1836             char *rule_s = cls_rule_to_string(&fte->rule);
1837             if (a) {
1838                 printf("-%s", rule_s);
1839                 fte_version_print(a);
1840             }
1841             if (b) {
1842                 printf("+%s", rule_s);
1843                 fte_version_print(b);
1844             }
1845             free(rule_s);
1846
1847             differences = true;
1848         }
1849     }
1850
1851     fte_free_all(&cls);
1852
1853     if (differences) {
1854         exit(2);
1855     }
1856 }
1857 \f
1858 /* Undocumented commands for unit testing. */
1859
1860 static void
1861 do_parse_flows__(struct ofputil_flow_mod *fms, size_t n_fms)
1862 {
1863     enum ofputil_protocol usable_protocols;
1864     enum ofputil_protocol protocol = 0;
1865     char *usable_s;
1866     size_t i;
1867
1868     usable_protocols = ofputil_flow_mod_usable_protocols(fms, n_fms);
1869     usable_s = ofputil_protocols_to_string(usable_protocols);
1870     printf("usable protocols: %s\n", usable_s);
1871     free(usable_s);
1872
1873     if (!(usable_protocols & allowed_protocols)) {
1874         ovs_fatal(0, "no usable protocol");
1875     }
1876     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1877         protocol = 1 << i;
1878         if (protocol & usable_protocols & allowed_protocols) {
1879             break;
1880         }
1881     }
1882     assert(IS_POW2(protocol));
1883
1884     printf("chosen protocol: %s\n", ofputil_protocol_to_string(protocol));
1885
1886     for (i = 0; i < n_fms; i++) {
1887         struct ofputil_flow_mod *fm = &fms[i];
1888         struct ofpbuf *msg;
1889
1890         msg = ofputil_encode_flow_mod(fm, protocol);
1891         ofp_print(stdout, msg->data, msg->size, verbosity);
1892         ofpbuf_delete(msg);
1893
1894         free(fm->actions);
1895     }
1896 }
1897
1898 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
1899  * it back to stdout.  */
1900 static void
1901 do_parse_flow(int argc OVS_UNUSED, char *argv[])
1902 {
1903     struct ofputil_flow_mod fm;
1904
1905     parse_ofp_flow_mod_str(&fm, argv[1], OFPFC_ADD, false);
1906     do_parse_flows__(&fm, 1);
1907 }
1908
1909 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
1910  * add-flows) and prints each of the flows back to stdout.  */
1911 static void
1912 do_parse_flows(int argc OVS_UNUSED, char *argv[])
1913 {
1914     struct ofputil_flow_mod *fms = NULL;
1915     size_t n_fms = 0;
1916
1917     parse_ofp_flow_mod_file(argv[1], OFPFC_ADD, &fms, &n_fms);
1918     do_parse_flows__(fms, n_fms);
1919     free(fms);
1920 }
1921
1922 static void
1923 do_parse_nxm__(bool oxm)
1924 {
1925     struct ds in;
1926
1927     ds_init(&in);
1928     while (!ds_get_test_line(&in, stdin)) {
1929         struct ofpbuf nx_match;
1930         struct cls_rule rule;
1931         ovs_be64 cookie, cookie_mask;
1932         enum ofperr error;
1933         int match_len;
1934
1935         /* Convert string to nx_match. */
1936         ofpbuf_init(&nx_match, 0);
1937         match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
1938
1939         /* Convert nx_match to cls_rule. */
1940         if (strict) {
1941             error = nx_pull_match(&nx_match, match_len, 0, &rule,
1942                                   &cookie, &cookie_mask);
1943         } else {
1944             error = nx_pull_match_loose(&nx_match, match_len, 0, &rule,
1945                                         &cookie, &cookie_mask);
1946         }
1947
1948         if (!error) {
1949             char *out;
1950
1951             /* Convert cls_rule back to nx_match. */
1952             ofpbuf_uninit(&nx_match);
1953             ofpbuf_init(&nx_match, 0);
1954             match_len = nx_put_match(&nx_match, oxm, &rule,
1955                                      cookie, cookie_mask);
1956
1957             /* Convert nx_match to string. */
1958             out = nx_match_to_string(nx_match.data, match_len);
1959             puts(out);
1960             free(out);
1961         } else {
1962             printf("nx_pull_match() returned error %s\n",
1963                    ofperr_get_name(error));
1964         }
1965
1966         ofpbuf_uninit(&nx_match);
1967     }
1968     ds_destroy(&in);
1969 }
1970
1971 /* "parse-nxm": reads a series of NXM nx_match specifications as strings from
1972  * stdin, does some internal fussing with them, and then prints them back as
1973  * strings on stdout. */
1974 static void
1975 do_parse_nxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1976 {
1977     return do_parse_nxm__(false);
1978 }
1979
1980 /* "parse-oxm": reads a series of OXM nx_match specifications as strings from
1981  * stdin, does some internal fussing with them, and then prints them back as
1982  * strings on stdout. */
1983 static void
1984 do_parse_oxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1985 {
1986     return do_parse_nxm__(true);
1987 }
1988
1989 /* "parse-ofp11-match": reads a series of ofp11_match specifications as hex
1990  * bytes from stdin, converts them to cls_rules, prints them as strings on
1991  * stdout, and then converts them back to hex bytes and prints any differences
1992  * from the input. */
1993 static void
1994 do_parse_ofp11_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1995 {
1996     struct ds in;
1997
1998     ds_init(&in);
1999     while (!ds_get_preprocessed_line(&in, stdin)) {
2000         struct ofpbuf match_in;
2001         struct ofp11_match match_out;
2002         struct cls_rule rule;
2003         enum ofperr error;
2004         int i;
2005
2006         /* Parse hex bytes. */
2007         ofpbuf_init(&match_in, 0);
2008         if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
2009             ovs_fatal(0, "Trailing garbage in hex data");
2010         }
2011         if (match_in.size != sizeof(struct ofp11_match)) {
2012             ovs_fatal(0, "Input is %zu bytes, expected %zu",
2013                       match_in.size, sizeof(struct ofp11_match));
2014         }
2015
2016         /* Convert to cls_rule. */
2017         error = ofputil_cls_rule_from_ofp11_match(match_in.data,
2018                                                   OFP_DEFAULT_PRIORITY, &rule);
2019         if (error) {
2020             printf("bad ofp11_match: %s\n\n", ofperr_get_name(error));
2021             ofpbuf_uninit(&match_in);
2022             continue;
2023         }
2024
2025         /* Print cls_rule. */
2026         cls_rule_print(&rule);
2027
2028         /* Convert back to ofp11_match and print differences from input. */
2029         ofputil_cls_rule_to_ofp11_match(&rule, &match_out);
2030
2031         for (i = 0; i < sizeof match_out; i++) {
2032             uint8_t in = ((const uint8_t *) match_in.data)[i];
2033             uint8_t out = ((const uint8_t *) &match_out)[i];
2034
2035             if (in != out) {
2036                 printf("%2d: %02"PRIx8" -> %02"PRIx8"\n", i, in, out);
2037             }
2038         }
2039         putchar('\n');
2040
2041         ofpbuf_uninit(&match_in);
2042     }
2043     ds_destroy(&in);
2044 }
2045
2046 /* "print-error ENUM": Prints the type and code of ENUM for every OpenFlow
2047  * version. */
2048 static void
2049 do_print_error(int argc OVS_UNUSED, char *argv[])
2050 {
2051     enum ofperr error;
2052     int version;
2053
2054     error = ofperr_from_name(argv[1]);
2055     if (!error) {
2056         ovs_fatal(0, "unknown error \"%s\"", argv[1]);
2057     }
2058
2059     for (version = 0; version <= UINT8_MAX; version++) {
2060         const struct ofperr_domain *domain;
2061
2062         domain = ofperr_domain_from_version(version);
2063         if (!domain) {
2064             continue;
2065         }
2066
2067         printf("%s: %d,%d\n",
2068                ofperr_domain_get_name(domain),
2069                ofperr_get_type(error, domain),
2070                ofperr_get_code(error, domain));
2071     }
2072 }
2073
2074 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
2075  * binary data, interpreting them as an OpenFlow message, and prints the
2076  * OpenFlow message on stdout, at VERBOSITY (level 2 by default).  */
2077 static void
2078 do_ofp_print(int argc, char *argv[])
2079 {
2080     struct ofpbuf packet;
2081
2082     ofpbuf_init(&packet, strlen(argv[1]) / 2);
2083     if (ofpbuf_put_hex(&packet, argv[1], NULL)[0] != '\0') {
2084         ovs_fatal(0, "trailing garbage following hex bytes");
2085     }
2086     ofp_print(stdout, packet.data, packet.size, argc > 2 ? atoi(argv[2]) : 2);
2087     ofpbuf_uninit(&packet);
2088 }
2089
2090 static const struct command all_commands[] = {
2091     { "show", 1, 1, do_show },
2092     { "monitor", 1, 3, do_monitor },
2093     { "snoop", 1, 1, do_snoop },
2094     { "dump-desc", 1, 1, do_dump_desc },
2095     { "dump-tables", 1, 1, do_dump_tables },
2096     { "dump-flows", 1, 2, do_dump_flows },
2097     { "dump-aggregate", 1, 2, do_dump_aggregate },
2098     { "queue-stats", 1, 3, do_queue_stats },
2099     { "add-flow", 2, 2, do_add_flow },
2100     { "add-flows", 2, 2, do_add_flows },
2101     { "mod-flows", 2, 2, do_mod_flows },
2102     { "del-flows", 1, 2, do_del_flows },
2103     { "replace-flows", 2, 2, do_replace_flows },
2104     { "diff-flows", 2, 2, do_diff_flows },
2105     { "packet-out", 4, INT_MAX, do_packet_out },
2106     { "dump-ports", 1, 2, do_dump_ports },
2107     { "dump-ports-desc", 1, 1, do_dump_ports_desc },
2108     { "mod-port", 3, 3, do_mod_port },
2109     { "get-frags", 1, 1, do_get_frags },
2110     { "set-frags", 2, 2, do_set_frags },
2111     { "probe", 1, 1, do_probe },
2112     { "ping", 1, 2, do_ping },
2113     { "benchmark", 3, 3, do_benchmark },
2114     { "help", 0, INT_MAX, do_help },
2115
2116     /* Undocumented commands for testing. */
2117     { "parse-flow", 1, 1, do_parse_flow },
2118     { "parse-flows", 1, 1, do_parse_flows },
2119     { "parse-nx-match", 0, 0, do_parse_nxm },
2120     { "parse-nxm", 0, 0, do_parse_nxm },
2121     { "parse-oxm", 0, 0, do_parse_oxm },
2122     { "parse-ofp11-match", 0, 0, do_parse_ofp11_match },
2123     { "print-error", 1, 1, do_print_error },
2124     { "ofp-print", 1, 2, do_ofp_print },
2125
2126     { NULL, 0, 0, NULL },
2127 };