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