ovs-ofctl: Use the prepared connection to dump flows in do_dump_flows__().
[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 "nx-match.h"
39 #include "odp-util.h"
40 #include "ofp-actions.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__(struct vconn *vconn, struct ofpbuf *request)
381 {
382     ovs_be32 send_xid = ((struct ofp_header *) request->data)->xid;
383     ovs_be16 stats_type = ((struct ofp_stats_msg *) request->data)->type;
384     bool done = false;
385
386     send_openflow_buffer(vconn, request);
387     while (!done) {
388         ovs_be32 recv_xid;
389         struct ofpbuf *reply;
390
391         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
392         recv_xid = ((struct ofp_header *) reply->data)->xid;
393         if (send_xid == recv_xid) {
394             const struct ofp_stats_msg *osm = reply->data;
395             const struct ofp_header *oh = reply->data;
396
397             ofp_print(stdout, reply->data, reply->size, verbosity + 1);
398
399             if (oh->type == OFPT_ERROR) {
400                 done = true;
401             } else if (oh->type == OFPT10_STATS_REPLY
402                        && osm->type == stats_type) {
403                 done = !(ntohs(osm->flags) & OFPSF_REPLY_MORE);
404             } else {
405                 ovs_fatal(0, "received bad reply: %s",
406                           ofp_to_string(reply->data, reply->size,
407                                         verbosity + 1));
408             }
409         } else {
410             VLOG_DBG("received reply with xid %08"PRIx32" "
411                      "!= expected %08"PRIx32, recv_xid, send_xid);
412         }
413         ofpbuf_delete(reply);
414     }
415 }
416
417 static void
418 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
419 {
420     struct vconn *vconn;
421
422     open_vconn(vconn_name, &vconn);
423     dump_stats_transaction__(vconn, request);
424     vconn_close(vconn);
425 }
426
427 static void
428 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
429 {
430     struct ofpbuf *request;
431     alloc_stats_request(sizeof(struct ofp_stats_msg), stats_type, &request);
432     dump_stats_transaction(vconn_name, request);
433 }
434
435 /* Sends 'request', which should be a request that only has a reply if an error
436  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
437  * it and exits with an error.
438  *
439  * Destroys all of the 'requests'. */
440 static void
441 transact_multiple_noreply(struct vconn *vconn, struct list *requests)
442 {
443     struct ofpbuf *request, *reply;
444
445     LIST_FOR_EACH (request, list_node, requests) {
446         update_openflow_length(request);
447     }
448
449     run(vconn_transact_multiple_noreply(vconn, requests, &reply),
450         "talking to %s", vconn_get_name(vconn));
451     if (reply) {
452         ofp_print(stderr, reply->data, reply->size, verbosity + 2);
453         exit(1);
454     }
455     ofpbuf_delete(reply);
456 }
457
458 /* Sends 'request', which should be a request that only has a reply if an error
459  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
460  * it and exits with an error.
461  *
462  * Destroys 'request'. */
463 static void
464 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
465 {
466     struct list requests;
467
468     list_init(&requests);
469     list_push_back(&requests, &request->list_node);
470     transact_multiple_noreply(vconn, &requests);
471 }
472
473 static void
474 fetch_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
475 {
476     struct ofp_switch_config *config;
477     struct ofp_header *header;
478     struct ofpbuf *request;
479     struct ofpbuf *reply;
480
481     make_openflow(sizeof(struct ofp_header), OFPT_GET_CONFIG_REQUEST,
482                   &request);
483     run(vconn_transact(vconn, request, &reply),
484         "talking to %s", vconn_get_name(vconn));
485
486     header = reply->data;
487     if (header->type != OFPT_GET_CONFIG_REPLY ||
488         header->length != htons(sizeof *config)) {
489         ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
490     }
491
492     config = reply->data;
493     *config_ = *config;
494
495     ofpbuf_delete(reply);
496 }
497
498 static void
499 set_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
500 {
501     struct ofp_switch_config *config;
502     struct ofp_header save_header;
503     struct ofpbuf *request;
504
505     config = make_openflow(sizeof *config, OFPT_SET_CONFIG, &request);
506     save_header = config->header;
507     *config = *config_;
508     config->header = save_header;
509
510     transact_noreply(vconn, request);
511 }
512
513 static void
514 ofctl_show(int argc OVS_UNUSED, char *argv[])
515 {
516     const char *vconn_name = argv[1];
517     struct vconn *vconn;
518     struct ofpbuf *request;
519     struct ofpbuf *reply;
520     bool trunc;
521
522     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST,
523                   &request);
524     open_vconn(vconn_name, &vconn);
525     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
526
527     trunc = ofputil_switch_features_ports_trunc(reply);
528     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
529
530     ofpbuf_delete(reply);
531     vconn_close(vconn);
532
533     if (trunc) {
534         /* The Features Reply may not contain all the ports, so send a
535          * Port Description stats request, which doesn't have size
536          * constraints. */
537         dump_trivial_stats_transaction(vconn_name, OFPST_PORT_DESC);
538     }
539     dump_trivial_transaction(vconn_name, OFPT_GET_CONFIG_REQUEST);
540 }
541
542 static void
543 ofctl_dump_desc(int argc OVS_UNUSED, char *argv[])
544 {
545     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
546 }
547
548 static void
549 ofctl_dump_tables(int argc OVS_UNUSED, char *argv[])
550 {
551     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
552 }
553
554 static bool
555 fetch_port_by_features(const char *vconn_name,
556                        const char *port_name, unsigned int port_no,
557                        struct ofputil_phy_port *pp, bool *trunc)
558 {
559     struct ofputil_switch_features features;
560     const struct ofp_switch_features *osf;
561     struct ofpbuf *request, *reply;
562     struct vconn *vconn;
563     enum ofperr error;
564     struct ofpbuf b;
565     bool found = false;
566
567     /* Fetch the switch's ofp_switch_features. */
568     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
569     open_vconn(vconn_name, &vconn);
570     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
571     vconn_close(vconn);
572
573     osf = reply->data;
574     if (reply->size < sizeof *osf) {
575         ovs_fatal(0, "%s: received too-short features reply (only %zu bytes)",
576                   vconn_name, reply->size);
577     }
578
579     *trunc = false;
580     if (ofputil_switch_features_ports_trunc(reply)) {
581         *trunc = true;
582         goto exit;
583     }
584
585     error = ofputil_decode_switch_features(osf, &features, &b);
586     if (error) {
587         ovs_fatal(0, "%s: failed to decode features reply (%s)",
588                   vconn_name, ofperr_to_string(error));
589     }
590
591     while (!ofputil_pull_phy_port(osf->header.version, &b, pp)) {
592         if (port_no != UINT_MAX
593             ? port_no == pp->port_no
594             : !strcmp(pp->name, port_name)) {
595             found = true;
596             goto exit;
597         }
598     }
599
600 exit:
601     ofpbuf_delete(reply);
602     return found;
603 }
604
605 static bool
606 fetch_port_by_stats(const char *vconn_name,
607                     const char *port_name, unsigned int port_no,
608                     struct ofputil_phy_port *pp)
609 {
610     struct ofpbuf *request;
611     struct vconn *vconn;
612     ovs_be32 send_xid;
613     struct ofpbuf b;
614     bool done = false;
615     bool found = false;
616
617     alloc_stats_request(sizeof(struct ofp_stats_msg), OFPST_PORT_DESC,
618                         &request);
619     send_xid = ((struct ofp_header *) request->data)->xid;
620
621     open_vconn(vconn_name, &vconn);
622     send_openflow_buffer(vconn, request);
623     while (!done) {
624         ovs_be32 recv_xid;
625         struct ofpbuf *reply;
626
627         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
628         recv_xid = ((struct ofp_header *) reply->data)->xid;
629         if (send_xid == recv_xid) {
630             const struct ofputil_msg_type *type;
631             struct ofp_stats_msg *osm;
632
633             ofputil_decode_msg_type(reply->data, &type);
634             if (ofputil_msg_type_code(type) != OFPUTIL_OFPST_PORT_DESC_REPLY) {
635                 ovs_fatal(0, "received bad reply: %s",
636                           ofp_to_string(reply->data, reply->size,
637                                         verbosity + 1));
638             }
639
640             osm = ofpbuf_at_assert(reply, 0, sizeof *osm);
641             done = !(ntohs(osm->flags) & OFPSF_REPLY_MORE);
642
643             if (found) {
644                 /* We've already found the port, but we need to drain
645                  * the queue of any other replies for this request. */
646                 continue;
647             }
648
649             ofpbuf_use_const(&b, &osm->header, ntohs(osm->header.length));
650             ofpbuf_pull(&b, sizeof(struct ofp_stats_msg));
651
652             while (!ofputil_pull_phy_port(osm->header.version, &b, pp)) {
653                 if (port_no != UINT_MAX ? port_no == pp->port_no
654                                         : !strcmp(pp->name, port_name)) {
655                     found = true;
656                     break;
657                 }
658             }
659         } else {
660             VLOG_DBG("received reply with xid %08"PRIx32" "
661                      "!= expected %08"PRIx32, recv_xid, send_xid);
662         }
663         ofpbuf_delete(reply);
664     }
665     vconn_close(vconn);
666
667     return found;
668 }
669
670
671 /* Opens a connection to 'vconn_name', fetches the port structure for
672  * 'port_name' (which may be a port name or number), and copies it into
673  * '*pp'. */
674 static void
675 fetch_ofputil_phy_port(const char *vconn_name, const char *port_name,
676                        struct ofputil_phy_port *pp)
677 {
678     unsigned int port_no;
679     bool found;
680     bool trunc;
681
682     /* Try to interpret the argument as a port number. */
683     if (!str_to_uint(port_name, 10, &port_no)) {
684         port_no = UINT_MAX;
685     }
686
687     /* Try to find the port based on the Features Reply.  If it looks
688      * like the results may be truncated, then use the Port Description
689      * stats message introduced in OVS 1.7. */
690     found = fetch_port_by_features(vconn_name, port_name, port_no, pp,
691                                    &trunc);
692     if (trunc) {
693         found = fetch_port_by_stats(vconn_name, port_name, port_no, pp);
694     }
695
696     if (!found) {
697         ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
698     }
699 }
700
701 /* Returns the port number corresponding to 'port_name' (which may be a port
702  * name or number) within the switch 'vconn_name'. */
703 static uint16_t
704 str_to_port_no(const char *vconn_name, const char *port_name)
705 {
706     unsigned int port_no;
707
708     if (str_to_uint(port_name, 10, &port_no)) {
709         return port_no;
710     } else {
711         struct ofputil_phy_port pp;
712
713         fetch_ofputil_phy_port(vconn_name, port_name, &pp);
714         return pp.port_no;
715     }
716 }
717
718 static bool
719 try_set_protocol(struct vconn *vconn, enum ofputil_protocol want,
720                  enum ofputil_protocol *cur)
721 {
722     for (;;) {
723         struct ofpbuf *request, *reply;
724         enum ofputil_protocol next;
725
726         request = ofputil_encode_set_protocol(*cur, want, &next);
727         if (!request) {
728             return true;
729         }
730
731         run(vconn_transact_noreply(vconn, request, &reply),
732             "talking to %s", vconn_get_name(vconn));
733         if (reply) {
734             char *s = ofp_to_string(reply->data, reply->size, 2);
735             VLOG_DBG("%s: failed to set protocol, switch replied: %s",
736                      vconn_get_name(vconn), s);
737             free(s);
738             ofpbuf_delete(reply);
739             return false;
740         }
741
742         *cur = next;
743     }
744 }
745
746 static enum ofputil_protocol
747 set_protocol_for_flow_dump(struct vconn *vconn,
748                            enum ofputil_protocol cur_protocol,
749                            enum ofputil_protocol usable_protocols)
750 {
751     char *usable_s;
752     int i;
753
754     for (i = 0; i < ofputil_n_flow_dump_protocols; i++) {
755         enum ofputil_protocol f = ofputil_flow_dump_protocols[i];
756         if (f & usable_protocols & allowed_protocols
757             && try_set_protocol(vconn, f, &cur_protocol)) {
758             return f;
759         }
760     }
761
762     usable_s = ofputil_protocols_to_string(usable_protocols);
763     if (usable_protocols & allowed_protocols) {
764         ovs_fatal(0, "switch does not support any of the usable flow "
765                   "formats (%s)", usable_s);
766     } else {
767         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
768         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
769                   "allowed flow formats (%s)", usable_s, allowed_s);
770     }
771 }
772
773 static void
774 ofctl_dump_flows__(int argc, char *argv[], bool aggregate)
775 {
776     enum ofputil_protocol usable_protocols, protocol;
777     struct ofputil_flow_stats_request fsr;
778     struct ofpbuf *request;
779     struct vconn *vconn;
780
781     parse_ofp_flow_stats_request_str(&fsr, aggregate, argc > 2 ? argv[2] : "");
782     usable_protocols = ofputil_flow_stats_request_usable_protocols(&fsr);
783
784     protocol = open_vconn(argv[1], &vconn);
785     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
786     request = ofputil_encode_flow_stats_request(&fsr, protocol);
787     dump_stats_transaction__(vconn, request);
788     vconn_close(vconn);
789 }
790
791 static void
792 ofctl_dump_flows(int argc, char *argv[])
793 {
794     return ofctl_dump_flows__(argc, argv, false);
795 }
796
797 static void
798 ofctl_dump_aggregate(int argc, char *argv[])
799 {
800     return ofctl_dump_flows__(argc, argv, true);
801 }
802
803 static void
804 ofctl_queue_stats(int argc, char *argv[])
805 {
806     struct ofp_queue_stats_request *req;
807     struct ofpbuf *request;
808
809     req = alloc_stats_request(sizeof *req, OFPST_QUEUE, &request);
810
811     if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
812         req->port_no = htons(str_to_port_no(argv[1], argv[2]));
813     } else {
814         req->port_no = htons(OFPP_ALL);
815     }
816     if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
817         req->queue_id = htonl(atoi(argv[3]));
818     } else {
819         req->queue_id = htonl(OFPQ_ALL);
820     }
821
822     memset(req->pad, 0, sizeof req->pad);
823
824     dump_stats_transaction(argv[1], request);
825 }
826
827 static enum ofputil_protocol
828 open_vconn_for_flow_mod(const char *remote,
829                         const struct ofputil_flow_mod *fms, size_t n_fms,
830                         struct vconn **vconnp)
831 {
832     enum ofputil_protocol usable_protocols;
833     enum ofputil_protocol cur_protocol;
834     char *usable_s;
835     int i;
836
837     /* Figure out what flow formats will work. */
838     usable_protocols = ofputil_flow_mod_usable_protocols(fms, n_fms);
839     if (!(usable_protocols & allowed_protocols)) {
840         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
841         usable_s = ofputil_protocols_to_string(usable_protocols);
842         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
843                   "allowed flow formats (%s)", usable_s, allowed_s);
844     }
845
846     /* If the initial flow format is allowed and usable, keep it. */
847     cur_protocol = open_vconn(remote, vconnp);
848     if (usable_protocols & allowed_protocols & cur_protocol) {
849         return cur_protocol;
850     }
851
852     /* Otherwise try each flow format in turn. */
853     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
854         enum ofputil_protocol f = 1 << i;
855
856         if (f != cur_protocol
857             && f & usable_protocols & allowed_protocols
858             && try_set_protocol(*vconnp, f, &cur_protocol)) {
859             return f;
860         }
861     }
862
863     usable_s = ofputil_protocols_to_string(usable_protocols);
864     ovs_fatal(0, "switch does not support any of the usable flow "
865               "formats (%s)", usable_s);
866 }
867
868 static void
869 ofctl_flow_mod__(const char *remote, struct ofputil_flow_mod *fms,
870                  size_t n_fms)
871 {
872     enum ofputil_protocol protocol;
873     struct vconn *vconn;
874     size_t i;
875
876     protocol = open_vconn_for_flow_mod(remote, fms, n_fms, &vconn);
877
878     for (i = 0; i < n_fms; i++) {
879         struct ofputil_flow_mod *fm = &fms[i];
880
881         transact_noreply(vconn, ofputil_encode_flow_mod(fm, protocol));
882         free(fm->ofpacts);
883     }
884     vconn_close(vconn);
885 }
886
887 static void
888 ofctl_flow_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
889 {
890     struct ofputil_flow_mod *fms = NULL;
891     size_t n_fms = 0;
892
893     parse_ofp_flow_mod_file(argv[2], command, &fms, &n_fms);
894     ofctl_flow_mod__(argv[1], fms, n_fms);
895     free(fms);
896 }
897
898 static void
899 ofctl_flow_mod(int argc, char *argv[], uint16_t command)
900 {
901     if (argc > 2 && !strcmp(argv[2], "-")) {
902         ofctl_flow_mod_file(argc, argv, command);
903     } else {
904         struct ofputil_flow_mod fm;
905         parse_ofp_flow_mod_str(&fm, argc > 2 ? argv[2] : "", command, false);
906         ofctl_flow_mod__(argv[1], &fm, 1);
907     }
908 }
909
910 static void
911 ofctl_add_flow(int argc, char *argv[])
912 {
913     ofctl_flow_mod(argc, argv, OFPFC_ADD);
914 }
915
916 static void
917 ofctl_add_flows(int argc, char *argv[])
918 {
919     ofctl_flow_mod_file(argc, argv, OFPFC_ADD);
920 }
921
922 static void
923 ofctl_mod_flows(int argc, char *argv[])
924 {
925     ofctl_flow_mod(argc, argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
926 }
927
928 static void
929 ofctl_del_flows(int argc, char *argv[])
930 {
931     ofctl_flow_mod(argc, argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
932 }
933
934 static void
935 set_packet_in_format(struct vconn *vconn,
936                      enum nx_packet_in_format packet_in_format)
937 {
938     struct ofpbuf *spif = ofputil_make_set_packet_in_format(packet_in_format);
939     transact_noreply(vconn, spif);
940     VLOG_DBG("%s: using user-specified packet in format %s",
941              vconn_get_name(vconn),
942              ofputil_packet_in_format_to_string(packet_in_format));
943 }
944
945 static int
946 monitor_set_invalid_ttl_to_controller(struct vconn *vconn)
947 {
948     struct ofp_switch_config config;
949     enum ofp_config_flags flags;
950
951     fetch_switch_config(vconn, &config);
952     flags = ntohs(config.flags);
953     if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
954         /* Set the invalid ttl config. */
955         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
956
957         config.flags = htons(flags);
958         set_switch_config(vconn, &config);
959
960         /* Then retrieve the configuration to see if it really took.  OpenFlow
961          * doesn't define error reporting for bad modes, so this is all we can
962          * do. */
963         fetch_switch_config(vconn, &config);
964         flags = ntohs(config.flags);
965         if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
966             ovs_fatal(0, "setting invalid_ttl_to_controller failed (this "
967                       "switch probably doesn't support mode)");
968             return -EOPNOTSUPP;
969         }
970     }
971     return 0;
972 }
973
974 /* Converts hex digits in 'hex' to an OpenFlow message in '*msgp'.  The
975  * caller must free '*msgp'.  On success, returns NULL.  On failure, returns
976  * an error message and stores NULL in '*msgp'. */
977 static const char *
978 openflow_from_hex(const char *hex, struct ofpbuf **msgp)
979 {
980     struct ofp_header *oh;
981     struct ofpbuf *msg;
982
983     msg = ofpbuf_new(strlen(hex) / 2);
984     *msgp = NULL;
985
986     if (ofpbuf_put_hex(msg, hex, NULL)[0] != '\0') {
987         ofpbuf_delete(msg);
988         return "Trailing garbage in hex data";
989     }
990
991     if (msg->size < sizeof(struct ofp_header)) {
992         ofpbuf_delete(msg);
993         return "Message too short for OpenFlow";
994     }
995
996     oh = msg->data;
997     if (msg->size != ntohs(oh->length)) {
998         ofpbuf_delete(msg);
999         return "Message size does not match length in OpenFlow header";
1000     }
1001
1002     *msgp = msg;
1003     return NULL;
1004 }
1005
1006 static void
1007 ofctl_send(struct unixctl_conn *conn, int argc,
1008            const char *argv[], void *vconn_)
1009 {
1010     struct vconn *vconn = vconn_;
1011     struct ds reply;
1012     bool ok;
1013     int i;
1014
1015     ok = true;
1016     ds_init(&reply);
1017     for (i = 1; i < argc; i++) {
1018         const char *error_msg;
1019         struct ofpbuf *msg;
1020         int error;
1021
1022         error_msg = openflow_from_hex(argv[i], &msg);
1023         if (error_msg) {
1024             ds_put_format(&reply, "%s\n", error_msg);
1025             ok = false;
1026             continue;
1027         }
1028
1029         fprintf(stderr, "send: ");
1030         ofp_print(stderr, msg->data, msg->size, verbosity);
1031
1032         error = vconn_send_block(vconn, msg);
1033         if (error) {
1034             ofpbuf_delete(msg);
1035             ds_put_format(&reply, "%s\n", strerror(error));
1036             ok = false;
1037         } else {
1038             ds_put_cstr(&reply, "sent\n");
1039         }
1040     }
1041
1042     if (ok) {
1043         unixctl_command_reply(conn, ds_cstr(&reply));
1044     } else {
1045         unixctl_command_reply_error(conn, ds_cstr(&reply));
1046     }
1047     ds_destroy(&reply);
1048 }
1049
1050 struct barrier_aux {
1051     struct vconn *vconn;        /* OpenFlow connection for sending barrier. */
1052     struct unixctl_conn *conn;  /* Connection waiting for barrier response. */
1053 };
1054
1055 static void
1056 ofctl_barrier(struct unixctl_conn *conn, int argc OVS_UNUSED,
1057               const char *argv[] OVS_UNUSED, void *aux_)
1058 {
1059     struct barrier_aux *aux = aux_;
1060     struct ofpbuf *msg;
1061     int error;
1062
1063     if (aux->conn) {
1064         unixctl_command_reply_error(conn, "already waiting for barrier reply");
1065         return;
1066     }
1067
1068     msg = ofputil_encode_barrier_request();
1069     error = vconn_send_block(aux->vconn, msg);
1070     if (error) {
1071         ofpbuf_delete(msg);
1072         unixctl_command_reply_error(conn, strerror(error));
1073     } else {
1074         aux->conn = conn;
1075     }
1076 }
1077
1078 static void
1079 ofctl_set_output_file(struct unixctl_conn *conn, int argc OVS_UNUSED,
1080                       const char *argv[], void *aux OVS_UNUSED)
1081 {
1082     int fd;
1083
1084     fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
1085     if (fd < 0) {
1086         unixctl_command_reply_error(conn, strerror(errno));
1087         return;
1088     }
1089
1090     fflush(stderr);
1091     dup2(fd, STDERR_FILENO);
1092     close(fd);
1093     unixctl_command_reply(conn, NULL);
1094 }
1095
1096 static void
1097 monitor_vconn(struct vconn *vconn)
1098 {
1099     struct barrier_aux barrier_aux = { vconn, NULL };
1100     struct unixctl_server *server;
1101     bool exiting = false;
1102     int error;
1103
1104     daemon_save_fd(STDERR_FILENO);
1105     daemonize_start();
1106     error = unixctl_server_create(NULL, &server);
1107     if (error) {
1108         ovs_fatal(error, "failed to create unixctl server");
1109     }
1110     unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
1111     unixctl_command_register("ofctl/send", "OFMSG...", 1, INT_MAX,
1112                              ofctl_send, vconn);
1113     unixctl_command_register("ofctl/barrier", "", 0, 0,
1114                              ofctl_barrier, &barrier_aux);
1115     unixctl_command_register("ofctl/set-output-file", "FILE", 1, 1,
1116                              ofctl_set_output_file, NULL);
1117     daemonize_complete();
1118
1119     for (;;) {
1120         struct ofpbuf *b;
1121         int retval;
1122
1123         unixctl_server_run(server);
1124
1125         for (;;) {
1126             uint8_t msg_type;
1127
1128             retval = vconn_recv(vconn, &b);
1129             if (retval == EAGAIN) {
1130                 break;
1131             }
1132             run(retval, "vconn_recv");
1133
1134             if (timestamp) {
1135                 time_t now = time_wall();
1136                 char s[32];
1137
1138                 strftime(s, sizeof s, "%Y-%m-%d %H:%M:%S: ", gmtime(&now));
1139                 fputs(s, stderr);
1140             }
1141
1142             msg_type = ((const struct ofp_header *) b->data)->type;
1143             ofp_print(stderr, b->data, b->size, verbosity + 2);
1144             ofpbuf_delete(b);
1145
1146             if (barrier_aux.conn && msg_type == OFPT10_BARRIER_REPLY) {
1147                 unixctl_command_reply(barrier_aux.conn, NULL);
1148                 barrier_aux.conn = NULL;
1149             }
1150         }
1151
1152         if (exiting) {
1153             break;
1154         }
1155
1156         vconn_run(vconn);
1157         vconn_run_wait(vconn);
1158         vconn_recv_wait(vconn);
1159         unixctl_server_wait(server);
1160         poll_block();
1161     }
1162     vconn_close(vconn);
1163     unixctl_server_destroy(server);
1164 }
1165
1166 static void
1167 ofctl_monitor(int argc, char *argv[])
1168 {
1169     struct vconn *vconn;
1170
1171     open_vconn(argv[1], &vconn);
1172     if (argc > 2) {
1173         struct ofp_switch_config config;
1174
1175         fetch_switch_config(vconn, &config);
1176         config.miss_send_len = htons(atoi(argv[2]));
1177         set_switch_config(vconn, &config);
1178     }
1179     if (argc > 3) {
1180         if (!strcmp(argv[3], "invalid_ttl")) {
1181             monitor_set_invalid_ttl_to_controller(vconn);
1182         }
1183     }
1184     if (preferred_packet_in_format >= 0) {
1185         set_packet_in_format(vconn, preferred_packet_in_format);
1186     } else {
1187         struct ofpbuf *spif, *reply;
1188
1189         spif = ofputil_make_set_packet_in_format(NXPIF_NXM);
1190         run(vconn_transact_noreply(vconn, spif, &reply),
1191             "talking to %s", vconn_get_name(vconn));
1192         if (reply) {
1193             char *s = ofp_to_string(reply->data, reply->size, 2);
1194             VLOG_DBG("%s: failed to set packet in format to nxm, controller"
1195                      " replied: %s. Falling back to the switch default.",
1196                      vconn_get_name(vconn), s);
1197             free(s);
1198             ofpbuf_delete(reply);
1199         }
1200     }
1201
1202     monitor_vconn(vconn);
1203 }
1204
1205 static void
1206 ofctl_snoop(int argc OVS_UNUSED, char *argv[])
1207 {
1208     struct vconn *vconn;
1209
1210     open_vconn__(argv[1], "snoop", &vconn);
1211     monitor_vconn(vconn);
1212 }
1213
1214 static void
1215 ofctl_dump_ports(int argc, char *argv[])
1216 {
1217     struct ofp_port_stats_request *req;
1218     struct ofpbuf *request;
1219     uint16_t port;
1220
1221     req = alloc_stats_request(sizeof *req, OFPST_PORT, &request);
1222     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_NONE;
1223     req->port_no = htons(port);
1224     dump_stats_transaction(argv[1], request);
1225 }
1226
1227 static void
1228 ofctl_dump_ports_desc(int argc OVS_UNUSED, char *argv[])
1229 {
1230     dump_trivial_stats_transaction(argv[1], OFPST_PORT_DESC);
1231 }
1232
1233 static void
1234 ofctl_probe(int argc OVS_UNUSED, char *argv[])
1235 {
1236     struct ofpbuf *request;
1237     struct vconn *vconn;
1238     struct ofpbuf *reply;
1239
1240     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
1241     open_vconn(argv[1], &vconn);
1242     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1243     if (reply->size != sizeof(struct ofp_header)) {
1244         ovs_fatal(0, "reply does not match request");
1245     }
1246     ofpbuf_delete(reply);
1247     vconn_close(vconn);
1248 }
1249
1250 static void
1251 ofctl_packet_out(int argc, char *argv[])
1252 {
1253     struct ofputil_packet_out po;
1254     struct ofpbuf ofpacts;
1255     struct vconn *vconn;
1256     int i;
1257
1258     ofpbuf_init(&ofpacts, 64);
1259     parse_ofpacts(argv[3], &ofpacts);
1260
1261     po.buffer_id = UINT32_MAX;
1262     po.in_port = (!strcasecmp(argv[2], "none") ? OFPP_NONE
1263                   : !strcasecmp(argv[2], "local") ? OFPP_LOCAL
1264                   : str_to_port_no(argv[1], argv[2]));
1265     po.ofpacts = ofpacts.data;
1266     po.ofpacts_len = ofpacts.size;
1267
1268     open_vconn(argv[1], &vconn);
1269     for (i = 4; i < argc; i++) {
1270         struct ofpbuf *packet, *opo;
1271         const char *error_msg;
1272
1273         error_msg = eth_from_hex(argv[i], &packet);
1274         if (error_msg) {
1275             ovs_fatal(0, "%s", error_msg);
1276         }
1277
1278         po.packet = packet->data;
1279         po.packet_len = packet->size;
1280         opo = ofputil_encode_packet_out(&po);
1281         transact_noreply(vconn, opo);
1282         ofpbuf_delete(packet);
1283     }
1284     vconn_close(vconn);
1285     ofpbuf_uninit(&ofpacts);
1286 }
1287
1288 static void
1289 ofctl_mod_port(int argc OVS_UNUSED, char *argv[])
1290 {
1291     struct ofp_config_flag {
1292         const char *name;             /* The flag's name. */
1293         enum ofputil_port_config bit; /* Bit to turn on or off. */
1294         bool on;                      /* Value to set the bit to. */
1295     };
1296     static const struct ofp_config_flag flags[] = {
1297         { "up",          OFPUTIL_PC_PORT_DOWN,    false },
1298         { "down",        OFPUTIL_PC_PORT_DOWN,    true  },
1299         { "stp",         OFPUTIL_PC_NO_STP,       false },
1300         { "receive",     OFPUTIL_PC_NO_RECV,      false },
1301         { "receive-stp", OFPUTIL_PC_NO_RECV_STP,  false },
1302         { "flood",       OFPUTIL_PC_NO_FLOOD,     false },
1303         { "forward",     OFPUTIL_PC_NO_FWD,       false },
1304         { "packet-in",   OFPUTIL_PC_NO_PACKET_IN, false },
1305     };
1306
1307     const struct ofp_config_flag *flag;
1308     enum ofputil_protocol protocol;
1309     struct ofputil_port_mod pm;
1310     struct ofputil_phy_port pp;
1311     struct vconn *vconn;
1312     const char *command;
1313     bool not;
1314
1315     fetch_ofputil_phy_port(argv[1], argv[2], &pp);
1316
1317     pm.port_no = pp.port_no;
1318     memcpy(pm.hw_addr, pp.hw_addr, ETH_ADDR_LEN);
1319     pm.config = 0;
1320     pm.mask = 0;
1321     pm.advertise = 0;
1322
1323     if (!strncasecmp(argv[3], "no-", 3)) {
1324         command = argv[3] + 3;
1325         not = true;
1326     } else if (!strncasecmp(argv[3], "no", 2)) {
1327         command = argv[3] + 2;
1328         not = true;
1329     } else {
1330         command = argv[3];
1331         not = false;
1332     }
1333     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1334         if (!strcasecmp(command, flag->name)) {
1335             pm.mask = flag->bit;
1336             pm.config = flag->on ^ not ? flag->bit : 0;
1337             goto found;
1338         }
1339     }
1340     ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1341
1342 found:
1343     protocol = open_vconn(argv[1], &vconn);
1344     transact_noreply(vconn, ofputil_encode_port_mod(&pm, protocol));
1345     vconn_close(vconn);
1346 }
1347
1348 static void
1349 ofctl_get_frags(int argc OVS_UNUSED, char *argv[])
1350 {
1351     struct ofp_switch_config config;
1352     struct vconn *vconn;
1353
1354     open_vconn(argv[1], &vconn);
1355     fetch_switch_config(vconn, &config);
1356     puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
1357     vconn_close(vconn);
1358 }
1359
1360 static void
1361 ofctl_set_frags(int argc OVS_UNUSED, char *argv[])
1362 {
1363     struct ofp_switch_config config;
1364     enum ofp_config_flags mode;
1365     struct vconn *vconn;
1366     ovs_be16 flags;
1367
1368     if (!ofputil_frag_handling_from_string(argv[2], &mode)) {
1369         ovs_fatal(0, "%s: unknown fragment handling mode", argv[2]);
1370     }
1371
1372     open_vconn(argv[1], &vconn);
1373     fetch_switch_config(vconn, &config);
1374     flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
1375     if (flags != config.flags) {
1376         /* Set the configuration. */
1377         config.flags = flags;
1378         set_switch_config(vconn, &config);
1379
1380         /* Then retrieve the configuration to see if it really took.  OpenFlow
1381          * doesn't define error reporting for bad modes, so this is all we can
1382          * do. */
1383         fetch_switch_config(vconn, &config);
1384         if (flags != config.flags) {
1385             ovs_fatal(0, "%s: setting fragment handling mode failed (this "
1386                       "switch probably doesn't support mode \"%s\")",
1387                       argv[1], ofputil_frag_handling_to_string(mode));
1388         }
1389     }
1390     vconn_close(vconn);
1391 }
1392
1393 static void
1394 ofctl_ping(int argc, char *argv[])
1395 {
1396     size_t max_payload = 65535 - sizeof(struct ofp_header);
1397     unsigned int payload;
1398     struct vconn *vconn;
1399     int i;
1400
1401     payload = argc > 2 ? atoi(argv[2]) : 64;
1402     if (payload > max_payload) {
1403         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1404     }
1405
1406     open_vconn(argv[1], &vconn);
1407     for (i = 0; i < 10; i++) {
1408         struct timeval start, end;
1409         struct ofpbuf *request, *reply;
1410         struct ofp_header *rq_hdr, *rpy_hdr;
1411
1412         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1413                                OFPT_ECHO_REQUEST, &request);
1414         random_bytes(rq_hdr + 1, payload);
1415
1416         xgettimeofday(&start);
1417         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1418         xgettimeofday(&end);
1419
1420         rpy_hdr = reply->data;
1421         if (reply->size != request->size
1422             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1423             || rpy_hdr->xid != rq_hdr->xid
1424             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1425             printf("Reply does not match request.  Request:\n");
1426             ofp_print(stdout, request, request->size, verbosity + 2);
1427             printf("Reply:\n");
1428             ofp_print(stdout, reply, reply->size, verbosity + 2);
1429         }
1430         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1431                reply->size - sizeof *rpy_hdr, argv[1], ntohl(rpy_hdr->xid),
1432                    (1000*(double)(end.tv_sec - start.tv_sec))
1433                    + (.001*(end.tv_usec - start.tv_usec)));
1434         ofpbuf_delete(request);
1435         ofpbuf_delete(reply);
1436     }
1437     vconn_close(vconn);
1438 }
1439
1440 static void
1441 ofctl_benchmark(int argc OVS_UNUSED, char *argv[])
1442 {
1443     size_t max_payload = 65535 - sizeof(struct ofp_header);
1444     struct timeval start, end;
1445     unsigned int payload_size, message_size;
1446     struct vconn *vconn;
1447     double duration;
1448     int count;
1449     int i;
1450
1451     payload_size = atoi(argv[2]);
1452     if (payload_size > max_payload) {
1453         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1454     }
1455     message_size = sizeof(struct ofp_header) + payload_size;
1456
1457     count = atoi(argv[3]);
1458
1459     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1460            count, message_size, count * message_size);
1461
1462     open_vconn(argv[1], &vconn);
1463     xgettimeofday(&start);
1464     for (i = 0; i < count; i++) {
1465         struct ofpbuf *request, *reply;
1466         struct ofp_header *rq_hdr;
1467
1468         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1469         memset(rq_hdr + 1, 0, payload_size);
1470         run(vconn_transact(vconn, request, &reply), "transact");
1471         ofpbuf_delete(reply);
1472     }
1473     xgettimeofday(&end);
1474     vconn_close(vconn);
1475
1476     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1477                 + (.001*(end.tv_usec - start.tv_usec)));
1478     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1479            duration, count / (duration / 1000.0),
1480            count * message_size / (duration / 1000.0));
1481 }
1482
1483 static void
1484 ofctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1485 {
1486     usage();
1487 }
1488 \f
1489 /* replace-flows and diff-flows commands. */
1490
1491 /* A flow table entry, possibly with two different versions. */
1492 struct fte {
1493     struct cls_rule rule;       /* Within a "struct classifier". */
1494     struct fte_version *versions[2];
1495 };
1496
1497 /* One version of a Flow Table Entry. */
1498 struct fte_version {
1499     ovs_be64 cookie;
1500     uint16_t idle_timeout;
1501     uint16_t hard_timeout;
1502     uint16_t flags;
1503     struct ofpact *ofpacts;
1504     size_t ofpacts_len;
1505 };
1506
1507 /* Frees 'version' and the data that it owns. */
1508 static void
1509 fte_version_free(struct fte_version *version)
1510 {
1511     if (version) {
1512         free(version->ofpacts);
1513         free(version);
1514     }
1515 }
1516
1517 /* Returns true if 'a' and 'b' are the same, false if they differ.
1518  *
1519  * Ignores differences in 'flags' because there's no way to retrieve flags from
1520  * an OpenFlow switch.  We have to assume that they are the same. */
1521 static bool
1522 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
1523 {
1524     return (a->cookie == b->cookie
1525             && a->idle_timeout == b->idle_timeout
1526             && a->hard_timeout == b->hard_timeout
1527             && ofpacts_equal(a->ofpacts, a->ofpacts_len,
1528                              b->ofpacts, b->ofpacts_len));
1529 }
1530
1531 /* Prints 'version' on stdout.  Expects the caller to have printed the rule
1532  * associated with the version. */
1533 static void
1534 fte_version_print(const struct fte_version *version)
1535 {
1536     struct ds s;
1537
1538     if (version->cookie != htonll(0)) {
1539         printf(" cookie=0x%"PRIx64, ntohll(version->cookie));
1540     }
1541     if (version->idle_timeout != OFP_FLOW_PERMANENT) {
1542         printf(" idle_timeout=%"PRIu16, version->idle_timeout);
1543     }
1544     if (version->hard_timeout != OFP_FLOW_PERMANENT) {
1545         printf(" hard_timeout=%"PRIu16, version->hard_timeout);
1546     }
1547
1548     ds_init(&s);
1549     ofpacts_format(version->ofpacts, version->ofpacts_len, &s);
1550     printf(" %s\n", ds_cstr(&s));
1551     ds_destroy(&s);
1552 }
1553
1554 static struct fte *
1555 fte_from_cls_rule(const struct cls_rule *cls_rule)
1556 {
1557     return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
1558 }
1559
1560 /* Frees 'fte' and its versions. */
1561 static void
1562 fte_free(struct fte *fte)
1563 {
1564     if (fte) {
1565         fte_version_free(fte->versions[0]);
1566         fte_version_free(fte->versions[1]);
1567         free(fte);
1568     }
1569 }
1570
1571 /* Frees all of the FTEs within 'cls'. */
1572 static void
1573 fte_free_all(struct classifier *cls)
1574 {
1575     struct cls_cursor cursor;
1576     struct fte *fte, *next;
1577
1578     cls_cursor_init(&cursor, cls, NULL);
1579     CLS_CURSOR_FOR_EACH_SAFE (fte, next, rule, &cursor) {
1580         classifier_remove(cls, &fte->rule);
1581         fte_free(fte);
1582     }
1583     classifier_destroy(cls);
1584 }
1585
1586 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
1587  * necessary.  Sets 'version' as the version of that rule with the given
1588  * 'index', replacing any existing version, if any.
1589  *
1590  * Takes ownership of 'version'. */
1591 static void
1592 fte_insert(struct classifier *cls, const struct cls_rule *rule,
1593            struct fte_version *version, int index)
1594 {
1595     struct fte *old, *fte;
1596
1597     fte = xzalloc(sizeof *fte);
1598     fte->rule = *rule;
1599     fte->versions[index] = version;
1600
1601     old = fte_from_cls_rule(classifier_replace(cls, &fte->rule));
1602     if (old) {
1603         fte_version_free(old->versions[index]);
1604         fte->versions[!index] = old->versions[!index];
1605         free(old);
1606     }
1607 }
1608
1609 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
1610  * with the specified 'index'.  Returns the flow formats able to represent the
1611  * flows that were read. */
1612 static enum ofputil_protocol
1613 read_flows_from_file(const char *filename, struct classifier *cls, int index)
1614 {
1615     enum ofputil_protocol usable_protocols;
1616     struct ds s;
1617     FILE *file;
1618
1619     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
1620     if (file == NULL) {
1621         ovs_fatal(errno, "%s: open", filename);
1622     }
1623
1624     ds_init(&s);
1625     usable_protocols = OFPUTIL_P_ANY;
1626     while (!ds_get_preprocessed_line(&s, file)) {
1627         struct fte_version *version;
1628         struct ofputil_flow_mod fm;
1629
1630         parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), true);
1631
1632         version = xmalloc(sizeof *version);
1633         version->cookie = fm.new_cookie;
1634         version->idle_timeout = fm.idle_timeout;
1635         version->hard_timeout = fm.hard_timeout;
1636         version->flags = fm.flags & (OFPFF_SEND_FLOW_REM | OFPFF_EMERG);
1637         version->ofpacts = fm.ofpacts;
1638         version->ofpacts_len = fm.ofpacts_len;
1639
1640         usable_protocols &= ofputil_usable_protocols(&fm.cr);
1641
1642         fte_insert(cls, &fm.cr, version, index);
1643     }
1644     ds_destroy(&s);
1645
1646     if (file != stdin) {
1647         fclose(file);
1648     }
1649
1650     return usable_protocols;
1651 }
1652
1653 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
1654  * format 'protocol', and adds them as flow table entries in 'cls' for the
1655  * version with the specified 'index'. */
1656 static void
1657 read_flows_from_switch(struct vconn *vconn,
1658                        enum ofputil_protocol protocol,
1659                        struct classifier *cls, int index)
1660 {
1661     struct ofputil_flow_stats_request fsr;
1662     struct ofpbuf *request;
1663     ovs_be32 send_xid;
1664     bool done;
1665
1666     fsr.aggregate = false;
1667     cls_rule_init_catchall(&fsr.match, 0);
1668     fsr.out_port = OFPP_NONE;
1669     fsr.table_id = 0xff;
1670     fsr.cookie = fsr.cookie_mask = htonll(0);
1671     request = ofputil_encode_flow_stats_request(&fsr, protocol);
1672     send_xid = ((struct ofp_header *) request->data)->xid;
1673     send_openflow_buffer(vconn, request);
1674
1675     done = false;
1676     while (!done) {
1677         ovs_be32 recv_xid;
1678         struct ofpbuf *reply;
1679
1680         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
1681         recv_xid = ((struct ofp_header *) reply->data)->xid;
1682         if (send_xid == recv_xid) {
1683             const struct ofputil_msg_type *type;
1684             const struct ofp_stats_msg *osm;
1685             enum ofputil_msg_code code;
1686
1687             ofputil_decode_msg_type(reply->data, &type);
1688             code = ofputil_msg_type_code(type);
1689             if (code != OFPUTIL_OFPST_FLOW_REPLY &&
1690                 code != OFPUTIL_NXST_FLOW_REPLY) {
1691                 ovs_fatal(0, "received bad reply: %s",
1692                           ofp_to_string(reply->data, reply->size,
1693                                         verbosity + 1));
1694             }
1695
1696             osm = reply->data;
1697             if (!(osm->flags & htons(OFPSF_REPLY_MORE))) {
1698                 done = true;
1699             }
1700
1701             for (;;) {
1702                 struct fte_version *version;
1703                 struct ofputil_flow_stats fs;
1704                 struct ofpbuf ofpacts;
1705                 int retval;
1706
1707                 ofpbuf_init(&ofpacts, 64);
1708                 retval = ofputil_decode_flow_stats_reply(&fs, reply, false,
1709                                                          &ofpacts);
1710                 if (retval) {
1711                     ofpbuf_uninit(&ofpacts);
1712                     if (retval != EOF) {
1713                         ovs_fatal(0, "parse error in reply");
1714                     }
1715                     break;
1716                 }
1717
1718                 version = xmalloc(sizeof *version);
1719                 version->cookie = fs.cookie;
1720                 version->idle_timeout = fs.idle_timeout;
1721                 version->hard_timeout = fs.hard_timeout;
1722                 version->flags = 0;
1723                 version->ofpacts = ofpbuf_steal_data(&ofpacts);
1724                 version->ofpacts_len = ofpacts.size;
1725
1726                 fte_insert(cls, &fs.rule, version, index);
1727             }
1728         } else {
1729             VLOG_DBG("received reply with xid %08"PRIx32" "
1730                      "!= expected %08"PRIx32, recv_xid, send_xid);
1731         }
1732         ofpbuf_delete(reply);
1733     }
1734 }
1735
1736 static void
1737 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
1738                   enum ofputil_protocol protocol, struct list *packets)
1739 {
1740     const struct fte_version *version = fte->versions[index];
1741     struct ofputil_flow_mod fm;
1742     struct ofpbuf *ofm;
1743
1744     fm.cr = fte->rule;
1745     fm.cookie = htonll(0);
1746     fm.cookie_mask = htonll(0);
1747     fm.new_cookie = version->cookie;
1748     fm.table_id = 0xff;
1749     fm.command = command;
1750     fm.idle_timeout = version->idle_timeout;
1751     fm.hard_timeout = version->hard_timeout;
1752     fm.buffer_id = UINT32_MAX;
1753     fm.out_port = OFPP_NONE;
1754     fm.flags = version->flags;
1755     if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
1756         command == OFPFC_MODIFY_STRICT) {
1757         fm.ofpacts = version->ofpacts;
1758         fm.ofpacts_len = version->ofpacts_len;
1759     } else {
1760         fm.ofpacts = NULL;
1761         fm.ofpacts_len = 0;
1762     }
1763
1764     ofm = ofputil_encode_flow_mod(&fm, protocol);
1765     list_push_back(packets, &ofm->list_node);
1766 }
1767
1768 static void
1769 ofctl_replace_flows(int argc OVS_UNUSED, char *argv[])
1770 {
1771     enum { FILE_IDX = 0, SWITCH_IDX = 1 };
1772     enum ofputil_protocol usable_protocols, protocol;
1773     struct cls_cursor cursor;
1774     struct classifier cls;
1775     struct list requests;
1776     struct vconn *vconn;
1777     struct fte *fte;
1778
1779     classifier_init(&cls);
1780     usable_protocols = read_flows_from_file(argv[2], &cls, FILE_IDX);
1781
1782     protocol = open_vconn(argv[1], &vconn);
1783     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
1784
1785     read_flows_from_switch(vconn, protocol, &cls, SWITCH_IDX);
1786
1787     list_init(&requests);
1788
1789     /* Delete flows that exist on the switch but not in the file. */
1790     cls_cursor_init(&cursor, &cls, NULL);
1791     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1792         struct fte_version *file_ver = fte->versions[FILE_IDX];
1793         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1794
1795         if (sw_ver && !file_ver) {
1796             fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
1797                               protocol, &requests);
1798         }
1799     }
1800
1801     /* Add flows that exist in the file but not on the switch.
1802      * Update flows that exist in both places but differ. */
1803     cls_cursor_init(&cursor, &cls, NULL);
1804     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1805         struct fte_version *file_ver = fte->versions[FILE_IDX];
1806         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1807
1808         if (file_ver
1809             && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
1810             fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, protocol, &requests);
1811         }
1812     }
1813     transact_multiple_noreply(vconn, &requests);
1814     vconn_close(vconn);
1815
1816     fte_free_all(&cls);
1817 }
1818
1819 static void
1820 read_flows_from_source(const char *source, struct classifier *cls, int index)
1821 {
1822     struct stat s;
1823
1824     if (source[0] == '/' || source[0] == '.'
1825         || (!strchr(source, ':') && !stat(source, &s))) {
1826         read_flows_from_file(source, cls, index);
1827     } else {
1828         enum ofputil_protocol protocol;
1829         struct vconn *vconn;
1830
1831         protocol = open_vconn(source, &vconn);
1832         protocol = set_protocol_for_flow_dump(vconn, protocol, OFPUTIL_P_ANY);
1833         read_flows_from_switch(vconn, protocol, cls, index);
1834         vconn_close(vconn);
1835     }
1836 }
1837
1838 static void
1839 ofctl_diff_flows(int argc OVS_UNUSED, char *argv[])
1840 {
1841     bool differences = false;
1842     struct cls_cursor cursor;
1843     struct classifier cls;
1844     struct fte *fte;
1845
1846     classifier_init(&cls);
1847     read_flows_from_source(argv[1], &cls, 0);
1848     read_flows_from_source(argv[2], &cls, 1);
1849
1850     cls_cursor_init(&cursor, &cls, NULL);
1851     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1852         struct fte_version *a = fte->versions[0];
1853         struct fte_version *b = fte->versions[1];
1854
1855         if (!a || !b || !fte_version_equals(a, b)) {
1856             char *rule_s = cls_rule_to_string(&fte->rule);
1857             if (a) {
1858                 printf("-%s", rule_s);
1859                 fte_version_print(a);
1860             }
1861             if (b) {
1862                 printf("+%s", rule_s);
1863                 fte_version_print(b);
1864             }
1865             free(rule_s);
1866
1867             differences = true;
1868         }
1869     }
1870
1871     fte_free_all(&cls);
1872
1873     if (differences) {
1874         exit(2);
1875     }
1876 }
1877 \f
1878 /* Undocumented commands for unit testing. */
1879
1880 static void
1881 ofctl_parse_flows__(struct ofputil_flow_mod *fms, size_t n_fms)
1882 {
1883     enum ofputil_protocol usable_protocols;
1884     enum ofputil_protocol protocol = 0;
1885     char *usable_s;
1886     size_t i;
1887
1888     usable_protocols = ofputil_flow_mod_usable_protocols(fms, n_fms);
1889     usable_s = ofputil_protocols_to_string(usable_protocols);
1890     printf("usable protocols: %s\n", usable_s);
1891     free(usable_s);
1892
1893     if (!(usable_protocols & allowed_protocols)) {
1894         ovs_fatal(0, "no usable protocol");
1895     }
1896     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1897         protocol = 1 << i;
1898         if (protocol & usable_protocols & allowed_protocols) {
1899             break;
1900         }
1901     }
1902     assert(IS_POW2(protocol));
1903
1904     printf("chosen protocol: %s\n", ofputil_protocol_to_string(protocol));
1905
1906     for (i = 0; i < n_fms; i++) {
1907         struct ofputil_flow_mod *fm = &fms[i];
1908         struct ofpbuf *msg;
1909
1910         msg = ofputil_encode_flow_mod(fm, protocol);
1911         ofp_print(stdout, msg->data, msg->size, verbosity);
1912         ofpbuf_delete(msg);
1913
1914         free(fm->ofpacts);
1915     }
1916 }
1917
1918 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
1919  * it back to stdout.  */
1920 static void
1921 ofctl_parse_flow(int argc OVS_UNUSED, char *argv[])
1922 {
1923     struct ofputil_flow_mod fm;
1924
1925     parse_ofp_flow_mod_str(&fm, argv[1], OFPFC_ADD, false);
1926     ofctl_parse_flows__(&fm, 1);
1927 }
1928
1929 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
1930  * add-flows) and prints each of the flows back to stdout.  */
1931 static void
1932 ofctl_parse_flows(int argc OVS_UNUSED, char *argv[])
1933 {
1934     struct ofputil_flow_mod *fms = NULL;
1935     size_t n_fms = 0;
1936
1937     parse_ofp_flow_mod_file(argv[1], OFPFC_ADD, &fms, &n_fms);
1938     ofctl_parse_flows__(fms, n_fms);
1939     free(fms);
1940 }
1941
1942 static void
1943 ofctl_parse_nxm__(bool oxm)
1944 {
1945     struct ds in;
1946
1947     ds_init(&in);
1948     while (!ds_get_test_line(&in, stdin)) {
1949         struct ofpbuf nx_match;
1950         struct cls_rule rule;
1951         ovs_be64 cookie, cookie_mask;
1952         enum ofperr error;
1953         int match_len;
1954
1955         /* Convert string to nx_match. */
1956         ofpbuf_init(&nx_match, 0);
1957         match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
1958
1959         /* Convert nx_match to cls_rule. */
1960         if (strict) {
1961             error = nx_pull_match(&nx_match, match_len, 0, &rule,
1962                                   &cookie, &cookie_mask);
1963         } else {
1964             error = nx_pull_match_loose(&nx_match, match_len, 0, &rule,
1965                                         &cookie, &cookie_mask);
1966         }
1967
1968         if (!error) {
1969             char *out;
1970
1971             /* Convert cls_rule back to nx_match. */
1972             ofpbuf_uninit(&nx_match);
1973             ofpbuf_init(&nx_match, 0);
1974             match_len = nx_put_match(&nx_match, oxm, &rule,
1975                                      cookie, cookie_mask);
1976
1977             /* Convert nx_match to string. */
1978             out = nx_match_to_string(nx_match.data, match_len);
1979             puts(out);
1980             free(out);
1981         } else {
1982             printf("nx_pull_match() returned error %s\n",
1983                    ofperr_get_name(error));
1984         }
1985
1986         ofpbuf_uninit(&nx_match);
1987     }
1988     ds_destroy(&in);
1989 }
1990
1991 /* "parse-nxm": reads a series of NXM nx_match specifications as strings from
1992  * stdin, does some internal fussing with them, and then prints them back as
1993  * strings on stdout. */
1994 static void
1995 ofctl_parse_nxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1996 {
1997     return ofctl_parse_nxm__(false);
1998 }
1999
2000 /* "parse-oxm": reads a series of OXM nx_match specifications as strings from
2001  * stdin, does some internal fussing with them, and then prints them back as
2002  * strings on stdout. */
2003 static void
2004 ofctl_parse_oxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2005 {
2006     return ofctl_parse_nxm__(true);
2007 }
2008
2009 static void
2010 print_differences(const void *a_, size_t a_len,
2011                   const void *b_, size_t b_len)
2012 {
2013     const uint8_t *a = a_;
2014     const uint8_t *b = b_;
2015     size_t i;
2016
2017     for (i = 0; i < MIN(a_len, b_len); i++) {
2018         if (a[i] != b[i]) {
2019             printf("%2zu: %02"PRIx8" -> %02"PRIx8"\n", i, a[i], b[i]);
2020         }
2021     }
2022     for (i = a_len; i < b_len; i++) {
2023         printf("%2zu: (none) -> %02"PRIx8"\n", i, b[i]);
2024     }
2025     for (i = b_len; i < a_len; i++) {
2026         printf("%2zu: %02"PRIx8" -> (none)\n", i, a[i]);
2027     }
2028 }
2029
2030 /* "parse-ofp10-actions": reads a series of OpenFlow 1.0 action specifications
2031  * as hex bytes from stdin, converts them to ofpacts, prints them as strings
2032  * on stdout, and then converts them back to hex bytes and prints any
2033  * differences from the input. */
2034 static void
2035 ofctl_parse_ofp10_actions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2036 {
2037     struct ds in;
2038
2039     ds_init(&in);
2040     while (!ds_get_preprocessed_line(&in, stdin)) {
2041         struct ofpbuf of10_out;
2042         struct ofpbuf of10_in;
2043         struct ofpbuf ofpacts;
2044         enum ofperr error;
2045         size_t size;
2046         struct ds s;
2047
2048         /* Parse hex bytes. */
2049         ofpbuf_init(&of10_in, 0);
2050         if (ofpbuf_put_hex(&of10_in, ds_cstr(&in), NULL)[0] != '\0') {
2051             ovs_fatal(0, "Trailing garbage in hex data");
2052         }
2053
2054         /* Convert to ofpacts. */
2055         ofpbuf_init(&ofpacts, 0);
2056         size = of10_in.size;
2057         error = ofpacts_pull_openflow10(&of10_in, of10_in.size, &ofpacts);
2058         if (error) {
2059             printf("bad OF1.1 actions: %s\n\n", ofperr_get_name(error));
2060             ofpbuf_uninit(&ofpacts);
2061             ofpbuf_uninit(&of10_in);
2062             continue;
2063         }
2064         ofpbuf_push_uninit(&of10_in, size);
2065
2066         /* Print cls_rule. */
2067         ds_init(&s);
2068         ofpacts_format(ofpacts.data, ofpacts.size, &s);
2069         puts(ds_cstr(&s));
2070         ds_destroy(&s);
2071
2072         /* Convert back to ofp10 actions and print differences from input. */
2073         ofpbuf_init(&of10_out, 0);
2074         ofpacts_put_openflow10(ofpacts.data, ofpacts.size, &of10_out);
2075
2076         print_differences(of10_in.data, of10_in.size,
2077                           of10_out.data, of10_out.size);
2078         putchar('\n');
2079
2080         ofpbuf_uninit(&ofpacts);
2081         ofpbuf_uninit(&of10_in);
2082         ofpbuf_uninit(&of10_out);
2083     }
2084     ds_destroy(&in);
2085 }
2086
2087 /* "parse-ofp11-match": reads a series of ofp11_match specifications as hex
2088  * bytes from stdin, converts them to cls_rules, prints them as strings on
2089  * stdout, and then converts them back to hex bytes and prints any differences
2090  * from the input. */
2091 static void
2092 ofctl_parse_ofp11_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2093 {
2094     struct ds in;
2095
2096     ds_init(&in);
2097     while (!ds_get_preprocessed_line(&in, stdin)) {
2098         struct ofpbuf match_in;
2099         struct ofp11_match match_out;
2100         struct cls_rule rule;
2101         enum ofperr error;
2102
2103         /* Parse hex bytes. */
2104         ofpbuf_init(&match_in, 0);
2105         if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
2106             ovs_fatal(0, "Trailing garbage in hex data");
2107         }
2108         if (match_in.size != sizeof(struct ofp11_match)) {
2109             ovs_fatal(0, "Input is %zu bytes, expected %zu",
2110                       match_in.size, sizeof(struct ofp11_match));
2111         }
2112
2113         /* Convert to cls_rule. */
2114         error = ofputil_cls_rule_from_ofp11_match(match_in.data,
2115                                                   OFP_DEFAULT_PRIORITY, &rule);
2116         if (error) {
2117             printf("bad ofp11_match: %s\n\n", ofperr_get_name(error));
2118             ofpbuf_uninit(&match_in);
2119             continue;
2120         }
2121
2122         /* Print cls_rule. */
2123         cls_rule_print(&rule);
2124
2125         /* Convert back to ofp11_match and print differences from input. */
2126         ofputil_cls_rule_to_ofp11_match(&rule, &match_out);
2127
2128         print_differences(match_in.data, match_in.size,
2129                           &match_out, sizeof match_out);
2130         putchar('\n');
2131
2132         ofpbuf_uninit(&match_in);
2133     }
2134     ds_destroy(&in);
2135 }
2136
2137 /* "parse-ofp11-actions": reads a series of OpenFlow 1.1 action specifications
2138  * as hex bytes from stdin, converts them to ofpacts, prints them as strings
2139  * on stdout, and then converts them back to hex bytes and prints any
2140  * differences from the input. */
2141 static void
2142 ofctl_parse_ofp11_actions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2143 {
2144     struct ds in;
2145
2146     ds_init(&in);
2147     while (!ds_get_preprocessed_line(&in, stdin)) {
2148         struct ofpbuf of11_out;
2149         struct ofpbuf of11_in;
2150         struct ofpbuf ofpacts;
2151         enum ofperr error;
2152         size_t size;
2153         struct ds s;
2154
2155         /* Parse hex bytes. */
2156         ofpbuf_init(&of11_in, 0);
2157         if (ofpbuf_put_hex(&of11_in, ds_cstr(&in), NULL)[0] != '\0') {
2158             ovs_fatal(0, "Trailing garbage in hex data");
2159         }
2160
2161         /* Convert to ofpacts. */
2162         ofpbuf_init(&ofpacts, 0);
2163         size = of11_in.size;
2164         error = ofpacts_pull_openflow11_actions(&of11_in, of11_in.size,
2165                                                 &ofpacts);
2166         if (error) {
2167             printf("bad OF1.1 actions: %s\n\n", ofperr_get_name(error));
2168             ofpbuf_uninit(&ofpacts);
2169             ofpbuf_uninit(&of11_in);
2170             continue;
2171         }
2172         ofpbuf_push_uninit(&of11_in, size);
2173
2174         /* Print cls_rule. */
2175         ds_init(&s);
2176         ofpacts_format(ofpacts.data, ofpacts.size, &s);
2177         puts(ds_cstr(&s));
2178         ds_destroy(&s);
2179
2180         /* Convert back to ofp11 actions and print differences from input. */
2181         ofpbuf_init(&of11_out, 0);
2182         ofpacts_put_openflow11_actions(ofpacts.data, ofpacts.size, &of11_out);
2183
2184         print_differences(of11_in.data, of11_in.size,
2185                           of11_out.data, of11_out.size);
2186         putchar('\n');
2187
2188         ofpbuf_uninit(&ofpacts);
2189         ofpbuf_uninit(&of11_in);
2190         ofpbuf_uninit(&of11_out);
2191     }
2192     ds_destroy(&in);
2193 }
2194
2195 /* "parse-ofp11-instructions": reads a series of OpenFlow 1.1 instruction
2196  * specifications as hex bytes from stdin, converts them to ofpacts, prints
2197  * them as strings on stdout, and then converts them back to hex bytes and
2198  * prints any differences from the input. */
2199 static void
2200 ofctl_parse_ofp11_instructions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2201 {
2202     struct ds in;
2203
2204     ds_init(&in);
2205     while (!ds_get_preprocessed_line(&in, stdin)) {
2206         struct ofpbuf of11_out;
2207         struct ofpbuf of11_in;
2208         struct ofpbuf ofpacts;
2209         enum ofperr error;
2210         size_t size;
2211         struct ds s;
2212
2213         /* Parse hex bytes. */
2214         ofpbuf_init(&of11_in, 0);
2215         if (ofpbuf_put_hex(&of11_in, ds_cstr(&in), NULL)[0] != '\0') {
2216             ovs_fatal(0, "Trailing garbage in hex data");
2217         }
2218
2219         /* Convert to ofpacts. */
2220         ofpbuf_init(&ofpacts, 0);
2221         size = of11_in.size;
2222         error = ofpacts_pull_openflow11_instructions(&of11_in, of11_in.size,
2223                                                      &ofpacts);
2224         if (error) {
2225             printf("bad OF1.1 instructions: %s\n\n", ofperr_get_name(error));
2226             ofpbuf_uninit(&ofpacts);
2227             ofpbuf_uninit(&of11_in);
2228             continue;
2229         }
2230         ofpbuf_push_uninit(&of11_in, size);
2231
2232         /* Print cls_rule. */
2233         ds_init(&s);
2234         ofpacts_format(ofpacts.data, ofpacts.size, &s);
2235         puts(ds_cstr(&s));
2236         ds_destroy(&s);
2237
2238         /* Convert back to ofp11 instructions and print differences from
2239          * input. */
2240         ofpbuf_init(&of11_out, 0);
2241         ofpacts_put_openflow11_instructions(ofpacts.data, ofpacts.size,
2242                                             &of11_out);
2243
2244         print_differences(of11_in.data, of11_in.size,
2245                           of11_out.data, of11_out.size);
2246         putchar('\n');
2247
2248         ofpbuf_uninit(&ofpacts);
2249         ofpbuf_uninit(&of11_in);
2250         ofpbuf_uninit(&of11_out);
2251     }
2252     ds_destroy(&in);
2253 }
2254
2255 /* "print-error ENUM": Prints the type and code of ENUM for every OpenFlow
2256  * version. */
2257 static void
2258 ofctl_print_error(int argc OVS_UNUSED, char *argv[])
2259 {
2260     enum ofperr error;
2261     int version;
2262
2263     error = ofperr_from_name(argv[1]);
2264     if (!error) {
2265         ovs_fatal(0, "unknown error \"%s\"", argv[1]);
2266     }
2267
2268     for (version = 0; version <= UINT8_MAX; version++) {
2269         const struct ofperr_domain *domain;
2270
2271         domain = ofperr_domain_from_version(version);
2272         if (!domain) {
2273             continue;
2274         }
2275
2276         printf("%s: %d,%d\n",
2277                ofperr_domain_get_name(domain),
2278                ofperr_get_type(error, domain),
2279                ofperr_get_code(error, domain));
2280     }
2281 }
2282
2283 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
2284  * binary data, interpreting them as an OpenFlow message, and prints the
2285  * OpenFlow message on stdout, at VERBOSITY (level 2 by default).  */
2286 static void
2287 ofctl_ofp_print(int argc, char *argv[])
2288 {
2289     struct ofpbuf packet;
2290
2291     ofpbuf_init(&packet, strlen(argv[1]) / 2);
2292     if (ofpbuf_put_hex(&packet, argv[1], NULL)[0] != '\0') {
2293         ovs_fatal(0, "trailing garbage following hex bytes");
2294     }
2295     ofp_print(stdout, packet.data, packet.size, argc > 2 ? atoi(argv[2]) : 2);
2296     ofpbuf_uninit(&packet);
2297 }
2298
2299 static const struct command all_commands[] = {
2300     { "show", 1, 1, ofctl_show },
2301     { "monitor", 1, 3, ofctl_monitor },
2302     { "snoop", 1, 1, ofctl_snoop },
2303     { "dump-desc", 1, 1, ofctl_dump_desc },
2304     { "dump-tables", 1, 1, ofctl_dump_tables },
2305     { "dump-flows", 1, 2, ofctl_dump_flows },
2306     { "dump-aggregate", 1, 2, ofctl_dump_aggregate },
2307     { "queue-stats", 1, 3, ofctl_queue_stats },
2308     { "add-flow", 2, 2, ofctl_add_flow },
2309     { "add-flows", 2, 2, ofctl_add_flows },
2310     { "mod-flows", 2, 2, ofctl_mod_flows },
2311     { "del-flows", 1, 2, ofctl_del_flows },
2312     { "replace-flows", 2, 2, ofctl_replace_flows },
2313     { "diff-flows", 2, 2, ofctl_diff_flows },
2314     { "packet-out", 4, INT_MAX, ofctl_packet_out },
2315     { "dump-ports", 1, 2, ofctl_dump_ports },
2316     { "dump-ports-desc", 1, 1, ofctl_dump_ports_desc },
2317     { "mod-port", 3, 3, ofctl_mod_port },
2318     { "get-frags", 1, 1, ofctl_get_frags },
2319     { "set-frags", 2, 2, ofctl_set_frags },
2320     { "probe", 1, 1, ofctl_probe },
2321     { "ping", 1, 2, ofctl_ping },
2322     { "benchmark", 3, 3, ofctl_benchmark },
2323     { "help", 0, INT_MAX, ofctl_help },
2324
2325     /* Undocumented commands for testing. */
2326     { "parse-flow", 1, 1, ofctl_parse_flow },
2327     { "parse-flows", 1, 1, ofctl_parse_flows },
2328     { "parse-nx-match", 0, 0, ofctl_parse_nxm },
2329     { "parse-nxm", 0, 0, ofctl_parse_nxm },
2330     { "parse-oxm", 0, 0, ofctl_parse_oxm },
2331     { "parse-ofp10-actions", 0, 0, ofctl_parse_ofp10_actions },
2332     { "parse-ofp11-match", 0, 0, ofctl_parse_ofp11_match },
2333     { "parse-ofp11-actions", 0, 0, ofctl_parse_ofp11_actions },
2334     { "parse-ofp11-instructions", 0, 0, ofctl_parse_ofp11_instructions },
2335     { "print-error", 1, 1, ofctl_print_error },
2336     { "ofp-print", 1, 2, ofctl_ofp_print },
2337
2338     { NULL, 0, 0, NULL },
2339 };