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