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