fatal-signal: SIGPIPE for Windows.
[sliver-openvswitch.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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 <ctype.h>
19 #include <errno.h>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <sys/socket.h>
23 #include <net/if.h>
24 #include <signal.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <sys/fcntl.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31
32 #include "byte-order.h"
33 #include "classifier.h"
34 #include "command-line.h"
35 #include "daemon.h"
36 #include "compiler.h"
37 #include "dirs.h"
38 #include "dynamic-string.h"
39 #include "fatal-signal.h"
40 #include "nx-match.h"
41 #include "odp-util.h"
42 #include "ofp-actions.h"
43 #include "ofp-errors.h"
44 #include "ofp-msgs.h"
45 #include "ofp-parse.h"
46 #include "ofp-print.h"
47 #include "ofp-util.h"
48 #include "ofp-version-opt.h"
49 #include "ofpbuf.h"
50 #include "ofproto/ofproto.h"
51 #include "openflow/nicira-ext.h"
52 #include "openflow/openflow.h"
53 #include "packets.h"
54 #include "pcap-file.h"
55 #include "poll-loop.h"
56 #include "random.h"
57 #include "stream-ssl.h"
58 #include "socket-util.h"
59 #include "timeval.h"
60 #include "unixctl.h"
61 #include "util.h"
62 #include "vconn.h"
63 #include "vlog.h"
64 #include "meta-flow.h"
65 #include "sort.h"
66
67 VLOG_DEFINE_THIS_MODULE(ofctl);
68
69 /* --strict: Use strict matching for flow mod commands?  Additionally governs
70  * use of nx_pull_match() instead of nx_pull_match_loose() in parse-nx-match.
71  */
72 static bool strict;
73
74 /* --readd: If true, on replace-flows, re-add even flows that have not changed
75  * (to reset flow counters). */
76 static bool readd;
77
78 /* -F, --flow-format: Allowed protocols.  By default, any protocol is
79  * allowed. */
80 static enum ofputil_protocol allowed_protocols = OFPUTIL_P_ANY;
81
82 /* -P, --packet-in-format: Packet IN format to use in monitor and snoop
83  * commands.  Either one of NXPIF_* to force a particular packet_in format, or
84  * -1 to let ovs-ofctl choose the default. */
85 static int preferred_packet_in_format = -1;
86
87 /* -m, --more: Additional verbosity for ofp-print functions. */
88 static int verbosity;
89
90 /* --timestamp: Print a timestamp before each received packet on "monitor" and
91  * "snoop" command? */
92 static bool timestamp;
93
94 /* --sort, --rsort: Sort order. */
95 enum sort_order { SORT_ASC, SORT_DESC };
96 struct sort_criterion {
97     const struct mf_field *field; /* NULL means to sort by priority. */
98     enum sort_order order;
99 };
100 static struct sort_criterion *criteria;
101 static size_t n_criteria, allocated_criteria;
102
103 static const struct command *get_all_commands(void);
104
105 static void usage(void) NO_RETURN;
106 static void parse_options(int argc, char *argv[]);
107
108 static bool recv_flow_stats_reply(struct vconn *, ovs_be32 send_xid,
109                                   struct ofpbuf **replyp,
110                                   struct ofputil_flow_stats *,
111                                   struct ofpbuf *ofpacts);
112 int
113 main(int argc, char *argv[])
114 {
115     set_program_name(argv[0]);
116     parse_options(argc, argv);
117     fatal_ignore_sigpipe();
118     run_command(argc - optind, argv + optind, get_all_commands());
119     return 0;
120 }
121
122 static void
123 add_sort_criterion(enum sort_order order, const char *field)
124 {
125     struct sort_criterion *sc;
126
127     if (n_criteria >= allocated_criteria) {
128         criteria = x2nrealloc(criteria, &allocated_criteria, sizeof *criteria);
129     }
130
131     sc = &criteria[n_criteria++];
132     if (!field || !strcasecmp(field, "priority")) {
133         sc->field = NULL;
134     } else {
135         sc->field = mf_from_name(field);
136         if (!sc->field) {
137             ovs_fatal(0, "%s: unknown field name", field);
138         }
139     }
140     sc->order = order;
141 }
142
143 static void
144 parse_options(int argc, char *argv[])
145 {
146     enum {
147         OPT_STRICT = UCHAR_MAX + 1,
148         OPT_READD,
149         OPT_TIMESTAMP,
150         OPT_SORT,
151         OPT_RSORT,
152         DAEMON_OPTION_ENUMS,
153         OFP_VERSION_OPTION_ENUMS,
154         VLOG_OPTION_ENUMS
155     };
156     static const struct option long_options[] = {
157         {"timeout", required_argument, NULL, 't'},
158         {"strict", no_argument, NULL, OPT_STRICT},
159         {"readd", no_argument, NULL, OPT_READD},
160         {"flow-format", required_argument, NULL, 'F'},
161         {"packet-in-format", required_argument, NULL, 'P'},
162         {"more", no_argument, NULL, 'm'},
163         {"timestamp", no_argument, NULL, OPT_TIMESTAMP},
164         {"sort", optional_argument, NULL, OPT_SORT},
165         {"rsort", optional_argument, NULL, OPT_RSORT},
166         {"help", no_argument, NULL, 'h'},
167         DAEMON_LONG_OPTIONS,
168         OFP_VERSION_LONG_OPTIONS,
169         VLOG_LONG_OPTIONS,
170         STREAM_SSL_LONG_OPTIONS,
171         {NULL, 0, NULL, 0},
172     };
173     char *short_options = long_options_to_short_options(long_options);
174     uint32_t versions;
175     enum ofputil_protocol version_protocols;
176
177     for (;;) {
178         unsigned long int timeout;
179         int c;
180
181         c = getopt_long(argc, argv, short_options, long_options, NULL);
182         if (c == -1) {
183             break;
184         }
185
186         switch (c) {
187         case 't':
188             timeout = strtoul(optarg, NULL, 10);
189             if (timeout <= 0) {
190                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
191                           optarg);
192             } else {
193                 time_alarm(timeout);
194             }
195             break;
196
197         case 'F':
198             allowed_protocols = ofputil_protocols_from_string(optarg);
199             if (!allowed_protocols) {
200                 ovs_fatal(0, "%s: invalid flow format(s)", optarg);
201             }
202             break;
203
204         case 'P':
205             preferred_packet_in_format =
206                 ofputil_packet_in_format_from_string(optarg);
207             if (preferred_packet_in_format < 0) {
208                 ovs_fatal(0, "unknown packet-in format `%s'", optarg);
209             }
210             break;
211
212         case 'm':
213             verbosity++;
214             break;
215
216         case 'h':
217             usage();
218
219         case OPT_STRICT:
220             strict = true;
221             break;
222
223         case OPT_READD:
224             readd = true;
225             break;
226
227         case OPT_TIMESTAMP:
228             timestamp = true;
229             break;
230
231         case OPT_SORT:
232             add_sort_criterion(SORT_ASC, optarg);
233             break;
234
235         case OPT_RSORT:
236             add_sort_criterion(SORT_DESC, optarg);
237             break;
238
239         DAEMON_OPTION_HANDLERS
240         OFP_VERSION_OPTION_HANDLERS
241         VLOG_OPTION_HANDLERS
242         STREAM_SSL_OPTION_HANDLERS
243
244         case '?':
245             exit(EXIT_FAILURE);
246
247         default:
248             abort();
249         }
250     }
251
252     if (n_criteria) {
253         /* Always do a final sort pass based on priority. */
254         add_sort_criterion(SORT_DESC, "priority");
255     }
256
257     free(short_options);
258
259     versions = get_allowed_ofp_versions();
260     version_protocols = ofputil_protocols_from_version_bitmap(versions);
261     if (!(allowed_protocols & version_protocols)) {
262         char *protocols = ofputil_protocols_to_string(allowed_protocols);
263         struct ds version_s = DS_EMPTY_INITIALIZER;
264
265         ofputil_format_version_bitmap_names(&version_s, versions);
266         ovs_fatal(0, "None of the enabled OpenFlow versions (%s) supports "
267                   "any of the enabled flow formats (%s).  (Use -O to enable "
268                   "additional OpenFlow versions or -F to enable additional "
269                   "flow formats.)", ds_cstr(&version_s), protocols);
270     }
271     allowed_protocols &= version_protocols;
272     mask_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
273                                   allowed_protocols));
274 }
275
276 static void
277 usage(void)
278 {
279     printf("%s: OpenFlow switch management utility\n"
280            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
281            "\nFor OpenFlow switches:\n"
282            "  show SWITCH                 show OpenFlow information\n"
283            "  dump-desc SWITCH            print switch description\n"
284            "  dump-tables SWITCH          print table stats\n"
285            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
286            "  mod-table SWITCH MOD        modify flow table behavior\n"
287            "  get-frags SWITCH            print fragment handling behavior\n"
288            "  set-frags SWITCH FRAG_MODE  set fragment handling behavior\n"
289            "  dump-ports SWITCH [PORT]    print port statistics\n"
290            "  dump-ports-desc SWITCH      print port descriptions\n"
291            "  dump-flows SWITCH           print all flow entries\n"
292            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
293            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
294            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
295            "  queue-stats SWITCH [PORT [QUEUE]]  dump queue stats\n"
296            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
297            "  add-flows SWITCH FILE       add flows from FILE\n"
298            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
299            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
300            "  replace-flows SWITCH FILE   replace flows with those in FILE\n"
301            "  diff-flows SOURCE1 SOURCE2  compare flows from two sources\n"
302            "  packet-out SWITCH IN_PORT ACTIONS PACKET...\n"
303            "                              execute ACTIONS on PACKET\n"
304            "  monitor SWITCH [MISSLEN] [invalid_ttl] [watch:[...]]\n"
305            "                              print packets received from SWITCH\n"
306            "  snoop SWITCH                snoop on SWITCH and its controller\n"
307            "  add-group SWITCH GROUP      add group described by GROUP\n"
308            "  add-group SWITCH FILE       add group from FILE\n"
309            "  mod-group SWITCH GROUP      modify specific group\n"
310            "  del-groups SWITCH [GROUP]   delete matching GROUPs\n"
311            "  dump-group-features SWITCH  print group features\n"
312            "  dump-groups SWITCH          print group description\n"
313            "  dump-group-stats SWITCH [GROUP]  print group statistics\n"
314            "  queue-get-config SWITCH PORT  print queue information for port\n"
315            "  add-meter SWITCH METER      add meter described by METER\n"
316            "  mod-meter SWITCH METER      modify specific METER\n"
317            "  del-meter SWITCH METER      delete METER\n"
318            "  del-meters SWITCH           delete all meters\n"
319            "  dump-meter SWITCH METER     print METER configuration\n"
320            "  dump-meters SWITCH          print all meter configuration\n"
321            "  meter-stats SWITCH [METER]  print meter statistics\n"
322            "  meter-features SWITCH       print meter features\n"
323            "\nFor OpenFlow switches and controllers:\n"
324            "  probe TARGET                probe whether TARGET is up\n"
325            "  ping TARGET [N]             latency of N-byte echos\n"
326            "  benchmark TARGET N COUNT    bandwidth of COUNT N-byte echos\n"
327            "SWITCH or TARGET is an active OpenFlow connection method.\n"
328            "\nOther commands:\n"
329            "  ofp-parse FILE              print messages read from FILE\n"
330            "  ofp-parse-pcap PCAP         print OpenFlow read from PCAP\n",
331            program_name, program_name);
332     vconn_usage(true, false, false);
333     daemon_usage();
334     ofp_version_usage();
335     vlog_usage();
336     printf("\nOther options:\n"
337            "  --strict                    use strict match for flow commands\n"
338            "  --readd                     replace flows that haven't changed\n"
339            "  -F, --flow-format=FORMAT    force particular flow format\n"
340            "  -P, --packet-in-format=FRMT force particular packet in format\n"
341            "  -m, --more                  be more verbose printing OpenFlow\n"
342            "  --timestamp                 (monitor, snoop) print timestamps\n"
343            "  -t, --timeout=SECS          give up after SECS seconds\n"
344            "  --sort[=field]              sort in ascending order\n"
345            "  --rsort[=field]             sort in descending order\n"
346            "  -h, --help                  display this help message\n"
347            "  -V, --version               display version information\n");
348     exit(EXIT_SUCCESS);
349 }
350
351 static void
352 ofctl_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
353            const char *argv[] OVS_UNUSED, void *exiting_)
354 {
355     bool *exiting = exiting_;
356     *exiting = true;
357     unixctl_command_reply(conn, NULL);
358 }
359
360 static void run(int retval, const char *message, ...)
361     PRINTF_FORMAT(2, 3);
362
363 static void
364 run(int retval, const char *message, ...)
365 {
366     if (retval) {
367         va_list args;
368
369         va_start(args, message);
370         ovs_fatal_valist(retval, message, args);
371     }
372 }
373 \f
374 /* Generic commands. */
375
376 static int
377 open_vconn_socket(const char *name, struct vconn **vconnp)
378 {
379     char *vconn_name = xasprintf("unix:%s", name);
380     int error;
381
382     error = vconn_open(vconn_name, get_allowed_ofp_versions(), DSCP_DEFAULT,
383                        vconnp);
384     if (error && error != ENOENT) {
385         ovs_fatal(0, "%s: failed to open socket (%s)", name,
386                   ovs_strerror(error));
387     }
388     free(vconn_name);
389
390     return error;
391 }
392
393 enum open_target { MGMT, SNOOP };
394
395 static enum ofputil_protocol
396 open_vconn__(const char *name, enum open_target target,
397              struct vconn **vconnp)
398 {
399     const char *suffix = target == MGMT ? "mgmt" : "snoop";
400     char *datapath_name, *datapath_type, *socket_name;
401     enum ofputil_protocol protocol;
402     char *bridge_path;
403     int ofp_version;
404     int error;
405
406     bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, suffix);
407
408     ofproto_parse_name(name, &datapath_name, &datapath_type);
409     socket_name = xasprintf("%s/%s.%s", ovs_rundir(), datapath_name, suffix);
410     free(datapath_name);
411     free(datapath_type);
412
413     if (strchr(name, ':')) {
414         run(vconn_open(name, get_allowed_ofp_versions(), DSCP_DEFAULT, vconnp),
415             "connecting to %s", name);
416     } else if (!open_vconn_socket(name, vconnp)) {
417         /* Fall Through. */
418     } else if (!open_vconn_socket(bridge_path, vconnp)) {
419         /* Fall Through. */
420     } else if (!open_vconn_socket(socket_name, vconnp)) {
421         /* Fall Through. */
422     } else {
423         ovs_fatal(0, "%s is not a bridge or a socket", name);
424     }
425
426     if (target == SNOOP) {
427         vconn_set_recv_any_version(*vconnp);
428     }
429
430     free(bridge_path);
431     free(socket_name);
432
433     VLOG_DBG("connecting to %s", vconn_get_name(*vconnp));
434     error = vconn_connect_block(*vconnp);
435     if (error) {
436         ovs_fatal(0, "%s: failed to connect to socket (%s)", name,
437                   ovs_strerror(error));
438     }
439
440     ofp_version = vconn_get_version(*vconnp);
441     protocol = ofputil_protocol_from_ofp_version(ofp_version);
442     if (!protocol) {
443         ovs_fatal(0, "%s: unsupported OpenFlow version 0x%02x",
444                   name, ofp_version);
445     }
446     return protocol;
447 }
448
449 static enum ofputil_protocol
450 open_vconn(const char *name, struct vconn **vconnp)
451 {
452     return open_vconn__(name, MGMT, vconnp);
453 }
454
455 static void
456 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
457 {
458     ofpmsg_update_length(buffer);
459     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
460 }
461
462 static void
463 dump_transaction(struct vconn *vconn, struct ofpbuf *request)
464 {
465     struct ofpbuf *reply;
466
467     ofpmsg_update_length(request);
468     run(vconn_transact(vconn, request, &reply), "talking to %s",
469         vconn_get_name(vconn));
470     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
471     ofpbuf_delete(reply);
472 }
473
474 static void
475 dump_trivial_transaction(const char *vconn_name, enum ofpraw raw)
476 {
477     struct ofpbuf *request;
478     struct vconn *vconn;
479
480     open_vconn(vconn_name, &vconn);
481     request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
482     dump_transaction(vconn, request);
483     vconn_close(vconn);
484 }
485
486 static void
487 dump_stats_transaction(struct vconn *vconn, struct ofpbuf *request)
488 {
489     const struct ofp_header *request_oh = request->data;
490     ovs_be32 send_xid = request_oh->xid;
491     enum ofpraw request_raw;
492     enum ofpraw reply_raw;
493     bool done = false;
494
495     ofpraw_decode_partial(&request_raw, request->data, request->size);
496     reply_raw = ofpraw_stats_request_to_reply(request_raw,
497                                               request_oh->version);
498
499     send_openflow_buffer(vconn, request);
500     while (!done) {
501         ovs_be32 recv_xid;
502         struct ofpbuf *reply;
503
504         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
505         recv_xid = ((struct ofp_header *) reply->data)->xid;
506         if (send_xid == recv_xid) {
507             enum ofpraw raw;
508
509             ofp_print(stdout, reply->data, reply->size, verbosity + 1);
510
511             ofpraw_decode(&raw, reply->data);
512             if (ofptype_from_ofpraw(raw) == OFPTYPE_ERROR) {
513                 done = true;
514             } else if (raw == reply_raw) {
515                 done = !ofpmp_more(reply->data);
516             } else {
517                 ovs_fatal(0, "received bad reply: %s",
518                           ofp_to_string(reply->data, reply->size,
519                                         verbosity + 1));
520             }
521         } else {
522             VLOG_DBG("received reply with xid %08"PRIx32" "
523                      "!= expected %08"PRIx32, recv_xid, send_xid);
524         }
525         ofpbuf_delete(reply);
526     }
527 }
528
529 static void
530 dump_trivial_stats_transaction(const char *vconn_name, enum ofpraw raw)
531 {
532     struct ofpbuf *request;
533     struct vconn *vconn;
534
535     open_vconn(vconn_name, &vconn);
536     request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
537     dump_stats_transaction(vconn, request);
538     vconn_close(vconn);
539 }
540
541 /* Sends all of the 'requests', which should be requests that only have replies
542  * if an error occurs, and waits for them to succeed or fail.  If an error does
543  * occur, prints it and exits with an error.
544  *
545  * Destroys all of the 'requests'. */
546 static void
547 transact_multiple_noreply(struct vconn *vconn, struct list *requests)
548 {
549     struct ofpbuf *request, *reply;
550
551     LIST_FOR_EACH (request, list_node, requests) {
552         ofpmsg_update_length(request);
553     }
554
555     run(vconn_transact_multiple_noreply(vconn, requests, &reply),
556         "talking to %s", vconn_get_name(vconn));
557     if (reply) {
558         ofp_print(stderr, reply->data, reply->size, verbosity + 2);
559         exit(1);
560     }
561     ofpbuf_delete(reply);
562 }
563
564 /* Sends 'request', which should be a request that only has a reply if an error
565  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
566  * it and exits with an error.
567  *
568  * Destroys 'request'. */
569 static void
570 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
571 {
572     struct list requests;
573
574     list_init(&requests);
575     list_push_back(&requests, &request->list_node);
576     transact_multiple_noreply(vconn, &requests);
577 }
578
579 static void
580 fetch_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
581 {
582     struct ofp_switch_config *config;
583     struct ofpbuf *request;
584     struct ofpbuf *reply;
585     enum ofptype type;
586
587     request = ofpraw_alloc(OFPRAW_OFPT_GET_CONFIG_REQUEST,
588                            vconn_get_version(vconn), 0);
589     run(vconn_transact(vconn, request, &reply),
590         "talking to %s", vconn_get_name(vconn));
591
592     if (ofptype_pull(&type, reply) || type != OFPTYPE_GET_CONFIG_REPLY) {
593         ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
594     }
595
596     config = ofpbuf_pull(reply, sizeof *config);
597     *config_ = *config;
598
599     ofpbuf_delete(reply);
600 }
601
602 static void
603 set_switch_config(struct vconn *vconn, const struct ofp_switch_config *config)
604 {
605     struct ofpbuf *request;
606
607     request = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG, vconn_get_version(vconn), 0);
608     ofpbuf_put(request, config, sizeof *config);
609
610     transact_noreply(vconn, request);
611 }
612
613 static void
614 ofctl_show(int argc OVS_UNUSED, char *argv[])
615 {
616     const char *vconn_name = argv[1];
617     struct vconn *vconn;
618     struct ofpbuf *request;
619     struct ofpbuf *reply;
620     bool trunc;
621
622     open_vconn(vconn_name, &vconn);
623     request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST,
624                            vconn_get_version(vconn), 0);
625     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
626
627     trunc = ofputil_switch_features_ports_trunc(reply);
628     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
629
630     ofpbuf_delete(reply);
631
632     if (trunc) {
633         /* The Features Reply may not contain all the ports, so send a
634          * Port Description stats request, which doesn't have size
635          * constraints. */
636         dump_trivial_stats_transaction(vconn_name,
637                                        OFPRAW_OFPST_PORT_DESC_REQUEST);
638     }
639     dump_trivial_transaction(vconn_name, OFPRAW_OFPT_GET_CONFIG_REQUEST);
640     vconn_close(vconn);
641 }
642
643 static void
644 ofctl_dump_desc(int argc OVS_UNUSED, char *argv[])
645 {
646     dump_trivial_stats_transaction(argv[1], OFPRAW_OFPST_DESC_REQUEST);
647 }
648
649 static void
650 ofctl_dump_tables(int argc OVS_UNUSED, char *argv[])
651 {
652     dump_trivial_stats_transaction(argv[1], OFPRAW_OFPST_TABLE_REQUEST);
653 }
654
655 static bool
656 fetch_port_by_features(const char *vconn_name,
657                        const char *port_name, ofp_port_t port_no,
658                        struct ofputil_phy_port *pp, bool *trunc)
659 {
660     struct ofputil_switch_features features;
661     const struct ofp_header *oh;
662     struct ofpbuf *request, *reply;
663     struct vconn *vconn;
664     enum ofperr error;
665     enum ofptype type;
666     struct ofpbuf b;
667     bool found = false;
668
669     /* Fetch the switch's ofp_switch_features. */
670     open_vconn(vconn_name, &vconn);
671     request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST,
672                            vconn_get_version(vconn), 0);
673     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
674     vconn_close(vconn);
675
676     oh = reply->data;
677     if (ofptype_decode(&type, reply->data)
678         || type != OFPTYPE_FEATURES_REPLY) {
679         ovs_fatal(0, "%s: received bad features reply", vconn_name);
680     }
681
682     *trunc = false;
683     if (ofputil_switch_features_ports_trunc(reply)) {
684         *trunc = true;
685         goto exit;
686     }
687
688     error = ofputil_decode_switch_features(oh, &features, &b);
689     if (error) {
690         ovs_fatal(0, "%s: failed to decode features reply (%s)",
691                   vconn_name, ofperr_to_string(error));
692     }
693
694     while (!ofputil_pull_phy_port(oh->version, &b, pp)) {
695         if (port_no != OFPP_NONE
696             ? port_no == pp->port_no
697             : !strcmp(pp->name, port_name)) {
698             found = true;
699             goto exit;
700         }
701     }
702
703 exit:
704     ofpbuf_delete(reply);
705     return found;
706 }
707
708 static bool
709 fetch_port_by_stats(const char *vconn_name,
710                     const char *port_name, ofp_port_t port_no,
711                     struct ofputil_phy_port *pp)
712 {
713     struct ofpbuf *request;
714     struct vconn *vconn;
715     ovs_be32 send_xid;
716     bool done = false;
717     bool found = false;
718
719     request = ofpraw_alloc(OFPRAW_OFPST_PORT_DESC_REQUEST, OFP10_VERSION, 0);
720     send_xid = ((struct ofp_header *) request->data)->xid;
721
722     open_vconn(vconn_name, &vconn);
723     send_openflow_buffer(vconn, request);
724     while (!done) {
725         ovs_be32 recv_xid;
726         struct ofpbuf *reply;
727
728         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
729         recv_xid = ((struct ofp_header *) reply->data)->xid;
730         if (send_xid == recv_xid) {
731             struct ofp_header *oh = reply->data;
732             enum ofptype type;
733             struct ofpbuf b;
734             uint16_t flags;
735
736             ofpbuf_use_const(&b, oh, ntohs(oh->length));
737             if (ofptype_pull(&type, &b)
738                 || type != OFPTYPE_PORT_DESC_STATS_REPLY) {
739                 ovs_fatal(0, "received bad reply: %s",
740                           ofp_to_string(reply->data, reply->size,
741                                         verbosity + 1));
742             }
743
744             flags = ofpmp_flags(oh);
745             done = !(flags & OFPSF_REPLY_MORE);
746
747             if (found) {
748                 /* We've already found the port, but we need to drain
749                  * the queue of any other replies for this request. */
750                 continue;
751             }
752
753             while (!ofputil_pull_phy_port(oh->version, &b, pp)) {
754                 if (port_no != OFPP_NONE ? port_no == pp->port_no
755                                          : !strcmp(pp->name, port_name)) {
756                     found = true;
757                     break;
758                 }
759             }
760         } else {
761             VLOG_DBG("received reply with xid %08"PRIx32" "
762                      "!= expected %08"PRIx32, recv_xid, send_xid);
763         }
764         ofpbuf_delete(reply);
765     }
766     vconn_close(vconn);
767
768     return found;
769 }
770
771 static bool
772 str_to_ofp(const char *s, ofp_port_t *ofp_port)
773 {
774     bool ret;
775     uint32_t port_;
776
777     ret = str_to_uint(s, 10, &port_);
778     *ofp_port = u16_to_ofp(port_);
779     return ret;
780 }
781
782 /* Opens a connection to 'vconn_name', fetches the port structure for
783  * 'port_name' (which may be a port name or number), and copies it into
784  * '*pp'. */
785 static void
786 fetch_ofputil_phy_port(const char *vconn_name, const char *port_name,
787                        struct ofputil_phy_port *pp)
788 {
789     ofp_port_t port_no;
790     bool found;
791     bool trunc;
792
793     /* Try to interpret the argument as a port number. */
794     if (!str_to_ofp(port_name, &port_no)) {
795         port_no = OFPP_NONE;
796     }
797
798     /* Try to find the port based on the Features Reply.  If it looks
799      * like the results may be truncated, then use the Port Description
800      * stats message introduced in OVS 1.7. */
801     found = fetch_port_by_features(vconn_name, port_name, port_no, pp,
802                                    &trunc);
803     if (trunc) {
804         found = fetch_port_by_stats(vconn_name, port_name, port_no, pp);
805     }
806
807     if (!found) {
808         ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
809     }
810 }
811
812 /* Returns the port number corresponding to 'port_name' (which may be a port
813  * name or number) within the switch 'vconn_name'. */
814 static ofp_port_t
815 str_to_port_no(const char *vconn_name, const char *port_name)
816 {
817     ofp_port_t port_no;
818
819     if (ofputil_port_from_string(port_name, &port_no)) {
820         return port_no;
821     } else {
822         struct ofputil_phy_port pp;
823
824         fetch_ofputil_phy_port(vconn_name, port_name, &pp);
825         return pp.port_no;
826     }
827 }
828
829 static bool
830 try_set_protocol(struct vconn *vconn, enum ofputil_protocol want,
831                  enum ofputil_protocol *cur)
832 {
833     for (;;) {
834         struct ofpbuf *request, *reply;
835         enum ofputil_protocol next;
836
837         request = ofputil_encode_set_protocol(*cur, want, &next);
838         if (!request) {
839             return *cur == want;
840         }
841
842         run(vconn_transact_noreply(vconn, request, &reply),
843             "talking to %s", vconn_get_name(vconn));
844         if (reply) {
845             char *s = ofp_to_string(reply->data, reply->size, 2);
846             VLOG_DBG("%s: failed to set protocol, switch replied: %s",
847                      vconn_get_name(vconn), s);
848             free(s);
849             ofpbuf_delete(reply);
850             return false;
851         }
852
853         *cur = next;
854     }
855 }
856
857 static enum ofputil_protocol
858 set_protocol_for_flow_dump(struct vconn *vconn,
859                            enum ofputil_protocol cur_protocol,
860                            enum ofputil_protocol usable_protocols)
861 {
862     char *usable_s;
863     int i;
864
865     for (i = 0; i < ofputil_n_flow_dump_protocols; i++) {
866         enum ofputil_protocol f = ofputil_flow_dump_protocols[i];
867         if (f & usable_protocols & allowed_protocols
868             && try_set_protocol(vconn, f, &cur_protocol)) {
869             return f;
870         }
871     }
872
873     usable_s = ofputil_protocols_to_string(usable_protocols);
874     if (usable_protocols & allowed_protocols) {
875         ovs_fatal(0, "switch does not support any of the usable flow "
876                   "formats (%s)", usable_s);
877     } else {
878         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
879         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
880                   "allowed flow formats (%s)", usable_s, allowed_s);
881     }
882 }
883
884 static struct vconn *
885 prepare_dump_flows(int argc, char *argv[], bool aggregate,
886                    struct ofpbuf **requestp)
887 {
888     enum ofputil_protocol usable_protocols, protocol;
889     struct ofputil_flow_stats_request fsr;
890     struct vconn *vconn;
891     char *error;
892
893     error = parse_ofp_flow_stats_request_str(&fsr, aggregate,
894                                              argc > 2 ? argv[2] : "",
895                                              &usable_protocols);
896     if (error) {
897         ovs_fatal(0, "%s", error);
898     }
899
900     protocol = open_vconn(argv[1], &vconn);
901     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
902     *requestp = ofputil_encode_flow_stats_request(&fsr, protocol);
903     return vconn;
904 }
905
906 static void
907 ofctl_dump_flows__(int argc, char *argv[], bool aggregate)
908 {
909     struct ofpbuf *request;
910     struct vconn *vconn;
911
912     vconn = prepare_dump_flows(argc, argv, aggregate, &request);
913     dump_stats_transaction(vconn, request);
914     vconn_close(vconn);
915 }
916
917 static int
918 compare_flows(const void *afs_, const void *bfs_)
919 {
920     const struct ofputil_flow_stats *afs = afs_;
921     const struct ofputil_flow_stats *bfs = bfs_;
922     const struct match *a = &afs->match;
923     const struct match *b = &bfs->match;
924     const struct sort_criterion *sc;
925
926     for (sc = criteria; sc < &criteria[n_criteria]; sc++) {
927         const struct mf_field *f = sc->field;
928         int ret;
929
930         if (!f) {
931             unsigned int a_pri = afs->priority;
932             unsigned int b_pri = bfs->priority;
933             ret = a_pri < b_pri ? -1 : a_pri > b_pri;
934         } else {
935             bool ina, inb;
936
937             ina = mf_are_prereqs_ok(f, &a->flow) && !mf_is_all_wild(f, &a->wc);
938             inb = mf_are_prereqs_ok(f, &b->flow) && !mf_is_all_wild(f, &b->wc);
939             if (ina != inb) {
940                 /* Skip the test for sc->order, so that missing fields always
941                  * sort to the end whether we're sorting in ascending or
942                  * descending order. */
943                 return ina ? -1 : 1;
944             } else {
945                 union mf_value aval, bval;
946
947                 mf_get_value(f, &a->flow, &aval);
948                 mf_get_value(f, &b->flow, &bval);
949                 ret = memcmp(&aval, &bval, f->n_bytes);
950             }
951         }
952
953         if (ret) {
954             return sc->order == SORT_ASC ? ret : -ret;
955         }
956     }
957
958     return 0;
959 }
960
961 static void
962 ofctl_dump_flows(int argc, char *argv[])
963 {
964     if (!n_criteria) {
965         return ofctl_dump_flows__(argc, argv, false);
966     } else {
967         struct ofputil_flow_stats *fses;
968         size_t n_fses, allocated_fses;
969         struct ofpbuf *request;
970         struct ofpbuf ofpacts;
971         struct ofpbuf *reply;
972         struct vconn *vconn;
973         ovs_be32 send_xid;
974         struct ds s;
975         size_t i;
976
977         vconn = prepare_dump_flows(argc, argv, false, &request);
978         send_xid = ((struct ofp_header *) request->data)->xid;
979         send_openflow_buffer(vconn, request);
980
981         fses = NULL;
982         n_fses = allocated_fses = 0;
983         reply = NULL;
984         ofpbuf_init(&ofpacts, 0);
985         for (;;) {
986             struct ofputil_flow_stats *fs;
987
988             if (n_fses >= allocated_fses) {
989                 fses = x2nrealloc(fses, &allocated_fses, sizeof *fses);
990             }
991
992             fs = &fses[n_fses];
993             if (!recv_flow_stats_reply(vconn, send_xid, &reply, fs,
994                                        &ofpacts)) {
995                 break;
996             }
997             fs->ofpacts = xmemdup(fs->ofpacts, fs->ofpacts_len);
998             n_fses++;
999         }
1000         ofpbuf_uninit(&ofpacts);
1001
1002         qsort(fses, n_fses, sizeof *fses, compare_flows);
1003
1004         ds_init(&s);
1005         for (i = 0; i < n_fses; i++) {
1006             ds_clear(&s);
1007             ofp_print_flow_stats(&s, &fses[i]);
1008             puts(ds_cstr(&s));
1009         }
1010         ds_destroy(&s);
1011
1012         for (i = 0; i < n_fses; i++) {
1013             free(fses[i].ofpacts);
1014         }
1015         free(fses);
1016
1017         vconn_close(vconn);
1018     }
1019 }
1020
1021 static void
1022 ofctl_dump_aggregate(int argc, char *argv[])
1023 {
1024     return ofctl_dump_flows__(argc, argv, true);
1025 }
1026
1027 static void
1028 ofctl_queue_stats(int argc, char *argv[])
1029 {
1030     struct ofpbuf *request;
1031     struct vconn *vconn;
1032     struct ofputil_queue_stats_request oqs;
1033
1034     open_vconn(argv[1], &vconn);
1035
1036     if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
1037         oqs.port_no = str_to_port_no(argv[1], argv[2]);
1038     } else {
1039         oqs.port_no = OFPP_ANY;
1040     }
1041     if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
1042         oqs.queue_id = atoi(argv[3]);
1043     } else {
1044         oqs.queue_id = OFPQ_ALL;
1045     }
1046
1047     request = ofputil_encode_queue_stats_request(vconn_get_version(vconn), &oqs);
1048     dump_stats_transaction(vconn, request);
1049     vconn_close(vconn);
1050 }
1051
1052 static void
1053 ofctl_queue_get_config(int argc OVS_UNUSED, char *argv[])
1054 {
1055     const char *vconn_name = argv[1];
1056     const char *port_name = argv[2];
1057     enum ofputil_protocol protocol;
1058     enum ofp_version version;
1059     struct ofpbuf *request;
1060     struct vconn *vconn;
1061     ofp_port_t port;
1062
1063     port = str_to_port_no(vconn_name, port_name);
1064
1065     protocol = open_vconn(vconn_name, &vconn);
1066     version = ofputil_protocol_to_ofp_version(protocol);
1067     request = ofputil_encode_queue_get_config_request(version, port);
1068     dump_transaction(vconn, request);
1069     vconn_close(vconn);
1070 }
1071
1072 static enum ofputil_protocol
1073 open_vconn_for_flow_mod(const char *remote, struct vconn **vconnp,
1074                         enum ofputil_protocol usable_protocols)
1075 {
1076     enum ofputil_protocol cur_protocol;
1077     char *usable_s;
1078     int i;
1079
1080     if (!(usable_protocols & allowed_protocols)) {
1081         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
1082         usable_s = ofputil_protocols_to_string(usable_protocols);
1083         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
1084                   "allowed flow formats (%s)", usable_s, allowed_s);
1085     }
1086
1087     /* If the initial flow format is allowed and usable, keep it. */
1088     cur_protocol = open_vconn(remote, vconnp);
1089     if (usable_protocols & allowed_protocols & cur_protocol) {
1090         return cur_protocol;
1091     }
1092
1093     /* Otherwise try each flow format in turn. */
1094     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1095         enum ofputil_protocol f = 1 << i;
1096
1097         if (f != cur_protocol
1098             && f & usable_protocols & allowed_protocols
1099             && try_set_protocol(*vconnp, f, &cur_protocol)) {
1100             return f;
1101         }
1102     }
1103
1104     usable_s = ofputil_protocols_to_string(usable_protocols);
1105     ovs_fatal(0, "switch does not support any of the usable flow "
1106               "formats (%s)", usable_s);
1107 }
1108
1109 static void
1110 ofctl_flow_mod__(const char *remote, struct ofputil_flow_mod *fms,
1111                  size_t n_fms, enum ofputil_protocol usable_protocols)
1112 {
1113     enum ofputil_protocol protocol;
1114     struct vconn *vconn;
1115     size_t i;
1116
1117     protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
1118
1119     for (i = 0; i < n_fms; i++) {
1120         struct ofputil_flow_mod *fm = &fms[i];
1121
1122         transact_noreply(vconn, ofputil_encode_flow_mod(fm, protocol));
1123         free(fm->ofpacts);
1124     }
1125     vconn_close(vconn);
1126 }
1127
1128 static void
1129 ofctl_flow_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
1130 {
1131     enum ofputil_protocol usable_protocols;
1132     struct ofputil_flow_mod *fms = NULL;
1133     size_t n_fms = 0;
1134     char *error;
1135
1136     error = parse_ofp_flow_mod_file(argv[2], command, &fms, &n_fms,
1137                                     &usable_protocols);
1138     if (error) {
1139         ovs_fatal(0, "%s", error);
1140     }
1141     ofctl_flow_mod__(argv[1], fms, n_fms, usable_protocols);
1142     free(fms);
1143 }
1144
1145 static void
1146 ofctl_flow_mod(int argc, char *argv[], uint16_t command)
1147 {
1148     if (argc > 2 && !strcmp(argv[2], "-")) {
1149         ofctl_flow_mod_file(argc, argv, command);
1150     } else {
1151         struct ofputil_flow_mod fm;
1152         char *error;
1153         enum ofputil_protocol usable_protocols;
1154
1155         error = parse_ofp_flow_mod_str(&fm, argc > 2 ? argv[2] : "", command,
1156                                        &usable_protocols);
1157         if (error) {
1158             ovs_fatal(0, "%s", error);
1159         }
1160         ofctl_flow_mod__(argv[1], &fm, 1, usable_protocols);
1161     }
1162 }
1163
1164 static void
1165 ofctl_add_flow(int argc, char *argv[])
1166 {
1167     ofctl_flow_mod(argc, argv, OFPFC_ADD);
1168 }
1169
1170 static void
1171 ofctl_add_flows(int argc, char *argv[])
1172 {
1173     ofctl_flow_mod_file(argc, argv, OFPFC_ADD);
1174 }
1175
1176 static void
1177 ofctl_mod_flows(int argc, char *argv[])
1178 {
1179     ofctl_flow_mod(argc, argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
1180 }
1181
1182 static void
1183 ofctl_del_flows(int argc, char *argv[])
1184 {
1185     ofctl_flow_mod(argc, argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
1186 }
1187
1188 static void
1189 set_packet_in_format(struct vconn *vconn,
1190                      enum nx_packet_in_format packet_in_format)
1191 {
1192     struct ofpbuf *spif;
1193
1194     spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1195                                              packet_in_format);
1196     transact_noreply(vconn, spif);
1197     VLOG_DBG("%s: using user-specified packet in format %s",
1198              vconn_get_name(vconn),
1199              ofputil_packet_in_format_to_string(packet_in_format));
1200 }
1201
1202 static int
1203 monitor_set_invalid_ttl_to_controller(struct vconn *vconn)
1204 {
1205     struct ofp_switch_config config;
1206     enum ofp_config_flags flags;
1207
1208     fetch_switch_config(vconn, &config);
1209     flags = ntohs(config.flags);
1210     if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
1211         /* Set the invalid ttl config. */
1212         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
1213
1214         config.flags = htons(flags);
1215         set_switch_config(vconn, &config);
1216
1217         /* Then retrieve the configuration to see if it really took.  OpenFlow
1218          * doesn't define error reporting for bad modes, so this is all we can
1219          * do. */
1220         fetch_switch_config(vconn, &config);
1221         flags = ntohs(config.flags);
1222         if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
1223             ovs_fatal(0, "setting invalid_ttl_to_controller failed (this "
1224                       "switch probably doesn't support mode)");
1225             return -EOPNOTSUPP;
1226         }
1227     }
1228     return 0;
1229 }
1230
1231 /* Converts hex digits in 'hex' to an OpenFlow message in '*msgp'.  The
1232  * caller must free '*msgp'.  On success, returns NULL.  On failure, returns
1233  * an error message and stores NULL in '*msgp'. */
1234 static const char *
1235 openflow_from_hex(const char *hex, struct ofpbuf **msgp)
1236 {
1237     struct ofp_header *oh;
1238     struct ofpbuf *msg;
1239
1240     msg = ofpbuf_new(strlen(hex) / 2);
1241     *msgp = NULL;
1242
1243     if (ofpbuf_put_hex(msg, hex, NULL)[0] != '\0') {
1244         ofpbuf_delete(msg);
1245         return "Trailing garbage in hex data";
1246     }
1247
1248     if (msg->size < sizeof(struct ofp_header)) {
1249         ofpbuf_delete(msg);
1250         return "Message too short for OpenFlow";
1251     }
1252
1253     oh = msg->data;
1254     if (msg->size != ntohs(oh->length)) {
1255         ofpbuf_delete(msg);
1256         return "Message size does not match length in OpenFlow header";
1257     }
1258
1259     *msgp = msg;
1260     return NULL;
1261 }
1262
1263 static void
1264 ofctl_send(struct unixctl_conn *conn, int argc,
1265            const char *argv[], void *vconn_)
1266 {
1267     struct vconn *vconn = vconn_;
1268     struct ds reply;
1269     bool ok;
1270     int i;
1271
1272     ok = true;
1273     ds_init(&reply);
1274     for (i = 1; i < argc; i++) {
1275         const char *error_msg;
1276         struct ofpbuf *msg;
1277         int error;
1278
1279         error_msg = openflow_from_hex(argv[i], &msg);
1280         if (error_msg) {
1281             ds_put_format(&reply, "%s\n", error_msg);
1282             ok = false;
1283             continue;
1284         }
1285
1286         fprintf(stderr, "send: ");
1287         ofp_print(stderr, msg->data, msg->size, verbosity);
1288
1289         error = vconn_send_block(vconn, msg);
1290         if (error) {
1291             ofpbuf_delete(msg);
1292             ds_put_format(&reply, "%s\n", ovs_strerror(error));
1293             ok = false;
1294         } else {
1295             ds_put_cstr(&reply, "sent\n");
1296         }
1297     }
1298
1299     if (ok) {
1300         unixctl_command_reply(conn, ds_cstr(&reply));
1301     } else {
1302         unixctl_command_reply_error(conn, ds_cstr(&reply));
1303     }
1304     ds_destroy(&reply);
1305 }
1306
1307 struct barrier_aux {
1308     struct vconn *vconn;        /* OpenFlow connection for sending barrier. */
1309     struct unixctl_conn *conn;  /* Connection waiting for barrier response. */
1310 };
1311
1312 static void
1313 ofctl_barrier(struct unixctl_conn *conn, int argc OVS_UNUSED,
1314               const char *argv[] OVS_UNUSED, void *aux_)
1315 {
1316     struct barrier_aux *aux = aux_;
1317     struct ofpbuf *msg;
1318     int error;
1319
1320     if (aux->conn) {
1321         unixctl_command_reply_error(conn, "already waiting for barrier reply");
1322         return;
1323     }
1324
1325     msg = ofputil_encode_barrier_request(vconn_get_version(aux->vconn));
1326     error = vconn_send_block(aux->vconn, msg);
1327     if (error) {
1328         ofpbuf_delete(msg);
1329         unixctl_command_reply_error(conn, ovs_strerror(error));
1330     } else {
1331         aux->conn = conn;
1332     }
1333 }
1334
1335 static void
1336 ofctl_set_output_file(struct unixctl_conn *conn, int argc OVS_UNUSED,
1337                       const char *argv[], void *aux OVS_UNUSED)
1338 {
1339     int fd;
1340
1341     fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
1342     if (fd < 0) {
1343         unixctl_command_reply_error(conn, ovs_strerror(errno));
1344         return;
1345     }
1346
1347     fflush(stderr);
1348     dup2(fd, STDERR_FILENO);
1349     close(fd);
1350     unixctl_command_reply(conn, NULL);
1351 }
1352
1353 static void
1354 ofctl_block(struct unixctl_conn *conn, int argc OVS_UNUSED,
1355             const char *argv[] OVS_UNUSED, void *blocked_)
1356 {
1357     bool *blocked = blocked_;
1358
1359     if (!*blocked) {
1360         *blocked = true;
1361         unixctl_command_reply(conn, NULL);
1362     } else {
1363         unixctl_command_reply(conn, "already blocking");
1364     }
1365 }
1366
1367 static void
1368 ofctl_unblock(struct unixctl_conn *conn, int argc OVS_UNUSED,
1369               const char *argv[] OVS_UNUSED, void *blocked_)
1370 {
1371     bool *blocked = blocked_;
1372
1373     if (*blocked) {
1374         *blocked = false;
1375         unixctl_command_reply(conn, NULL);
1376     } else {
1377         unixctl_command_reply(conn, "already unblocked");
1378     }
1379 }
1380
1381 /* Prints to stdout all of the messages received on 'vconn'.
1382  *
1383  * Iff 'reply_to_echo_requests' is true, sends a reply to any echo request
1384  * received on 'vconn'. */
1385 static void
1386 monitor_vconn(struct vconn *vconn, bool reply_to_echo_requests)
1387 {
1388     struct barrier_aux barrier_aux = { vconn, NULL };
1389     struct unixctl_server *server;
1390     bool exiting = false;
1391     bool blocked = false;
1392     int error;
1393
1394     daemon_save_fd(STDERR_FILENO);
1395     daemonize_start();
1396     error = unixctl_server_create(NULL, &server);
1397     if (error) {
1398         ovs_fatal(error, "failed to create unixctl server");
1399     }
1400     unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
1401     unixctl_command_register("ofctl/send", "OFMSG...", 1, INT_MAX,
1402                              ofctl_send, vconn);
1403     unixctl_command_register("ofctl/barrier", "", 0, 0,
1404                              ofctl_barrier, &barrier_aux);
1405     unixctl_command_register("ofctl/set-output-file", "FILE", 1, 1,
1406                              ofctl_set_output_file, NULL);
1407
1408     unixctl_command_register("ofctl/block", "", 0, 0, ofctl_block, &blocked);
1409     unixctl_command_register("ofctl/unblock", "", 0, 0, ofctl_unblock,
1410                              &blocked);
1411
1412     daemonize_complete();
1413
1414     for (;;) {
1415         struct ofpbuf *b;
1416         int retval;
1417
1418         unixctl_server_run(server);
1419
1420         while (!blocked) {
1421             enum ofptype type;
1422
1423             retval = vconn_recv(vconn, &b);
1424             if (retval == EAGAIN) {
1425                 break;
1426             }
1427             run(retval, "vconn_recv");
1428
1429             if (timestamp) {
1430                 char *s = xastrftime_msec("%Y-%m-%d %H:%M:%S.###: ",
1431                                           time_wall_msec(), true);
1432                 fputs(s, stderr);
1433                 free(s);
1434             }
1435
1436             ofptype_decode(&type, b->data);
1437             ofp_print(stderr, b->data, b->size, verbosity + 2);
1438
1439             switch ((int) type) {
1440             case OFPTYPE_BARRIER_REPLY:
1441                 if (barrier_aux.conn) {
1442                     unixctl_command_reply(barrier_aux.conn, NULL);
1443                     barrier_aux.conn = NULL;
1444                 }
1445                 break;
1446
1447             case OFPTYPE_ECHO_REQUEST:
1448                 if (reply_to_echo_requests) {
1449                     struct ofpbuf *reply;
1450
1451                     reply = make_echo_reply(b->data);
1452                     retval = vconn_send_block(vconn, reply);
1453                     if (retval) {
1454                         ovs_fatal(retval, "failed to send echo reply");
1455                     }
1456                 }
1457                 break;
1458             }
1459             ofpbuf_delete(b);
1460         }
1461
1462         if (exiting) {
1463             break;
1464         }
1465
1466         vconn_run(vconn);
1467         vconn_run_wait(vconn);
1468         if (!blocked) {
1469             vconn_recv_wait(vconn);
1470         }
1471         unixctl_server_wait(server);
1472         poll_block();
1473     }
1474     vconn_close(vconn);
1475     unixctl_server_destroy(server);
1476 }
1477
1478 static void
1479 ofctl_monitor(int argc, char *argv[])
1480 {
1481     struct vconn *vconn;
1482     int i;
1483     enum ofputil_protocol usable_protocols;
1484
1485     open_vconn(argv[1], &vconn);
1486     for (i = 2; i < argc; i++) {
1487         const char *arg = argv[i];
1488
1489         if (isdigit((unsigned char) *arg)) {
1490             struct ofp_switch_config config;
1491
1492             fetch_switch_config(vconn, &config);
1493             config.miss_send_len = htons(atoi(arg));
1494             set_switch_config(vconn, &config);
1495         } else if (!strcmp(arg, "invalid_ttl")) {
1496             monitor_set_invalid_ttl_to_controller(vconn);
1497         } else if (!strncmp(arg, "watch:", 6)) {
1498             struct ofputil_flow_monitor_request fmr;
1499             struct ofpbuf *msg;
1500             char *error;
1501
1502             error = parse_flow_monitor_request(&fmr, arg + 6,
1503                                                &usable_protocols);
1504             if (error) {
1505                 ovs_fatal(0, "%s", error);
1506             }
1507
1508             msg = ofpbuf_new(0);
1509             ofputil_append_flow_monitor_request(&fmr, msg);
1510             dump_stats_transaction(vconn, msg);
1511         } else {
1512             ovs_fatal(0, "%s: unsupported \"monitor\" argument", arg);
1513         }
1514     }
1515
1516     if (preferred_packet_in_format >= 0) {
1517         set_packet_in_format(vconn, preferred_packet_in_format);
1518     } else {
1519         enum ofp_version version = vconn_get_version(vconn);
1520
1521         switch (version) {
1522         case OFP10_VERSION: {
1523             struct ofpbuf *spif, *reply;
1524
1525             spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1526                                                      NXPIF_NXM);
1527             run(vconn_transact_noreply(vconn, spif, &reply),
1528                 "talking to %s", vconn_get_name(vconn));
1529             if (reply) {
1530                 char *s = ofp_to_string(reply->data, reply->size, 2);
1531                 VLOG_DBG("%s: failed to set packet in format to nxm, controller"
1532                         " replied: %s. Falling back to the switch default.",
1533                         vconn_get_name(vconn), s);
1534                 free(s);
1535                 ofpbuf_delete(reply);
1536             }
1537             break;
1538         }
1539         case OFP11_VERSION:
1540         case OFP12_VERSION:
1541         case OFP13_VERSION:
1542             break;
1543         default:
1544             OVS_NOT_REACHED();
1545         }
1546     }
1547
1548     monitor_vconn(vconn, true);
1549 }
1550
1551 static void
1552 ofctl_snoop(int argc OVS_UNUSED, char *argv[])
1553 {
1554     struct vconn *vconn;
1555
1556     open_vconn__(argv[1], SNOOP, &vconn);
1557     monitor_vconn(vconn, false);
1558 }
1559
1560 static void
1561 ofctl_dump_ports(int argc, char *argv[])
1562 {
1563     struct ofpbuf *request;
1564     struct vconn *vconn;
1565     ofp_port_t port;
1566
1567     open_vconn(argv[1], &vconn);
1568     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_ANY;
1569     request = ofputil_encode_dump_ports_request(vconn_get_version(vconn), port);
1570     dump_stats_transaction(vconn, request);
1571     vconn_close(vconn);
1572 }
1573
1574 static void
1575 ofctl_dump_ports_desc(int argc OVS_UNUSED, char *argv[])
1576 {
1577     dump_trivial_stats_transaction(argv[1], OFPRAW_OFPST_PORT_DESC_REQUEST);
1578 }
1579
1580 static void
1581 ofctl_probe(int argc OVS_UNUSED, char *argv[])
1582 {
1583     struct ofpbuf *request;
1584     struct vconn *vconn;
1585     struct ofpbuf *reply;
1586
1587     open_vconn(argv[1], &vconn);
1588     request = make_echo_request(vconn_get_version(vconn));
1589     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1590     if (reply->size != sizeof(struct ofp_header)) {
1591         ovs_fatal(0, "reply does not match request");
1592     }
1593     ofpbuf_delete(reply);
1594     vconn_close(vconn);
1595 }
1596
1597 static void
1598 ofctl_packet_out(int argc, char *argv[])
1599 {
1600     enum ofputil_protocol protocol;
1601     struct ofputil_packet_out po;
1602     struct ofpbuf ofpacts;
1603     struct vconn *vconn;
1604     char *error;
1605     int i;
1606     enum ofputil_protocol usable_protocols; /* XXX: Use in proto selection */
1607
1608     ofpbuf_init(&ofpacts, 64);
1609     error = parse_ofpacts(argv[3], &ofpacts, &usable_protocols);
1610     if (error) {
1611         ovs_fatal(0, "%s", error);
1612     }
1613
1614     po.buffer_id = UINT32_MAX;
1615     po.in_port = str_to_port_no(argv[1], argv[2]);
1616     po.ofpacts = ofpacts.data;
1617     po.ofpacts_len = ofpacts.size;
1618
1619     protocol = open_vconn(argv[1], &vconn);
1620     for (i = 4; i < argc; i++) {
1621         struct ofpbuf *packet, *opo;
1622         const char *error_msg;
1623
1624         error_msg = eth_from_hex(argv[i], &packet);
1625         if (error_msg) {
1626             ovs_fatal(0, "%s", error_msg);
1627         }
1628
1629         po.packet = packet->data;
1630         po.packet_len = packet->size;
1631         opo = ofputil_encode_packet_out(&po, protocol);
1632         transact_noreply(vconn, opo);
1633         ofpbuf_delete(packet);
1634     }
1635     vconn_close(vconn);
1636     ofpbuf_uninit(&ofpacts);
1637 }
1638
1639 static void
1640 ofctl_mod_port(int argc OVS_UNUSED, char *argv[])
1641 {
1642     struct ofp_config_flag {
1643         const char *name;             /* The flag's name. */
1644         enum ofputil_port_config bit; /* Bit to turn on or off. */
1645         bool on;                      /* Value to set the bit to. */
1646     };
1647     static const struct ofp_config_flag flags[] = {
1648         { "up",          OFPUTIL_PC_PORT_DOWN,    false },
1649         { "down",        OFPUTIL_PC_PORT_DOWN,    true  },
1650         { "stp",         OFPUTIL_PC_NO_STP,       false },
1651         { "receive",     OFPUTIL_PC_NO_RECV,      false },
1652         { "receive-stp", OFPUTIL_PC_NO_RECV_STP,  false },
1653         { "flood",       OFPUTIL_PC_NO_FLOOD,     false },
1654         { "forward",     OFPUTIL_PC_NO_FWD,       false },
1655         { "packet-in",   OFPUTIL_PC_NO_PACKET_IN, false },
1656     };
1657
1658     const struct ofp_config_flag *flag;
1659     enum ofputil_protocol protocol;
1660     struct ofputil_port_mod pm;
1661     struct ofputil_phy_port pp;
1662     struct vconn *vconn;
1663     const char *command;
1664     bool not;
1665
1666     fetch_ofputil_phy_port(argv[1], argv[2], &pp);
1667
1668     pm.port_no = pp.port_no;
1669     memcpy(pm.hw_addr, pp.hw_addr, ETH_ADDR_LEN);
1670     pm.config = 0;
1671     pm.mask = 0;
1672     pm.advertise = 0;
1673
1674     if (!strncasecmp(argv[3], "no-", 3)) {
1675         command = argv[3] + 3;
1676         not = true;
1677     } else if (!strncasecmp(argv[3], "no", 2)) {
1678         command = argv[3] + 2;
1679         not = true;
1680     } else {
1681         command = argv[3];
1682         not = false;
1683     }
1684     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1685         if (!strcasecmp(command, flag->name)) {
1686             pm.mask = flag->bit;
1687             pm.config = flag->on ^ not ? flag->bit : 0;
1688             goto found;
1689         }
1690     }
1691     ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1692
1693 found:
1694     protocol = open_vconn(argv[1], &vconn);
1695     transact_noreply(vconn, ofputil_encode_port_mod(&pm, protocol));
1696     vconn_close(vconn);
1697 }
1698
1699 static void
1700 ofctl_mod_table(int argc OVS_UNUSED, char *argv[])
1701 {
1702     enum ofputil_protocol protocol, usable_protocols;
1703     struct ofputil_table_mod tm;
1704     struct vconn *vconn;
1705     char *error;
1706     int i;
1707
1708     error = parse_ofp_table_mod(&tm, argv[2], argv[3], &usable_protocols);
1709     if (error) {
1710         ovs_fatal(0, "%s", error);
1711     }
1712
1713     protocol = open_vconn(argv[1], &vconn);
1714     if (!(protocol & usable_protocols)) {
1715         for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1716             enum ofputil_protocol f = 1 << i;
1717             if (f != protocol
1718                 && f & usable_protocols
1719                 && try_set_protocol(vconn, f, &protocol)) {
1720                 protocol = f;
1721                 break;
1722             }
1723         }
1724     }
1725
1726     if (!(protocol & usable_protocols)) {
1727         char *usable_s = ofputil_protocols_to_string(usable_protocols);
1728         ovs_fatal(0, "Switch does not support table mod message(%s)", usable_s);
1729     }
1730
1731     transact_noreply(vconn, ofputil_encode_table_mod(&tm, protocol));
1732     vconn_close(vconn);
1733 }
1734
1735 static void
1736 ofctl_get_frags(int argc OVS_UNUSED, char *argv[])
1737 {
1738     struct ofp_switch_config config;
1739     struct vconn *vconn;
1740
1741     open_vconn(argv[1], &vconn);
1742     fetch_switch_config(vconn, &config);
1743     puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
1744     vconn_close(vconn);
1745 }
1746
1747 static void
1748 ofctl_set_frags(int argc OVS_UNUSED, char *argv[])
1749 {
1750     struct ofp_switch_config config;
1751     enum ofp_config_flags mode;
1752     struct vconn *vconn;
1753     ovs_be16 flags;
1754
1755     if (!ofputil_frag_handling_from_string(argv[2], &mode)) {
1756         ovs_fatal(0, "%s: unknown fragment handling mode", argv[2]);
1757     }
1758
1759     open_vconn(argv[1], &vconn);
1760     fetch_switch_config(vconn, &config);
1761     flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
1762     if (flags != config.flags) {
1763         /* Set the configuration. */
1764         config.flags = flags;
1765         set_switch_config(vconn, &config);
1766
1767         /* Then retrieve the configuration to see if it really took.  OpenFlow
1768          * doesn't define error reporting for bad modes, so this is all we can
1769          * do. */
1770         fetch_switch_config(vconn, &config);
1771         if (flags != config.flags) {
1772             ovs_fatal(0, "%s: setting fragment handling mode failed (this "
1773                       "switch probably doesn't support mode \"%s\")",
1774                       argv[1], ofputil_frag_handling_to_string(mode));
1775         }
1776     }
1777     vconn_close(vconn);
1778 }
1779
1780 static void
1781 ofctl_ofp_parse(int argc OVS_UNUSED, char *argv[])
1782 {
1783     const char *filename = argv[1];
1784     struct ofpbuf b;
1785     FILE *file;
1786
1787     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
1788     if (file == NULL) {
1789         ovs_fatal(errno, "%s: open", filename);
1790     }
1791
1792     ofpbuf_init(&b, 65536);
1793     for (;;) {
1794         struct ofp_header *oh;
1795         size_t length, tail_len;
1796         void *tail;
1797         size_t n;
1798
1799         ofpbuf_clear(&b);
1800         oh = ofpbuf_put_uninit(&b, sizeof *oh);
1801         n = fread(oh, 1, sizeof *oh, file);
1802         if (n == 0) {
1803             break;
1804         } else if (n < sizeof *oh) {
1805             ovs_fatal(0, "%s: unexpected end of file mid-message", filename);
1806         }
1807
1808         length = ntohs(oh->length);
1809         if (length < sizeof *oh) {
1810             ovs_fatal(0, "%s: %"PRIuSIZE"-byte message is too short for OpenFlow",
1811                       filename, length);
1812         }
1813
1814         tail_len = length - sizeof *oh;
1815         tail = ofpbuf_put_uninit(&b, tail_len);
1816         n = fread(tail, 1, tail_len, file);
1817         if (n < tail_len) {
1818             ovs_fatal(0, "%s: unexpected end of file mid-message", filename);
1819         }
1820
1821         ofp_print(stdout, b.data, b.size, verbosity + 2);
1822     }
1823     ofpbuf_uninit(&b);
1824
1825     if (file != stdin) {
1826         fclose(file);
1827     }
1828 }
1829
1830 static bool
1831 is_openflow_port(ovs_be16 port_, char *ports[])
1832 {
1833     uint16_t port = ntohs(port_);
1834     if (ports[0]) {
1835         int i;
1836
1837         for (i = 0; ports[i]; i++) {
1838             if (port == atoi(ports[i])) {
1839                 return true;
1840             }
1841         }
1842         return false;
1843     } else {
1844         return port == OFP_PORT || port == OFP_OLD_PORT;
1845     }
1846 }
1847
1848 static void
1849 ofctl_ofp_parse_pcap(int argc OVS_UNUSED, char *argv[])
1850 {
1851     struct tcp_reader *reader;
1852     FILE *file;
1853     int error;
1854     bool first;
1855
1856     file = ovs_pcap_open(argv[1], "rb");
1857     if (!file) {
1858         ovs_fatal(errno, "%s: open failed", argv[1]);
1859     }
1860
1861     reader = tcp_reader_open();
1862     first = true;
1863     for (;;) {
1864         struct ofpbuf *packet;
1865         long long int when;
1866         struct flow flow;
1867
1868         error = ovs_pcap_read(file, &packet, &when);
1869         if (error) {
1870             break;
1871         }
1872         flow_extract(packet, 0, 0, NULL, NULL, &flow);
1873         if (flow.dl_type == htons(ETH_TYPE_IP)
1874             && flow.nw_proto == IPPROTO_TCP
1875             && (is_openflow_port(flow.tp_src, argv + 2) ||
1876                 is_openflow_port(flow.tp_dst, argv + 2))) {
1877             struct ofpbuf *payload = tcp_reader_run(reader, &flow, packet);
1878             if (payload) {
1879                 while (payload->size >= sizeof(struct ofp_header)) {
1880                     const struct ofp_header *oh;
1881                     int length;
1882
1883                     /* Align OpenFlow on 8-byte boundary for safe access. */
1884                     ofpbuf_shift(payload, -((intptr_t) payload->data & 7));
1885
1886                     oh = payload->data;
1887                     length = ntohs(oh->length);
1888                     if (payload->size < length) {
1889                         break;
1890                     }
1891
1892                     if (!first) {
1893                         putchar('\n');
1894                     }
1895                     first = false;
1896
1897                     if (timestamp) {
1898                         char *s = xastrftime_msec("%H:%M:%S.### ", when, true);
1899                         fputs(s, stdout);
1900                         free(s);
1901                     }
1902
1903                     printf(IP_FMT".%"PRIu16" > "IP_FMT".%"PRIu16":\n",
1904                            IP_ARGS(flow.nw_src), ntohs(flow.tp_src),
1905                            IP_ARGS(flow.nw_dst), ntohs(flow.tp_dst));
1906                     ofp_print(stdout, payload->data, length, verbosity + 1);
1907                     ofpbuf_pull(payload, length);
1908                 }
1909             }
1910         }
1911         ofpbuf_delete(packet);
1912     }
1913     tcp_reader_close(reader);
1914 }
1915
1916 static void
1917 ofctl_ping(int argc, char *argv[])
1918 {
1919     size_t max_payload = 65535 - sizeof(struct ofp_header);
1920     unsigned int payload;
1921     struct vconn *vconn;
1922     int i;
1923
1924     payload = argc > 2 ? atoi(argv[2]) : 64;
1925     if (payload > max_payload) {
1926         ovs_fatal(0, "payload must be between 0 and %"PRIuSIZE" bytes", max_payload);
1927     }
1928
1929     open_vconn(argv[1], &vconn);
1930     for (i = 0; i < 10; i++) {
1931         struct timeval start, end;
1932         struct ofpbuf *request, *reply;
1933         const struct ofp_header *rpy_hdr;
1934         enum ofptype type;
1935
1936         request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
1937                                vconn_get_version(vconn), payload);
1938         random_bytes(ofpbuf_put_uninit(request, payload), payload);
1939
1940         xgettimeofday(&start);
1941         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1942         xgettimeofday(&end);
1943
1944         rpy_hdr = reply->data;
1945         if (ofptype_pull(&type, reply)
1946             || type != OFPTYPE_ECHO_REPLY
1947             || reply->size != payload
1948             || memcmp(request->l3, reply->l3, payload)) {
1949             printf("Reply does not match request.  Request:\n");
1950             ofp_print(stdout, request, request->size, verbosity + 2);
1951             printf("Reply:\n");
1952             ofp_print(stdout, reply, reply->size, verbosity + 2);
1953         }
1954         printf("%"PRIuSIZE" bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1955                reply->size, argv[1], ntohl(rpy_hdr->xid),
1956                    (1000*(double)(end.tv_sec - start.tv_sec))
1957                    + (.001*(end.tv_usec - start.tv_usec)));
1958         ofpbuf_delete(request);
1959         ofpbuf_delete(reply);
1960     }
1961     vconn_close(vconn);
1962 }
1963
1964 static void
1965 ofctl_benchmark(int argc OVS_UNUSED, char *argv[])
1966 {
1967     size_t max_payload = 65535 - sizeof(struct ofp_header);
1968     struct timeval start, end;
1969     unsigned int payload_size, message_size;
1970     struct vconn *vconn;
1971     double duration;
1972     int count;
1973     int i;
1974
1975     payload_size = atoi(argv[2]);
1976     if (payload_size > max_payload) {
1977         ovs_fatal(0, "payload must be between 0 and %"PRIuSIZE" bytes", max_payload);
1978     }
1979     message_size = sizeof(struct ofp_header) + payload_size;
1980
1981     count = atoi(argv[3]);
1982
1983     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1984            count, message_size, count * message_size);
1985
1986     open_vconn(argv[1], &vconn);
1987     xgettimeofday(&start);
1988     for (i = 0; i < count; i++) {
1989         struct ofpbuf *request, *reply;
1990
1991         request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
1992                                vconn_get_version(vconn), payload_size);
1993         ofpbuf_put_zeros(request, payload_size);
1994         run(vconn_transact(vconn, request, &reply), "transact");
1995         ofpbuf_delete(reply);
1996     }
1997     xgettimeofday(&end);
1998     vconn_close(vconn);
1999
2000     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
2001                 + (.001*(end.tv_usec - start.tv_usec)));
2002     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
2003            duration, count / (duration / 1000.0),
2004            count * message_size / (duration / 1000.0));
2005 }
2006
2007 static void
2008 ofctl_group_mod__(const char *remote, struct ofputil_group_mod *gms,
2009                  size_t n_gms)
2010 {
2011     struct ofputil_group_mod *gm;
2012     struct ofpbuf *request;
2013
2014     struct vconn *vconn;
2015     size_t i;
2016
2017     open_vconn(remote, &vconn);
2018
2019     for (i = 0; i < n_gms; i++) {
2020         gm = &gms[i];
2021         request = ofputil_encode_group_mod(vconn_get_version(vconn), gm);
2022         if (request) {
2023             transact_noreply(vconn, request);
2024         }
2025     }
2026
2027     vconn_close(vconn);
2028
2029 }
2030
2031
2032 static void
2033 ofctl_group_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
2034 {
2035     struct ofputil_group_mod *gms = NULL;
2036     enum ofputil_protocol usable_protocols;
2037     size_t n_gms = 0;
2038     char *error;
2039
2040     error = parse_ofp_group_mod_file(argv[2], command, &gms, &n_gms,
2041                                      &usable_protocols);
2042     if (error) {
2043         ovs_fatal(0, "%s", error);
2044     }
2045     ofctl_group_mod__(argv[1], gms, n_gms);
2046     free(gms);
2047 }
2048
2049 static void
2050 ofctl_group_mod(int argc, char *argv[], uint16_t command)
2051 {
2052     if (argc > 2 && !strcmp(argv[2], "-")) {
2053         ofctl_group_mod_file(argc, argv, command);
2054     } else {
2055         enum ofputil_protocol usable_protocols;
2056         struct ofputil_group_mod gm;
2057         char *error;
2058
2059         error = parse_ofp_group_mod_str(&gm, command, argc > 2 ? argv[2] : "",
2060                                         &usable_protocols);
2061         if (error) {
2062             ovs_fatal(0, "%s", error);
2063         }
2064         ofctl_group_mod__(argv[1], &gm, 1);
2065     }
2066 }
2067
2068 static void
2069 ofctl_add_group(int argc, char *argv[])
2070 {
2071     ofctl_group_mod(argc, argv, OFPGC11_ADD);
2072 }
2073
2074 static void
2075 ofctl_add_groups(int argc, char *argv[])
2076 {
2077     ofctl_group_mod_file(argc, argv, OFPGC11_ADD);
2078 }
2079
2080 static void
2081 ofctl_mod_group(int argc, char *argv[])
2082 {
2083     ofctl_group_mod(argc, argv, OFPGC11_MODIFY);
2084 }
2085
2086 static void
2087 ofctl_del_groups(int argc, char *argv[])
2088 {
2089     ofctl_group_mod(argc, argv, OFPGC11_DELETE);
2090 }
2091
2092 static void
2093 ofctl_dump_group_stats(int argc, char *argv[])
2094 {
2095     enum ofputil_protocol usable_protocols;
2096     struct ofputil_group_mod gm;
2097     struct ofpbuf *request;
2098     struct vconn *vconn;
2099     uint32_t group_id;
2100     char *error;
2101
2102     memset(&gm, 0, sizeof gm);
2103
2104     error = parse_ofp_group_mod_str(&gm, OFPGC11_DELETE,
2105                                     argc > 2 ? argv[2] : "",
2106                                     &usable_protocols);
2107     if (error) {
2108         ovs_fatal(0, "%s", error);
2109     }
2110
2111     group_id = gm.group_id;
2112
2113     open_vconn(argv[1], &vconn);
2114     request = ofputil_encode_group_stats_request(vconn_get_version(vconn),
2115                                                  group_id);
2116     if (request) {
2117         dump_stats_transaction(vconn, request);
2118     }
2119
2120     vconn_close(vconn);
2121 }
2122
2123 static void
2124 ofctl_dump_group_desc(int argc OVS_UNUSED, char *argv[])
2125 {
2126     struct ofpbuf *request;
2127     struct vconn *vconn;
2128
2129     open_vconn(argv[1], &vconn);
2130
2131     request = ofputil_encode_group_desc_request(vconn_get_version(vconn));
2132     if (request) {
2133         dump_stats_transaction(vconn, request);
2134     }
2135
2136     vconn_close(vconn);
2137 }
2138
2139 static void
2140 ofctl_dump_group_features(int argc OVS_UNUSED, char *argv[])
2141 {
2142     struct ofpbuf *request;
2143     struct vconn *vconn;
2144
2145     open_vconn(argv[1], &vconn);
2146     request = ofputil_encode_group_features_request(vconn_get_version(vconn));
2147     if (request) {
2148         dump_stats_transaction(vconn, request);
2149     }
2150
2151     vconn_close(vconn);
2152 }
2153
2154 static void
2155 ofctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2156 {
2157     usage();
2158 }
2159 \f
2160 /* replace-flows and diff-flows commands. */
2161
2162 /* A flow table entry, possibly with two different versions. */
2163 struct fte {
2164     struct cls_rule rule;       /* Within a "struct classifier". */
2165     struct fte_version *versions[2];
2166 };
2167
2168 /* One version of a Flow Table Entry. */
2169 struct fte_version {
2170     ovs_be64 cookie;
2171     uint16_t idle_timeout;
2172     uint16_t hard_timeout;
2173     uint16_t flags;
2174     struct ofpact *ofpacts;
2175     size_t ofpacts_len;
2176 };
2177
2178 /* Frees 'version' and the data that it owns. */
2179 static void
2180 fte_version_free(struct fte_version *version)
2181 {
2182     if (version) {
2183         free(version->ofpacts);
2184         free(version);
2185     }
2186 }
2187
2188 /* Returns true if 'a' and 'b' are the same, false if they differ.
2189  *
2190  * Ignores differences in 'flags' because there's no way to retrieve flags from
2191  * an OpenFlow switch.  We have to assume that they are the same. */
2192 static bool
2193 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
2194 {
2195     return (a->cookie == b->cookie
2196             && a->idle_timeout == b->idle_timeout
2197             && a->hard_timeout == b->hard_timeout
2198             && ofpacts_equal(a->ofpacts, a->ofpacts_len,
2199                              b->ofpacts, b->ofpacts_len));
2200 }
2201
2202 /* Clears 's', then if 's' has a version 'index', formats 'fte' and version
2203  * 'index' into 's', followed by a new-line. */
2204 static void
2205 fte_version_format(const struct fte *fte, int index, struct ds *s)
2206 {
2207     const struct fte_version *version = fte->versions[index];
2208
2209     ds_clear(s);
2210     if (!version) {
2211         return;
2212     }
2213
2214     cls_rule_format(&fte->rule, s);
2215     if (version->cookie != htonll(0)) {
2216         ds_put_format(s, " cookie=0x%"PRIx64, ntohll(version->cookie));
2217     }
2218     if (version->idle_timeout != OFP_FLOW_PERMANENT) {
2219         ds_put_format(s, " idle_timeout=%"PRIu16, version->idle_timeout);
2220     }
2221     if (version->hard_timeout != OFP_FLOW_PERMANENT) {
2222         ds_put_format(s, " hard_timeout=%"PRIu16, version->hard_timeout);
2223     }
2224
2225     ds_put_cstr(s, " actions=");
2226     ofpacts_format(version->ofpacts, version->ofpacts_len, s);
2227
2228     ds_put_char(s, '\n');
2229 }
2230
2231 static struct fte *
2232 fte_from_cls_rule(const struct cls_rule *cls_rule)
2233 {
2234     return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
2235 }
2236
2237 /* Frees 'fte' and its versions. */
2238 static void
2239 fte_free(struct fte *fte)
2240 {
2241     if (fte) {
2242         fte_version_free(fte->versions[0]);
2243         fte_version_free(fte->versions[1]);
2244         cls_rule_destroy(&fte->rule);
2245         free(fte);
2246     }
2247 }
2248
2249 /* Frees all of the FTEs within 'cls'. */
2250 static void
2251 fte_free_all(struct classifier *cls)
2252 {
2253     struct cls_cursor cursor;
2254     struct fte *fte, *next;
2255
2256     fat_rwlock_wrlock(&cls->rwlock);
2257     cls_cursor_init(&cursor, cls, NULL);
2258     CLS_CURSOR_FOR_EACH_SAFE (fte, next, rule, &cursor) {
2259         classifier_remove(cls, &fte->rule);
2260         fte_free(fte);
2261     }
2262     fat_rwlock_unlock(&cls->rwlock);
2263     classifier_destroy(cls);
2264 }
2265
2266 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
2267  * necessary.  Sets 'version' as the version of that rule with the given
2268  * 'index', replacing any existing version, if any.
2269  *
2270  * Takes ownership of 'version'. */
2271 static void
2272 fte_insert(struct classifier *cls, const struct match *match,
2273            unsigned int priority, struct fte_version *version, int index)
2274 {
2275     struct fte *old, *fte;
2276
2277     fte = xzalloc(sizeof *fte);
2278     cls_rule_init(&fte->rule, match, priority);
2279     fte->versions[index] = version;
2280
2281     fat_rwlock_wrlock(&cls->rwlock);
2282     old = fte_from_cls_rule(classifier_replace(cls, &fte->rule));
2283     fat_rwlock_unlock(&cls->rwlock);
2284     if (old) {
2285         fte_version_free(old->versions[index]);
2286         fte->versions[!index] = old->versions[!index];
2287         cls_rule_destroy(&old->rule);
2288         free(old);
2289     }
2290 }
2291
2292 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
2293  * with the specified 'index'.  Returns the flow formats able to represent the
2294  * flows that were read. */
2295 static enum ofputil_protocol
2296 read_flows_from_file(const char *filename, struct classifier *cls, int index)
2297 {
2298     enum ofputil_protocol usable_protocols;
2299     int line_number;
2300     struct ds s;
2301     FILE *file;
2302
2303     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
2304     if (file == NULL) {
2305         ovs_fatal(errno, "%s: open", filename);
2306     }
2307
2308     ds_init(&s);
2309     usable_protocols = OFPUTIL_P_ANY;
2310     line_number = 0;
2311     while (!ds_get_preprocessed_line(&s, file, &line_number)) {
2312         struct fte_version *version;
2313         struct ofputil_flow_mod fm;
2314         char *error;
2315         enum ofputil_protocol usable;
2316
2317         error = parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), &usable);
2318         if (error) {
2319             ovs_fatal(0, "%s:%d: %s", filename, line_number, error);
2320         }
2321         usable_protocols &= usable;
2322
2323         version = xmalloc(sizeof *version);
2324         version->cookie = fm.new_cookie;
2325         version->idle_timeout = fm.idle_timeout;
2326         version->hard_timeout = fm.hard_timeout;
2327         version->flags = fm.flags & (OFPUTIL_FF_SEND_FLOW_REM
2328                                      | OFPUTIL_FF_EMERG);
2329         version->ofpacts = fm.ofpacts;
2330         version->ofpacts_len = fm.ofpacts_len;
2331
2332         fte_insert(cls, &fm.match, fm.priority, version, index);
2333     }
2334     ds_destroy(&s);
2335
2336     if (file != stdin) {
2337         fclose(file);
2338     }
2339
2340     return usable_protocols;
2341 }
2342
2343 static bool
2344 recv_flow_stats_reply(struct vconn *vconn, ovs_be32 send_xid,
2345                       struct ofpbuf **replyp,
2346                       struct ofputil_flow_stats *fs, struct ofpbuf *ofpacts)
2347 {
2348     struct ofpbuf *reply = *replyp;
2349
2350     for (;;) {
2351         int retval;
2352         bool more;
2353
2354         /* Get a flow stats reply message, if we don't already have one. */
2355         if (!reply) {
2356             enum ofptype type;
2357             enum ofperr error;
2358
2359             do {
2360                 run(vconn_recv_block(vconn, &reply),
2361                     "OpenFlow packet receive failed");
2362             } while (((struct ofp_header *) reply->data)->xid != send_xid);
2363
2364             error = ofptype_decode(&type, reply->data);
2365             if (error || type != OFPTYPE_FLOW_STATS_REPLY) {
2366                 ovs_fatal(0, "received bad reply: %s",
2367                           ofp_to_string(reply->data, reply->size,
2368                                         verbosity + 1));
2369             }
2370         }
2371
2372         /* Pull an individual flow stats reply out of the message. */
2373         retval = ofputil_decode_flow_stats_reply(fs, reply, false, ofpacts);
2374         switch (retval) {
2375         case 0:
2376             *replyp = reply;
2377             return true;
2378
2379         case EOF:
2380             more = ofpmp_more(reply->l2);
2381             ofpbuf_delete(reply);
2382             reply = NULL;
2383             if (!more) {
2384                 *replyp = NULL;
2385                 return false;
2386             }
2387             break;
2388
2389         default:
2390             ovs_fatal(0, "parse error in reply (%s)",
2391                       ofperr_to_string(retval));
2392         }
2393     }
2394 }
2395
2396 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
2397  * format 'protocol', and adds them as flow table entries in 'cls' for the
2398  * version with the specified 'index'. */
2399 static void
2400 read_flows_from_switch(struct vconn *vconn,
2401                        enum ofputil_protocol protocol,
2402                        struct classifier *cls, int index)
2403 {
2404     struct ofputil_flow_stats_request fsr;
2405     struct ofputil_flow_stats fs;
2406     struct ofpbuf *request;
2407     struct ofpbuf ofpacts;
2408     struct ofpbuf *reply;
2409     ovs_be32 send_xid;
2410
2411     fsr.aggregate = false;
2412     match_init_catchall(&fsr.match);
2413     fsr.out_port = OFPP_ANY;
2414     fsr.table_id = 0xff;
2415     fsr.cookie = fsr.cookie_mask = htonll(0);
2416     request = ofputil_encode_flow_stats_request(&fsr, protocol);
2417     send_xid = ((struct ofp_header *) request->data)->xid;
2418     send_openflow_buffer(vconn, request);
2419
2420     reply = NULL;
2421     ofpbuf_init(&ofpacts, 0);
2422     while (recv_flow_stats_reply(vconn, send_xid, &reply, &fs, &ofpacts)) {
2423         struct fte_version *version;
2424
2425         version = xmalloc(sizeof *version);
2426         version->cookie = fs.cookie;
2427         version->idle_timeout = fs.idle_timeout;
2428         version->hard_timeout = fs.hard_timeout;
2429         version->flags = 0;
2430         version->ofpacts_len = fs.ofpacts_len;
2431         version->ofpacts = xmemdup(fs.ofpacts, fs.ofpacts_len);
2432
2433         fte_insert(cls, &fs.match, fs.priority, version, index);
2434     }
2435     ofpbuf_uninit(&ofpacts);
2436 }
2437
2438 static void
2439 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
2440                   enum ofputil_protocol protocol, struct list *packets)
2441 {
2442     const struct fte_version *version = fte->versions[index];
2443     struct ofputil_flow_mod fm;
2444     struct ofpbuf *ofm;
2445
2446     minimatch_expand(&fte->rule.match, &fm.match);
2447     fm.priority = fte->rule.priority;
2448     fm.cookie = htonll(0);
2449     fm.cookie_mask = htonll(0);
2450     fm.new_cookie = version->cookie;
2451     fm.modify_cookie = true;
2452     fm.table_id = 0xff;
2453     fm.command = command;
2454     fm.idle_timeout = version->idle_timeout;
2455     fm.hard_timeout = version->hard_timeout;
2456     fm.buffer_id = UINT32_MAX;
2457     fm.out_port = OFPP_ANY;
2458     fm.flags = version->flags;
2459     if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
2460         command == OFPFC_MODIFY_STRICT) {
2461         fm.ofpacts = version->ofpacts;
2462         fm.ofpacts_len = version->ofpacts_len;
2463     } else {
2464         fm.ofpacts = NULL;
2465         fm.ofpacts_len = 0;
2466     }
2467
2468     ofm = ofputil_encode_flow_mod(&fm, protocol);
2469     list_push_back(packets, &ofm->list_node);
2470 }
2471
2472 static void
2473 ofctl_replace_flows(int argc OVS_UNUSED, char *argv[])
2474 {
2475     enum { FILE_IDX = 0, SWITCH_IDX = 1 };
2476     enum ofputil_protocol usable_protocols, protocol;
2477     struct cls_cursor cursor;
2478     struct classifier cls;
2479     struct list requests;
2480     struct vconn *vconn;
2481     struct fte *fte;
2482
2483     classifier_init(&cls, NULL);
2484     usable_protocols = read_flows_from_file(argv[2], &cls, FILE_IDX);
2485
2486     protocol = open_vconn(argv[1], &vconn);
2487     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
2488
2489     read_flows_from_switch(vconn, protocol, &cls, SWITCH_IDX);
2490
2491     list_init(&requests);
2492
2493     /* Delete flows that exist on the switch but not in the file. */
2494     fat_rwlock_rdlock(&cls.rwlock);
2495     cls_cursor_init(&cursor, &cls, NULL);
2496     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
2497         struct fte_version *file_ver = fte->versions[FILE_IDX];
2498         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
2499
2500         if (sw_ver && !file_ver) {
2501             fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
2502                               protocol, &requests);
2503         }
2504     }
2505
2506     /* Add flows that exist in the file but not on the switch.
2507      * Update flows that exist in both places but differ. */
2508     cls_cursor_init(&cursor, &cls, NULL);
2509     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
2510         struct fte_version *file_ver = fte->versions[FILE_IDX];
2511         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
2512
2513         if (file_ver
2514             && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
2515             fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, protocol, &requests);
2516         }
2517     }
2518     fat_rwlock_unlock(&cls.rwlock);
2519     transact_multiple_noreply(vconn, &requests);
2520     vconn_close(vconn);
2521
2522     fte_free_all(&cls);
2523 }
2524
2525 static void
2526 read_flows_from_source(const char *source, struct classifier *cls, int index)
2527 {
2528     struct stat s;
2529
2530     if (source[0] == '/' || source[0] == '.'
2531         || (!strchr(source, ':') && !stat(source, &s))) {
2532         read_flows_from_file(source, cls, index);
2533     } else {
2534         enum ofputil_protocol protocol;
2535         struct vconn *vconn;
2536
2537         protocol = open_vconn(source, &vconn);
2538         protocol = set_protocol_for_flow_dump(vconn, protocol, OFPUTIL_P_ANY);
2539         read_flows_from_switch(vconn, protocol, cls, index);
2540         vconn_close(vconn);
2541     }
2542 }
2543
2544 static void
2545 ofctl_diff_flows(int argc OVS_UNUSED, char *argv[])
2546 {
2547     bool differences = false;
2548     struct cls_cursor cursor;
2549     struct classifier cls;
2550     struct ds a_s, b_s;
2551     struct fte *fte;
2552
2553     classifier_init(&cls, NULL);
2554     read_flows_from_source(argv[1], &cls, 0);
2555     read_flows_from_source(argv[2], &cls, 1);
2556
2557     ds_init(&a_s);
2558     ds_init(&b_s);
2559
2560     fat_rwlock_rdlock(&cls.rwlock);
2561     cls_cursor_init(&cursor, &cls, NULL);
2562     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
2563         struct fte_version *a = fte->versions[0];
2564         struct fte_version *b = fte->versions[1];
2565
2566         if (!a || !b || !fte_version_equals(a, b)) {
2567             fte_version_format(fte, 0, &a_s);
2568             fte_version_format(fte, 1, &b_s);
2569             if (strcmp(ds_cstr(&a_s), ds_cstr(&b_s))) {
2570                 if (a_s.length) {
2571                     printf("-%s", ds_cstr(&a_s));
2572                 }
2573                 if (b_s.length) {
2574                     printf("+%s", ds_cstr(&b_s));
2575                 }
2576                 differences = true;
2577             }
2578         }
2579     }
2580     fat_rwlock_unlock(&cls.rwlock);
2581
2582     ds_destroy(&a_s);
2583     ds_destroy(&b_s);
2584
2585     fte_free_all(&cls);
2586
2587     if (differences) {
2588         exit(2);
2589     }
2590 }
2591
2592 static void
2593 ofctl_meter_mod__(const char *bridge, const char *str, int command)
2594 {
2595     struct ofputil_meter_mod mm;
2596     struct vconn *vconn;
2597     enum ofputil_protocol protocol;
2598     enum ofputil_protocol usable_protocols;
2599     enum ofp_version version;
2600
2601     if (str) {
2602         char *error;
2603         error = parse_ofp_meter_mod_str(&mm, str, command, &usable_protocols);
2604         if (error) {
2605             ovs_fatal(0, "%s", error);
2606         }
2607     } else {
2608         usable_protocols = OFPUTIL_P_OF13_UP;
2609         mm.command = command;
2610         mm.meter.meter_id = OFPM13_ALL;
2611     }
2612
2613     protocol = open_vconn_for_flow_mod(bridge, &vconn, usable_protocols);
2614     version = ofputil_protocol_to_ofp_version(protocol);
2615     transact_noreply(vconn, ofputil_encode_meter_mod(version, &mm));
2616     vconn_close(vconn);
2617 }
2618
2619 static void
2620 ofctl_meter_request__(const char *bridge, const char *str,
2621                       enum ofputil_meter_request_type type)
2622 {
2623     struct ofputil_meter_mod mm;
2624     struct vconn *vconn;
2625     enum ofputil_protocol usable_protocols;
2626     enum ofputil_protocol protocol;
2627     enum ofp_version version;
2628
2629     if (str) {
2630         char *error;
2631         error = parse_ofp_meter_mod_str(&mm, str, -1, &usable_protocols);
2632         if (error) {
2633             ovs_fatal(0, "%s", error);
2634         }
2635     } else {
2636         usable_protocols = OFPUTIL_P_OF13_UP;
2637         mm.meter.meter_id = OFPM13_ALL;
2638     }
2639
2640     protocol = open_vconn_for_flow_mod(bridge, &vconn, usable_protocols);
2641     version = ofputil_protocol_to_ofp_version(protocol);
2642     transact_noreply(vconn, ofputil_encode_meter_request(version,
2643                                                          type,
2644                                                          mm.meter.meter_id));
2645     vconn_close(vconn);
2646 }
2647
2648
2649 static void
2650 ofctl_add_meter(int argc OVS_UNUSED, char *argv[])
2651 {
2652     ofctl_meter_mod__(argv[1], argv[2], OFPMC13_ADD);
2653 }
2654
2655 static void
2656 ofctl_mod_meter(int argc OVS_UNUSED, char *argv[])
2657 {
2658     ofctl_meter_mod__(argv[1], argv[2], OFPMC13_MODIFY);
2659 }
2660
2661 static void
2662 ofctl_del_meters(int argc, char *argv[])
2663 {
2664     ofctl_meter_mod__(argv[1], argc > 2 ? argv[2] : NULL, OFPMC13_DELETE);
2665 }
2666
2667 static void
2668 ofctl_dump_meters(int argc, char *argv[])
2669 {
2670     ofctl_meter_request__(argv[1], argc > 2 ? argv[2] : NULL,
2671                           OFPUTIL_METER_CONFIG);
2672 }
2673
2674 static void
2675 ofctl_meter_stats(int argc, char *argv[])
2676 {
2677     ofctl_meter_request__(argv[1], argc > 2 ? argv[2] : NULL,
2678                           OFPUTIL_METER_STATS);
2679 }
2680
2681 static void
2682 ofctl_meter_features(int argc OVS_UNUSED, char *argv[])
2683 {
2684     ofctl_meter_request__(argv[1], NULL, OFPUTIL_METER_FEATURES);
2685 }
2686
2687 \f
2688 /* Undocumented commands for unit testing. */
2689
2690 static void
2691 ofctl_parse_flows__(struct ofputil_flow_mod *fms, size_t n_fms,
2692                     enum ofputil_protocol usable_protocols)
2693 {
2694     enum ofputil_protocol protocol = 0;
2695     char *usable_s;
2696     size_t i;
2697
2698     usable_s = ofputil_protocols_to_string(usable_protocols);
2699     printf("usable protocols: %s\n", usable_s);
2700     free(usable_s);
2701
2702     if (!(usable_protocols & allowed_protocols)) {
2703         ovs_fatal(0, "no usable protocol");
2704     }
2705     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
2706         protocol = 1 << i;
2707         if (protocol & usable_protocols & allowed_protocols) {
2708             break;
2709         }
2710     }
2711     ovs_assert(is_pow2(protocol));
2712
2713     printf("chosen protocol: %s\n", ofputil_protocol_to_string(protocol));
2714
2715     for (i = 0; i < n_fms; i++) {
2716         struct ofputil_flow_mod *fm = &fms[i];
2717         struct ofpbuf *msg;
2718
2719         msg = ofputil_encode_flow_mod(fm, protocol);
2720         ofp_print(stdout, msg->data, msg->size, verbosity);
2721         ofpbuf_delete(msg);
2722
2723         free(fm->ofpacts);
2724     }
2725 }
2726
2727 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
2728  * it back to stdout.  */
2729 static void
2730 ofctl_parse_flow(int argc OVS_UNUSED, char *argv[])
2731 {
2732     enum ofputil_protocol usable_protocols;
2733     struct ofputil_flow_mod fm;
2734     char *error;
2735
2736     error = parse_ofp_flow_mod_str(&fm, argv[1], OFPFC_ADD, &usable_protocols);
2737     if (error) {
2738         ovs_fatal(0, "%s", error);
2739     }
2740     ofctl_parse_flows__(&fm, 1, usable_protocols);
2741 }
2742
2743 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
2744  * add-flows) and prints each of the flows back to stdout.  */
2745 static void
2746 ofctl_parse_flows(int argc OVS_UNUSED, char *argv[])
2747 {
2748     enum ofputil_protocol usable_protocols;
2749     struct ofputil_flow_mod *fms = NULL;
2750     size_t n_fms = 0;
2751     char *error;
2752
2753     error = parse_ofp_flow_mod_file(argv[1], OFPFC_ADD, &fms, &n_fms,
2754                                     &usable_protocols);
2755     if (error) {
2756         ovs_fatal(0, "%s", error);
2757     }
2758     ofctl_parse_flows__(fms, n_fms, usable_protocols);
2759     free(fms);
2760 }
2761
2762 static void
2763 ofctl_parse_nxm__(bool oxm)
2764 {
2765     struct ds in;
2766
2767     ds_init(&in);
2768     while (!ds_get_test_line(&in, stdin)) {
2769         struct ofpbuf nx_match;
2770         struct match match;
2771         ovs_be64 cookie, cookie_mask;
2772         enum ofperr error;
2773         int match_len;
2774
2775         /* Convert string to nx_match. */
2776         ofpbuf_init(&nx_match, 0);
2777         if (oxm) {
2778             match_len = oxm_match_from_string(ds_cstr(&in), &nx_match);
2779         } else {
2780             match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
2781         }
2782
2783         /* Convert nx_match to match. */
2784         if (strict) {
2785             if (oxm) {
2786                 error = oxm_pull_match(&nx_match, &match);
2787             } else {
2788                 error = nx_pull_match(&nx_match, match_len, &match,
2789                                       &cookie, &cookie_mask);
2790             }
2791         } else {
2792             if (oxm) {
2793                 error = oxm_pull_match_loose(&nx_match, &match);
2794             } else {
2795                 error = nx_pull_match_loose(&nx_match, match_len, &match,
2796                                             &cookie, &cookie_mask);
2797             }
2798         }
2799
2800
2801         if (!error) {
2802             char *out;
2803
2804             /* Convert match back to nx_match. */
2805             ofpbuf_uninit(&nx_match);
2806             ofpbuf_init(&nx_match, 0);
2807             if (oxm) {
2808                 match_len = oxm_put_match(&nx_match, &match);
2809                 out = oxm_match_to_string(&nx_match, match_len);
2810             } else {
2811                 match_len = nx_put_match(&nx_match, &match,
2812                                          cookie, cookie_mask);
2813                 out = nx_match_to_string(nx_match.data, match_len);
2814             }
2815
2816             puts(out);
2817             free(out);
2818         } else {
2819             printf("nx_pull_match() returned error %s\n",
2820                    ofperr_get_name(error));
2821         }
2822
2823         ofpbuf_uninit(&nx_match);
2824     }
2825     ds_destroy(&in);
2826 }
2827
2828 /* "parse-nxm": reads a series of NXM nx_match specifications as strings from
2829  * stdin, does some internal fussing with them, and then prints them back as
2830  * strings on stdout. */
2831 static void
2832 ofctl_parse_nxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2833 {
2834     return ofctl_parse_nxm__(false);
2835 }
2836
2837 /* "parse-oxm": reads a series of OXM nx_match specifications as strings from
2838  * stdin, does some internal fussing with them, and then prints them back as
2839  * strings on stdout. */
2840 static void
2841 ofctl_parse_oxm(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2842 {
2843     return ofctl_parse_nxm__(true);
2844 }
2845
2846 static void
2847 print_differences(const char *prefix,
2848                   const void *a_, size_t a_len,
2849                   const void *b_, size_t b_len)
2850 {
2851     const uint8_t *a = a_;
2852     const uint8_t *b = b_;
2853     size_t i;
2854
2855     for (i = 0; i < MIN(a_len, b_len); i++) {
2856         if (a[i] != b[i]) {
2857             printf("%s%2"PRIuSIZE": %02"PRIx8" -> %02"PRIx8"\n",
2858                    prefix, i, a[i], b[i]);
2859         }
2860     }
2861     for (i = a_len; i < b_len; i++) {
2862         printf("%s%2"PRIuSIZE": (none) -> %02"PRIx8"\n", prefix, i, b[i]);
2863     }
2864     for (i = b_len; i < a_len; i++) {
2865         printf("%s%2"PRIuSIZE": %02"PRIx8" -> (none)\n", prefix, i, a[i]);
2866     }
2867 }
2868
2869 /* "parse-ofp10-actions": reads a series of OpenFlow 1.0 action specifications
2870  * as hex bytes from stdin, converts them to ofpacts, prints them as strings
2871  * on stdout, and then converts them back to hex bytes and prints any
2872  * differences from the input. */
2873 static void
2874 ofctl_parse_ofp10_actions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2875 {
2876     struct ds in;
2877
2878     ds_init(&in);
2879     while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
2880         struct ofpbuf of10_out;
2881         struct ofpbuf of10_in;
2882         struct ofpbuf ofpacts;
2883         enum ofperr error;
2884         size_t size;
2885         struct ds s;
2886
2887         /* Parse hex bytes. */
2888         ofpbuf_init(&of10_in, 0);
2889         if (ofpbuf_put_hex(&of10_in, ds_cstr(&in), NULL)[0] != '\0') {
2890             ovs_fatal(0, "Trailing garbage in hex data");
2891         }
2892
2893         /* Convert to ofpacts. */
2894         ofpbuf_init(&ofpacts, 0);
2895         size = of10_in.size;
2896         error = ofpacts_pull_openflow_actions(&of10_in, of10_in.size,
2897                                               OFP10_VERSION, &ofpacts);
2898         if (error) {
2899             printf("bad OF1.1 actions: %s\n\n", ofperr_get_name(error));
2900             ofpbuf_uninit(&ofpacts);
2901             ofpbuf_uninit(&of10_in);
2902             continue;
2903         }
2904         ofpbuf_push_uninit(&of10_in, size);
2905
2906         /* Print cls_rule. */
2907         ds_init(&s);
2908         ds_put_cstr(&s, "actions=");
2909         ofpacts_format(ofpacts.data, ofpacts.size, &s);
2910         puts(ds_cstr(&s));
2911         ds_destroy(&s);
2912
2913         /* Convert back to ofp10 actions and print differences from input. */
2914         ofpbuf_init(&of10_out, 0);
2915         ofpacts_put_openflow_actions(ofpacts.data, ofpacts.size, &of10_out,
2916                                      OFP10_VERSION);
2917
2918         print_differences("", of10_in.data, of10_in.size,
2919                           of10_out.data, of10_out.size);
2920         putchar('\n');
2921
2922         ofpbuf_uninit(&ofpacts);
2923         ofpbuf_uninit(&of10_in);
2924         ofpbuf_uninit(&of10_out);
2925     }
2926     ds_destroy(&in);
2927 }
2928
2929 /* "parse-ofp10-match": reads a series of ofp10_match specifications as hex
2930  * bytes from stdin, converts them to cls_rules, prints them as strings on
2931  * stdout, and then converts them back to hex bytes and prints any differences
2932  * from the input.
2933  *
2934  * The input hex bytes may contain "x"s to represent "don't-cares", bytes whose
2935  * values are ignored in the input and will be set to zero when OVS converts
2936  * them back to hex bytes.  ovs-ofctl actually sets "x"s to random bits when
2937  * it does the conversion to hex, to ensure that in fact they are ignored. */
2938 static void
2939 ofctl_parse_ofp10_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
2940 {
2941     struct ds expout;
2942     struct ds in;
2943
2944     ds_init(&in);
2945     ds_init(&expout);
2946     while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
2947         struct ofpbuf match_in, match_expout;
2948         struct ofp10_match match_out;
2949         struct ofp10_match match_normal;
2950         struct match match;
2951         char *p;
2952
2953         /* Parse hex bytes to use for expected output. */
2954         ds_clear(&expout);
2955         ds_put_cstr(&expout, ds_cstr(&in));
2956         for (p = ds_cstr(&expout); *p; p++) {
2957             if (*p == 'x') {
2958                 *p = '0';
2959             }
2960         }
2961         ofpbuf_init(&match_expout, 0);
2962         if (ofpbuf_put_hex(&match_expout, ds_cstr(&expout), NULL)[0] != '\0') {
2963             ovs_fatal(0, "Trailing garbage in hex data");
2964         }
2965         if (match_expout.size != sizeof(struct ofp10_match)) {
2966             ovs_fatal(0, "Input is %"PRIuSIZE" bytes, expected %"PRIuSIZE,
2967                       match_expout.size, sizeof(struct ofp10_match));
2968         }
2969
2970         /* Parse hex bytes for input. */
2971         for (p = ds_cstr(&in); *p; p++) {
2972             if (*p == 'x') {
2973                 *p = "0123456789abcdef"[random_uint32() & 0xf];
2974             }
2975         }
2976         ofpbuf_init(&match_in, 0);
2977         if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
2978             ovs_fatal(0, "Trailing garbage in hex data");
2979         }
2980         if (match_in.size != sizeof(struct ofp10_match)) {
2981             ovs_fatal(0, "Input is %"PRIuSIZE" bytes, expected %"PRIuSIZE,
2982                       match_in.size, sizeof(struct ofp10_match));
2983         }
2984
2985         /* Convert to cls_rule and print. */
2986         ofputil_match_from_ofp10_match(match_in.data, &match);
2987         match_print(&match);
2988
2989         /* Convert back to ofp10_match and print differences from input. */
2990         ofputil_match_to_ofp10_match(&match, &match_out);
2991         print_differences("", match_expout.data, match_expout.size,
2992                           &match_out, sizeof match_out);
2993
2994         /* Normalize, then convert and compare again. */
2995         ofputil_normalize_match(&match);
2996         ofputil_match_to_ofp10_match(&match, &match_normal);
2997         print_differences("normal: ", &match_out, sizeof match_out,
2998                           &match_normal, sizeof match_normal);
2999         putchar('\n');
3000
3001         ofpbuf_uninit(&match_in);
3002         ofpbuf_uninit(&match_expout);
3003     }
3004     ds_destroy(&in);
3005     ds_destroy(&expout);
3006 }
3007
3008 /* "parse-ofp11-match": reads a series of ofp11_match specifications as hex
3009  * bytes from stdin, converts them to "struct match"es, prints them as strings
3010  * on stdout, and then converts them back to hex bytes and prints any
3011  * differences from the input. */
3012 static void
3013 ofctl_parse_ofp11_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
3014 {
3015     struct ds in;
3016
3017     ds_init(&in);
3018     while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3019         struct ofpbuf match_in;
3020         struct ofp11_match match_out;
3021         struct match match;
3022         enum ofperr error;
3023
3024         /* Parse hex bytes. */
3025         ofpbuf_init(&match_in, 0);
3026         if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
3027             ovs_fatal(0, "Trailing garbage in hex data");
3028         }
3029         if (match_in.size != sizeof(struct ofp11_match)) {
3030             ovs_fatal(0, "Input is %"PRIuSIZE" bytes, expected %"PRIuSIZE,
3031                       match_in.size, sizeof(struct ofp11_match));
3032         }
3033
3034         /* Convert to match. */
3035         error = ofputil_match_from_ofp11_match(match_in.data, &match);
3036         if (error) {
3037             printf("bad ofp11_match: %s\n\n", ofperr_get_name(error));
3038             ofpbuf_uninit(&match_in);
3039             continue;
3040         }
3041
3042         /* Print match. */
3043         match_print(&match);
3044
3045         /* Convert back to ofp11_match and print differences from input. */
3046         ofputil_match_to_ofp11_match(&match, &match_out);
3047
3048         print_differences("", match_in.data, match_in.size,
3049                           &match_out, sizeof match_out);
3050         putchar('\n');
3051
3052         ofpbuf_uninit(&match_in);
3053     }
3054     ds_destroy(&in);
3055 }
3056
3057 /* "parse-ofp11-actions": reads a series of OpenFlow 1.1 action specifications
3058  * as hex bytes from stdin, converts them to ofpacts, prints them as strings
3059  * on stdout, and then converts them back to hex bytes and prints any
3060  * differences from the input. */
3061 static void
3062 ofctl_parse_ofp11_actions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
3063 {
3064     struct ds in;
3065
3066     ds_init(&in);
3067     while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3068         struct ofpbuf of11_out;
3069         struct ofpbuf of11_in;
3070         struct ofpbuf ofpacts;
3071         enum ofperr error;
3072         size_t size;
3073         struct ds s;
3074
3075         /* Parse hex bytes. */
3076         ofpbuf_init(&of11_in, 0);
3077         if (ofpbuf_put_hex(&of11_in, ds_cstr(&in), NULL)[0] != '\0') {
3078             ovs_fatal(0, "Trailing garbage in hex data");
3079         }
3080
3081         /* Convert to ofpacts. */
3082         ofpbuf_init(&ofpacts, 0);
3083         size = of11_in.size;
3084         error = ofpacts_pull_openflow_actions(&of11_in, of11_in.size,
3085                                               OFP11_VERSION, &ofpacts);
3086         if (error) {
3087             printf("bad OF1.1 actions: %s\n\n", ofperr_get_name(error));
3088             ofpbuf_uninit(&ofpacts);
3089             ofpbuf_uninit(&of11_in);
3090             continue;
3091         }
3092         ofpbuf_push_uninit(&of11_in, size);
3093
3094         /* Print cls_rule. */
3095         ds_init(&s);
3096         ds_put_cstr(&s, "actions=");
3097         ofpacts_format(ofpacts.data, ofpacts.size, &s);
3098         puts(ds_cstr(&s));
3099         ds_destroy(&s);
3100
3101         /* Convert back to ofp11 actions and print differences from input. */
3102         ofpbuf_init(&of11_out, 0);
3103         ofpacts_put_openflow_actions(ofpacts.data, ofpacts.size, &of11_out,
3104                                      OFP11_VERSION);
3105
3106         print_differences("", of11_in.data, of11_in.size,
3107                           of11_out.data, of11_out.size);
3108         putchar('\n');
3109
3110         ofpbuf_uninit(&ofpacts);
3111         ofpbuf_uninit(&of11_in);
3112         ofpbuf_uninit(&of11_out);
3113     }
3114     ds_destroy(&in);
3115 }
3116
3117 /* "parse-ofp11-instructions": reads a series of OpenFlow 1.1 instruction
3118  * specifications as hex bytes from stdin, converts them to ofpacts, prints
3119  * them as strings on stdout, and then converts them back to hex bytes and
3120  * prints any differences from the input. */
3121 static void
3122 ofctl_parse_ofp11_instructions(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
3123 {
3124     struct ds in;
3125
3126     ds_init(&in);
3127     while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3128         struct ofpbuf of11_out;
3129         struct ofpbuf of11_in;
3130         struct ofpbuf ofpacts;
3131         enum ofperr error;
3132         size_t size;
3133         struct ds s;
3134         const char *table_id;
3135         char *instructions;
3136
3137         /* Parse table_id separated with the follow-up instructions by ",", if
3138          * any. */
3139         instructions = ds_cstr(&in);
3140         table_id = NULL;
3141         if (strstr(instructions, ",")) {
3142             table_id = strsep(&instructions, ",");
3143         }
3144
3145         /* Parse hex bytes. */
3146         ofpbuf_init(&of11_in, 0);
3147         if (ofpbuf_put_hex(&of11_in, instructions, NULL)[0] != '\0') {
3148             ovs_fatal(0, "Trailing garbage in hex data");
3149         }
3150
3151         /* Convert to ofpacts. */
3152         ofpbuf_init(&ofpacts, 0);
3153         size = of11_in.size;
3154         error = ofpacts_pull_openflow_instructions(&of11_in, of11_in.size,
3155                                                    OFP11_VERSION, &ofpacts);
3156         if (!error) {
3157             /* Verify actions, enforce consistency. */
3158             struct flow flow;
3159             memset(&flow, 0, sizeof flow);
3160             error = ofpacts_check_consistency(ofpacts.data, ofpacts.size,
3161                                               &flow, OFPP_MAX,
3162                                               table_id ? atoi(table_id) : 0,
3163                                               255, OFPUTIL_P_OF11_STD);
3164         }
3165         if (error) {
3166             printf("bad OF1.1 instructions: %s\n\n", ofperr_get_name(error));
3167             ofpbuf_uninit(&ofpacts);
3168             ofpbuf_uninit(&of11_in);
3169             continue;
3170         }
3171         ofpbuf_push_uninit(&of11_in, size);
3172
3173         /* Print cls_rule. */
3174         ds_init(&s);
3175         ds_put_cstr(&s, "actions=");
3176         ofpacts_format(ofpacts.data, ofpacts.size, &s);
3177         puts(ds_cstr(&s));
3178         ds_destroy(&s);
3179
3180         /* Convert back to ofp11 instructions and print differences from
3181          * input. */
3182         ofpbuf_init(&of11_out, 0);
3183         ofpacts_put_openflow_instructions(ofpacts.data, ofpacts.size,
3184                                           &of11_out, OFP13_VERSION);
3185
3186         print_differences("", of11_in.data, of11_in.size,
3187                           of11_out.data, of11_out.size);
3188         putchar('\n');
3189
3190         ofpbuf_uninit(&ofpacts);
3191         ofpbuf_uninit(&of11_in);
3192         ofpbuf_uninit(&of11_out);
3193     }
3194     ds_destroy(&in);
3195 }
3196
3197 /* "parse-pcap PCAP": read packets from PCAP and print their flows. */
3198 static void
3199 ofctl_parse_pcap(int argc OVS_UNUSED, char *argv[])
3200 {
3201     FILE *pcap;
3202
3203     pcap = ovs_pcap_open(argv[1], "rb");
3204     if (!pcap) {
3205         ovs_fatal(errno, "%s: open failed", argv[1]);
3206     }
3207
3208     for (;;) {
3209         struct ofpbuf *packet;
3210         struct flow flow;
3211         int error;
3212
3213         error = ovs_pcap_read(pcap, &packet, NULL);
3214         if (error == EOF) {
3215             break;
3216         } else if (error) {
3217             ovs_fatal(error, "%s: read failed", argv[1]);
3218         }
3219
3220         flow_extract(packet, 0, 0, NULL, NULL, &flow);
3221         flow_print(stdout, &flow);
3222         putchar('\n');
3223         ofpbuf_delete(packet);
3224     }
3225 }
3226
3227 /* "check-vlan VLAN_TCI VLAN_TCI_MASK": converts the specified vlan_tci and
3228  * mask values to and from various formats and prints the results. */
3229 static void
3230 ofctl_check_vlan(int argc OVS_UNUSED, char *argv[])
3231 {
3232     struct match match;
3233
3234     char *string_s;
3235     struct ofputil_flow_mod fm;
3236
3237     struct ofpbuf nxm;
3238     struct match nxm_match;
3239     int nxm_match_len;
3240     char *nxm_s;
3241
3242     struct ofp10_match of10_raw;
3243     struct match of10_match;
3244
3245     struct ofp11_match of11_raw;
3246     struct match of11_match;
3247
3248     enum ofperr error;
3249     char *error_s;
3250
3251     enum ofputil_protocol usable_protocols; /* Unused for now. */
3252
3253     match_init_catchall(&match);
3254     match.flow.vlan_tci = htons(strtoul(argv[1], NULL, 16));
3255     match.wc.masks.vlan_tci = htons(strtoul(argv[2], NULL, 16));
3256
3257     /* Convert to and from string. */
3258     string_s = match_to_string(&match, OFP_DEFAULT_PRIORITY);
3259     printf("%s -> ", string_s);
3260     fflush(stdout);
3261     error_s = parse_ofp_str(&fm, -1, string_s, &usable_protocols);
3262     if (error_s) {
3263         ovs_fatal(0, "%s", error_s);
3264     }
3265     printf("%04"PRIx16"/%04"PRIx16"\n",
3266            ntohs(fm.match.flow.vlan_tci),
3267            ntohs(fm.match.wc.masks.vlan_tci));
3268     free(string_s);
3269
3270     /* Convert to and from NXM. */
3271     ofpbuf_init(&nxm, 0);
3272     nxm_match_len = nx_put_match(&nxm, &match, htonll(0), htonll(0));
3273     nxm_s = nx_match_to_string(nxm.data, nxm_match_len);
3274     error = nx_pull_match(&nxm, nxm_match_len, &nxm_match, NULL, NULL);
3275     printf("NXM: %s -> ", nxm_s);
3276     if (error) {
3277         printf("%s\n", ofperr_to_string(error));
3278     } else {
3279         printf("%04"PRIx16"/%04"PRIx16"\n",
3280                ntohs(nxm_match.flow.vlan_tci),
3281                ntohs(nxm_match.wc.masks.vlan_tci));
3282     }
3283     free(nxm_s);
3284     ofpbuf_uninit(&nxm);
3285
3286     /* Convert to and from OXM. */
3287     ofpbuf_init(&nxm, 0);
3288     nxm_match_len = oxm_put_match(&nxm, &match);
3289     nxm_s = oxm_match_to_string(&nxm, nxm_match_len);
3290     error = oxm_pull_match(&nxm, &nxm_match);
3291     printf("OXM: %s -> ", nxm_s);
3292     if (error) {
3293         printf("%s\n", ofperr_to_string(error));
3294     } else {
3295         uint16_t vid = ntohs(nxm_match.flow.vlan_tci) &
3296             (VLAN_VID_MASK | VLAN_CFI);
3297         uint16_t mask = ntohs(nxm_match.wc.masks.vlan_tci) &
3298             (VLAN_VID_MASK | VLAN_CFI);
3299
3300         printf("%04"PRIx16"/%04"PRIx16",", vid, mask);
3301         if (vid && vlan_tci_to_pcp(nxm_match.wc.masks.vlan_tci)) {
3302             printf("%02"PRIx8"\n", vlan_tci_to_pcp(nxm_match.flow.vlan_tci));
3303         } else {
3304             printf("--\n");
3305         }
3306     }
3307     free(nxm_s);
3308     ofpbuf_uninit(&nxm);
3309
3310     /* Convert to and from OpenFlow 1.0. */
3311     ofputil_match_to_ofp10_match(&match, &of10_raw);
3312     ofputil_match_from_ofp10_match(&of10_raw, &of10_match);
3313     printf("OF1.0: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
3314            ntohs(of10_raw.dl_vlan),
3315            (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN)) != 0,
3316            of10_raw.dl_vlan_pcp,
3317            (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN_PCP)) != 0,
3318            ntohs(of10_match.flow.vlan_tci),
3319            ntohs(of10_match.wc.masks.vlan_tci));
3320
3321     /* Convert to and from OpenFlow 1.1. */
3322     ofputil_match_to_ofp11_match(&match, &of11_raw);
3323     ofputil_match_from_ofp11_match(&of11_raw, &of11_match);
3324     printf("OF1.1: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
3325            ntohs(of11_raw.dl_vlan),
3326            (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN)) != 0,
3327            of11_raw.dl_vlan_pcp,
3328            (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN_PCP)) != 0,
3329            ntohs(of11_match.flow.vlan_tci),
3330            ntohs(of11_match.wc.masks.vlan_tci));
3331 }
3332
3333 /* "print-error ENUM": Prints the type and code of ENUM for every OpenFlow
3334  * version. */
3335 static void
3336 ofctl_print_error(int argc OVS_UNUSED, char *argv[])
3337 {
3338     enum ofperr error;
3339     int version;
3340
3341     error = ofperr_from_name(argv[1]);
3342     if (!error) {
3343         ovs_fatal(0, "unknown error \"%s\"", argv[1]);
3344     }
3345
3346     for (version = 0; version <= UINT8_MAX; version++) {
3347         const char *name = ofperr_domain_get_name(version);
3348         if (name) {
3349             int vendor = ofperr_get_vendor(error, version);
3350             int type = ofperr_get_type(error, version);
3351             int code = ofperr_get_code(error, version);
3352
3353             if (vendor != -1 || type != -1 || code != -1) {
3354                 printf("%s: vendor %#x, type %d, code %d\n",
3355                        name, vendor, type, code);
3356             }
3357         }
3358     }
3359 }
3360
3361 /* "encode-error-reply ENUM REQUEST": Encodes an error reply to REQUEST for the
3362  * error named ENUM and prints the error reply in hex. */
3363 static void
3364 ofctl_encode_error_reply(int argc OVS_UNUSED, char *argv[])
3365 {
3366     const struct ofp_header *oh;
3367     struct ofpbuf request, *reply;
3368     enum ofperr error;
3369
3370     error = ofperr_from_name(argv[1]);
3371     if (!error) {
3372         ovs_fatal(0, "unknown error \"%s\"", argv[1]);
3373     }
3374
3375     ofpbuf_init(&request, 0);
3376     if (ofpbuf_put_hex(&request, argv[2], NULL)[0] != '\0') {
3377         ovs_fatal(0, "Trailing garbage in hex data");
3378     }
3379     if (request.size < sizeof(struct ofp_header)) {
3380         ovs_fatal(0, "Request too short");
3381     }
3382
3383     oh = request.data;
3384     if (request.size != ntohs(oh->length)) {
3385         ovs_fatal(0, "Request size inconsistent");
3386     }
3387
3388     reply = ofperr_encode_reply(error, request.data);
3389     ofpbuf_uninit(&request);
3390
3391     ovs_hex_dump(stdout, reply->data, reply->size, 0, false);
3392     ofpbuf_delete(reply);
3393 }
3394
3395 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
3396  * binary data, interpreting them as an OpenFlow message, and prints the
3397  * OpenFlow message on stdout, at VERBOSITY (level 2 by default).  */
3398 static void
3399 ofctl_ofp_print(int argc, char *argv[])
3400 {
3401     struct ofpbuf packet;
3402
3403     ofpbuf_init(&packet, strlen(argv[1]) / 2);
3404     if (ofpbuf_put_hex(&packet, argv[1], NULL)[0] != '\0') {
3405         ovs_fatal(0, "trailing garbage following hex bytes");
3406     }
3407     ofp_print(stdout, packet.data, packet.size, argc > 2 ? atoi(argv[2]) : 2);
3408     ofpbuf_uninit(&packet);
3409 }
3410
3411 /* "encode-hello BITMAP...": Encodes each BITMAP as an OpenFlow hello message
3412  * and dumps each message in hex.  */
3413 static void
3414 ofctl_encode_hello(int argc OVS_UNUSED, char *argv[])
3415 {
3416     uint32_t bitmap = strtol(argv[1], NULL, 0);
3417     struct ofpbuf *hello;
3418
3419     hello = ofputil_encode_hello(bitmap);
3420     ovs_hex_dump(stdout, hello->data, hello->size, 0, false);
3421     ofp_print(stdout, hello->data, hello->size, verbosity);
3422     ofpbuf_delete(hello);
3423 }
3424
3425 static const struct command all_commands[] = {
3426     { "show", 1, 1, ofctl_show },
3427     { "monitor", 1, 3, ofctl_monitor },
3428     { "snoop", 1, 1, ofctl_snoop },
3429     { "dump-desc", 1, 1, ofctl_dump_desc },
3430     { "dump-tables", 1, 1, ofctl_dump_tables },
3431     { "dump-flows", 1, 2, ofctl_dump_flows },
3432     { "dump-aggregate", 1, 2, ofctl_dump_aggregate },
3433     { "queue-stats", 1, 3, ofctl_queue_stats },
3434     { "queue-get-config", 2, 2, ofctl_queue_get_config },
3435     { "add-flow", 2, 2, ofctl_add_flow },
3436     { "add-flows", 2, 2, ofctl_add_flows },
3437     { "mod-flows", 2, 2, ofctl_mod_flows },
3438     { "del-flows", 1, 2, ofctl_del_flows },
3439     { "replace-flows", 2, 2, ofctl_replace_flows },
3440     { "diff-flows", 2, 2, ofctl_diff_flows },
3441     { "add-meter", 2, 2, ofctl_add_meter },
3442     { "mod-meter", 2, 2, ofctl_mod_meter },
3443     { "del-meter", 2, 2, ofctl_del_meters },
3444     { "del-meters", 1, 1, ofctl_del_meters },
3445     { "dump-meter", 2, 2, ofctl_dump_meters },
3446     { "dump-meters", 1, 1, ofctl_dump_meters },
3447     { "meter-stats", 1, 2, ofctl_meter_stats },
3448     { "meter-features", 1, 1, ofctl_meter_features },
3449     { "packet-out", 4, INT_MAX, ofctl_packet_out },
3450     { "dump-ports", 1, 2, ofctl_dump_ports },
3451     { "dump-ports-desc", 1, 1, ofctl_dump_ports_desc },
3452     { "mod-port", 3, 3, ofctl_mod_port },
3453     { "mod-table", 3, 3, ofctl_mod_table },
3454     { "get-frags", 1, 1, ofctl_get_frags },
3455     { "set-frags", 2, 2, ofctl_set_frags },
3456     { "probe", 1, 1, ofctl_probe },
3457     { "ping", 1, 2, ofctl_ping },
3458     { "benchmark", 3, 3, ofctl_benchmark },
3459
3460     { "ofp-parse", 1, 1, ofctl_ofp_parse },
3461     { "ofp-parse-pcap", 1, INT_MAX, ofctl_ofp_parse_pcap },
3462
3463     { "add-group", 1, 2, ofctl_add_group },
3464     { "add-groups", 1, 2, ofctl_add_groups },
3465     { "mod-group", 1, 2, ofctl_mod_group },
3466     { "del-groups", 1, 2, ofctl_del_groups },
3467     { "dump-groups", 1, 1, ofctl_dump_group_desc },
3468     { "dump-group-stats", 1, 2, ofctl_dump_group_stats },
3469     { "dump-group-features", 1, 1, ofctl_dump_group_features },
3470     { "help", 0, INT_MAX, ofctl_help },
3471
3472     /* Undocumented commands for testing. */
3473     { "parse-flow", 1, 1, ofctl_parse_flow },
3474     { "parse-flows", 1, 1, ofctl_parse_flows },
3475     { "parse-nx-match", 0, 0, ofctl_parse_nxm },
3476     { "parse-nxm", 0, 0, ofctl_parse_nxm },
3477     { "parse-oxm", 0, 0, ofctl_parse_oxm },
3478     { "parse-ofp10-actions", 0, 0, ofctl_parse_ofp10_actions },
3479     { "parse-ofp10-match", 0, 0, ofctl_parse_ofp10_match },
3480     { "parse-ofp11-match", 0, 0, ofctl_parse_ofp11_match },
3481     { "parse-ofp11-actions", 0, 0, ofctl_parse_ofp11_actions },
3482     { "parse-ofp11-instructions", 0, 0, ofctl_parse_ofp11_instructions },
3483     { "parse-pcap", 1, 1, ofctl_parse_pcap },
3484     { "check-vlan", 2, 2, ofctl_check_vlan },
3485     { "print-error", 1, 1, ofctl_print_error },
3486     { "encode-error-reply", 2, 2, ofctl_encode_error_reply },
3487     { "ofp-print", 1, 2, ofctl_ofp_print },
3488     { "encode-hello", 1, 1, ofctl_encode_hello },
3489
3490     { NULL, 0, 0, NULL },
3491 };
3492
3493 static const struct command *get_all_commands(void)
3494 {
3495     return all_commands;
3496 }