ovs-ofctl: Make "barrier" output reproducible for testing.
[cascardo/ovs.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <errno.h>
19 #include <getopt.h>
20 #include <inttypes.h>
21 #include <sys/socket.h>
22 #include <net/if.h>
23 #include <signal.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <sys/fcntl.h>
28 #include <sys/stat.h>
29 #include <sys/time.h>
30
31 #include "byte-order.h"
32 #include "classifier.h"
33 #include "command-line.h"
34 #include "daemon.h"
35 #include "compiler.h"
36 #include "dirs.h"
37 #include "dynamic-string.h"
38 #include "netlink.h"
39 #include "nx-match.h"
40 #include "odp-util.h"
41 #include "ofp-errors.h"
42 #include "ofp-parse.h"
43 #include "ofp-print.h"
44 #include "ofp-util.h"
45 #include "ofpbuf.h"
46 #include "ofproto/ofproto.h"
47 #include "openflow/nicira-ext.h"
48 #include "openflow/openflow.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "random.h"
52 #include "stream-ssl.h"
53 #include "timeval.h"
54 #include "unixctl.h"
55 #include "util.h"
56 #include "vconn.h"
57 #include "vlog.h"
58
59 VLOG_DEFINE_THIS_MODULE(ofctl);
60
61 /* --strict: Use strict matching for flow mod commands?  Additionally governs
62  * use of nx_pull_match() instead of nx_pull_match_loose() in parse-nx-match.
63  */
64 static bool strict;
65
66 /* --readd: If true, on replace-flows, re-add even flows that have not changed
67  * (to reset flow counters). */
68 static bool readd;
69
70 /* -F, --flow-format: Allowed protocols.  By default, any protocol is
71  * allowed. */
72 static enum ofputil_protocol allowed_protocols = OFPUTIL_P_ANY;
73
74 /* -P, --packet-in-format: Packet IN format to use in monitor and snoop
75  * commands.  Either one of NXPIF_* to force a particular packet_in format, or
76  * -1 to let ovs-ofctl choose the default. */
77 static int preferred_packet_in_format = -1;
78
79 /* -m, --more: Additional verbosity for ofp-print functions. */
80 static int verbosity;
81
82 /* --timestamp: Print a timestamp before each received packet on "monitor" and
83  * "snoop" command? */
84 static bool timestamp;
85
86 static const struct command all_commands[];
87
88 static void usage(void) NO_RETURN;
89 static void parse_options(int argc, char *argv[]);
90
91 int
92 main(int argc, char *argv[])
93 {
94     set_program_name(argv[0]);
95     parse_options(argc, argv);
96     signal(SIGPIPE, SIG_IGN);
97     run_command(argc - optind, argv + optind, all_commands);
98     return 0;
99 }
100
101 static void
102 parse_options(int argc, char *argv[])
103 {
104     enum {
105         OPT_STRICT = UCHAR_MAX + 1,
106         OPT_READD,
107         OPT_TIMESTAMP,
108         DAEMON_OPTION_ENUMS,
109         VLOG_OPTION_ENUMS
110     };
111     static struct option long_options[] = {
112         {"timeout", required_argument, NULL, 't'},
113         {"strict", no_argument, NULL, OPT_STRICT},
114         {"readd", no_argument, NULL, OPT_READD},
115         {"flow-format", required_argument, NULL, 'F'},
116         {"packet-in-format", required_argument, NULL, 'P'},
117         {"more", no_argument, NULL, 'm'},
118         {"timestamp", no_argument, NULL, OPT_TIMESTAMP},
119         {"help", no_argument, NULL, 'h'},
120         {"version", no_argument, NULL, 'V'},
121         DAEMON_LONG_OPTIONS,
122         VLOG_LONG_OPTIONS,
123         STREAM_SSL_LONG_OPTIONS,
124         {NULL, 0, NULL, 0},
125     };
126     char *short_options = long_options_to_short_options(long_options);
127
128     for (;;) {
129         unsigned long int timeout;
130         int c;
131
132         c = getopt_long(argc, argv, short_options, long_options, NULL);
133         if (c == -1) {
134             break;
135         }
136
137         switch (c) {
138         case 't':
139             timeout = strtoul(optarg, NULL, 10);
140             if (timeout <= 0) {
141                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
142                           optarg);
143             } else {
144                 time_alarm(timeout);
145             }
146             break;
147
148         case 'F':
149             allowed_protocols = ofputil_protocols_from_string(optarg);
150             if (!allowed_protocols) {
151                 ovs_fatal(0, "%s: invalid flow format(s)", optarg);
152             }
153             break;
154
155         case 'P':
156             preferred_packet_in_format =
157                 ofputil_packet_in_format_from_string(optarg);
158             if (preferred_packet_in_format < 0) {
159                 ovs_fatal(0, "unknown packet-in format `%s'", optarg);
160             }
161             break;
162
163         case 'm':
164             verbosity++;
165             break;
166
167         case 'h':
168             usage();
169
170         case 'V':
171             ovs_print_version(OFP10_VERSION, OFP10_VERSION);
172             exit(EXIT_SUCCESS);
173
174         case OPT_STRICT:
175             strict = true;
176             break;
177
178         case OPT_READD:
179             readd = true;
180             break;
181
182         case OPT_TIMESTAMP:
183             timestamp = true;
184             break;
185
186         DAEMON_OPTION_HANDLERS
187         VLOG_OPTION_HANDLERS
188         STREAM_SSL_OPTION_HANDLERS
189
190         case '?':
191             exit(EXIT_FAILURE);
192
193         default:
194             abort();
195         }
196     }
197     free(short_options);
198 }
199
200 static void
201 usage(void)
202 {
203     printf("%s: OpenFlow switch management utility\n"
204            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
205            "\nFor OpenFlow switches:\n"
206            "  show SWITCH                 show OpenFlow information\n"
207            "  dump-desc SWITCH            print switch description\n"
208            "  dump-tables SWITCH          print table stats\n"
209            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
210            "  get-frags SWITCH            print fragment handling behavior\n"
211            "  set-frags SWITCH FRAG_MODE  set fragment handling behavior\n"
212            "  dump-ports SWITCH [PORT]    print port statistics\n"
213            "  dump-flows SWITCH           print all flow entries\n"
214            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
215            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
216            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
217            "  queue-stats SWITCH [PORT [QUEUE]]  dump queue stats\n"
218            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
219            "  add-flows SWITCH FILE       add flows from FILE\n"
220            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
221            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
222            "  replace-flows SWITCH FILE   replace flows with those in FILE\n"
223            "  diff-flows SOURCE1 SOURCE2  compare flows from two sources\n"
224            "  packet-out SWITCH IN_PORT ACTIONS PACKET...\n"
225            "                              execute ACTIONS on PACKET\n"
226            "  monitor SWITCH [MISSLEN] [invalid_ttl]\n"
227            "                              print packets received from SWITCH\n"
228            "  snoop SWITCH                snoop on SWITCH and its controller\n"
229            "\nFor OpenFlow switches and controllers:\n"
230            "  probe TARGET                probe whether TARGET is up\n"
231            "  ping TARGET [N]             latency of N-byte echos\n"
232            "  benchmark TARGET N COUNT    bandwidth of COUNT N-byte echos\n"
233            "where SWITCH or TARGET is an active OpenFlow connection method.\n",
234            program_name, program_name);
235     vconn_usage(true, false, false);
236     daemon_usage();
237     vlog_usage();
238     printf("\nOther options:\n"
239            "  --strict                    use strict match for flow commands\n"
240            "  --readd                     replace flows that haven't changed\n"
241            "  -F, --flow-format=FORMAT    force particular flow format\n"
242            "  -P, --packet-in-format=FRMT force particular packet in format\n"
243            "  -m, --more                  be more verbose printing OpenFlow\n"
244            "  --timestamp                 (monitor, snoop) print timestamps\n"
245            "  -t, --timeout=SECS          give up after SECS seconds\n"
246            "  -h, --help                  display this help message\n"
247            "  -V, --version               display version information\n");
248     exit(EXIT_SUCCESS);
249 }
250
251 static void
252 ofctl_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
253            const char *argv[] OVS_UNUSED, void *exiting_)
254 {
255     bool *exiting = exiting_;
256     *exiting = true;
257     unixctl_command_reply(conn, NULL);
258 }
259
260 static void run(int retval, const char *message, ...)
261     PRINTF_FORMAT(2, 3);
262
263 static void run(int retval, const char *message, ...)
264 {
265     if (retval) {
266         va_list args;
267
268         va_start(args, message);
269         ovs_fatal_valist(retval, message, args);
270     }
271 }
272 \f
273 /* Generic commands. */
274
275 static void
276 open_vconn_socket(const char *name, struct vconn **vconnp)
277 {
278     char *vconn_name = xasprintf("unix:%s", name);
279     VLOG_DBG("connecting to %s", vconn_name);
280     run(vconn_open_block(vconn_name, OFP10_VERSION, vconnp),
281         "connecting to %s", vconn_name);
282     free(vconn_name);
283 }
284
285 static enum ofputil_protocol
286 open_vconn__(const char *name, const char *default_suffix,
287              struct vconn **vconnp)
288 {
289     char *datapath_name, *datapath_type, *socket_name;
290     enum ofputil_protocol protocol;
291     char *bridge_path;
292     int ofp_version;
293     struct stat s;
294
295     bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, default_suffix);
296
297     ofproto_parse_name(name, &datapath_name, &datapath_type);
298     socket_name = xasprintf("%s/%s.%s",
299                             ovs_rundir(), datapath_name, default_suffix);
300     free(datapath_name);
301     free(datapath_type);
302
303     if (strchr(name, ':')) {
304         run(vconn_open_block(name, OFP10_VERSION, vconnp),
305             "connecting to %s", name);
306     } else if (!stat(name, &s) && S_ISSOCK(s.st_mode)) {
307         open_vconn_socket(name, vconnp);
308     } else if (!stat(bridge_path, &s) && S_ISSOCK(s.st_mode)) {
309         open_vconn_socket(bridge_path, vconnp);
310     } else if (!stat(socket_name, &s)) {
311         if (!S_ISSOCK(s.st_mode)) {
312             ovs_fatal(0, "cannot connect to %s: %s is not a socket",
313                       name, socket_name);
314         }
315         open_vconn_socket(socket_name, vconnp);
316     } else {
317         ovs_fatal(0, "%s is not a bridge or a socket", name);
318     }
319
320     free(bridge_path);
321     free(socket_name);
322
323     ofp_version = vconn_get_version(*vconnp);
324     protocol = ofputil_protocol_from_ofp_version(ofp_version);
325     if (!protocol) {
326         ovs_fatal(0, "%s: unsupported OpenFlow version 0x%02x",
327                   name, ofp_version);
328     }
329     return protocol;
330 }
331
332 static enum ofputil_protocol
333 open_vconn(const char *name, struct vconn **vconnp)
334 {
335     return open_vconn__(name, "mgmt", vconnp);
336 }
337
338 static void *
339 alloc_stats_request(size_t rq_len, uint16_t type, struct ofpbuf **bufferp)
340 {
341     struct ofp_stats_msg *rq;
342
343     rq = make_openflow(rq_len, OFPT10_STATS_REQUEST, bufferp);
344     rq->type = htons(type);
345     rq->flags = htons(0);
346     return rq;
347 }
348
349 static void
350 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
351 {
352     update_openflow_length(buffer);
353     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
354 }
355
356 static void
357 dump_transaction(const char *vconn_name, struct ofpbuf *request)
358 {
359     struct vconn *vconn;
360     struct ofpbuf *reply;
361
362     update_openflow_length(request);
363     open_vconn(vconn_name, &vconn);
364     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
365     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
366     vconn_close(vconn);
367 }
368
369 static void
370 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
371 {
372     struct ofpbuf *request;
373     make_openflow(sizeof(struct ofp_header), request_type, &request);
374     dump_transaction(vconn_name, request);
375 }
376
377 static void
378 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
379 {
380     ovs_be32 send_xid = ((struct ofp_header *) request->data)->xid;
381     struct vconn *vconn;
382     bool done = false;
383
384     open_vconn(vconn_name, &vconn);
385     send_openflow_buffer(vconn, request);
386     while (!done) {
387         ovs_be32 recv_xid;
388         struct ofpbuf *reply;
389
390         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
391         recv_xid = ((struct ofp_header *) reply->data)->xid;
392         if (send_xid == recv_xid) {
393             struct ofp_stats_msg *osm;
394
395             ofp_print(stdout, reply->data, reply->size, verbosity + 1);
396
397             osm = ofpbuf_at(reply, 0, sizeof *osm);
398             done = !osm || !(ntohs(osm->flags) & OFPSF_REPLY_MORE);
399         } else {
400             VLOG_DBG("received reply with xid %08"PRIx32" "
401                      "!= expected %08"PRIx32, recv_xid, send_xid);
402         }
403         ofpbuf_delete(reply);
404     }
405     vconn_close(vconn);
406 }
407
408 static void
409 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
410 {
411     struct ofpbuf *request;
412     alloc_stats_request(sizeof(struct ofp_stats_msg), stats_type, &request);
413     dump_stats_transaction(vconn_name, request);
414 }
415
416 /* Sends 'request', which should be a request that only has a reply if an error
417  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
418  * it and exits with an error.
419  *
420  * Destroys all of the 'requests'. */
421 static void
422 transact_multiple_noreply(struct vconn *vconn, struct list *requests)
423 {
424     struct ofpbuf *request, *reply;
425
426     LIST_FOR_EACH (request, list_node, requests) {
427         update_openflow_length(request);
428     }
429
430     run(vconn_transact_multiple_noreply(vconn, requests, &reply),
431         "talking to %s", vconn_get_name(vconn));
432     if (reply) {
433         ofp_print(stderr, reply->data, reply->size, verbosity + 2);
434         exit(1);
435     }
436     ofpbuf_delete(reply);
437 }
438
439 /* Sends 'request', which should be a request that only has a reply if an error
440  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
441  * it and exits with an error.
442  *
443  * Destroys 'request'. */
444 static void
445 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
446 {
447     struct list requests;
448
449     list_init(&requests);
450     list_push_back(&requests, &request->list_node);
451     transact_multiple_noreply(vconn, &requests);
452 }
453
454 static void
455 fetch_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
456 {
457     struct ofp_switch_config *config;
458     struct ofp_header *header;
459     struct ofpbuf *request;
460     struct ofpbuf *reply;
461
462     make_openflow(sizeof(struct ofp_header), OFPT_GET_CONFIG_REQUEST,
463                   &request);
464     run(vconn_transact(vconn, request, &reply),
465         "talking to %s", vconn_get_name(vconn));
466
467     header = reply->data;
468     if (header->type != OFPT_GET_CONFIG_REPLY ||
469         header->length != htons(sizeof *config)) {
470         ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
471     }
472
473     config = reply->data;
474     *config_ = *config;
475
476     ofpbuf_delete(reply);
477 }
478
479 static void
480 set_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
481 {
482     struct ofp_switch_config *config;
483     struct ofp_header save_header;
484     struct ofpbuf *request;
485
486     config = make_openflow(sizeof *config, OFPT_SET_CONFIG, &request);
487     save_header = config->header;
488     *config = *config_;
489     config->header = save_header;
490
491     transact_noreply(vconn, request);
492 }
493
494 static void
495 do_show(int argc OVS_UNUSED, char *argv[])
496 {
497     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
498     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
499 }
500
501 static void
502 do_dump_desc(int argc OVS_UNUSED, char *argv[])
503 {
504     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
505 }
506
507 static void
508 do_dump_tables(int argc OVS_UNUSED, char *argv[])
509 {
510     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
511 }
512
513 /* Opens a connection to 'vconn_name', fetches the port structure for
514  * 'port_name' (which may be a port name or number), and copies it into
515  * '*oppp'. */
516 static void
517 fetch_ofputil_phy_port(const char *vconn_name, const char *port_name,
518                        struct ofputil_phy_port *pp)
519 {
520     struct ofputil_switch_features features;
521     const struct ofp_switch_features *osf;
522     struct ofpbuf *request, *reply;
523     unsigned int port_no;
524     struct vconn *vconn;
525     enum ofperr error;
526     struct ofpbuf b;
527
528     /* Try to interpret the argument as a port number. */
529     if (!str_to_uint(port_name, 10, &port_no)) {
530         port_no = UINT_MAX;
531     }
532
533     /* Fetch the switch's ofp_switch_features. */
534     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
535     open_vconn(vconn_name, &vconn);
536     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
537
538     osf = reply->data;
539     if (reply->size < sizeof *osf) {
540         ovs_fatal(0, "%s: received too-short features reply (only %zu bytes)",
541                   vconn_name, reply->size);
542     }
543     error = ofputil_decode_switch_features(osf, &features, &b);
544     if (error) {
545         ovs_fatal(0, "%s: failed to decode features reply (%s)",
546                   vconn_name, ofperr_to_string(error));
547     }
548
549     while (!ofputil_pull_switch_features_port(&b, pp)) {
550         if (port_no != UINT_MAX
551             ? port_no == pp->port_no
552             : !strcmp(pp->name, port_name)) {
553             ofpbuf_delete(reply);
554             vconn_close(vconn);
555             return;
556         }
557     }
558     ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
559 }
560
561 /* Returns the port number corresponding to 'port_name' (which may be a port
562  * name or number) within the switch 'vconn_name'. */
563 static uint16_t
564 str_to_port_no(const char *vconn_name, const char *port_name)
565 {
566     unsigned int port_no;
567
568     if (str_to_uint(port_name, 10, &port_no)) {
569         return port_no;
570     } else {
571         struct ofputil_phy_port pp;
572
573         fetch_ofputil_phy_port(vconn_name, port_name, &pp);
574         return pp.port_no;
575     }
576 }
577
578 static bool
579 try_set_protocol(struct vconn *vconn, enum ofputil_protocol want,
580                  enum ofputil_protocol *cur)
581 {
582     for (;;) {
583         struct ofpbuf *request, *reply;
584         enum ofputil_protocol next;
585
586         request = ofputil_encode_set_protocol(*cur, want, &next);
587         if (!request) {
588             return true;
589         }
590
591         run(vconn_transact_noreply(vconn, request, &reply),
592             "talking to %s", vconn_get_name(vconn));
593         if (reply) {
594             char *s = ofp_to_string(reply->data, reply->size, 2);
595             VLOG_DBG("%s: failed to set protocol, switch replied: %s",
596                      vconn_get_name(vconn), s);
597             free(s);
598             ofpbuf_delete(reply);
599             return false;
600         }
601
602         *cur = next;
603     }
604 }
605
606 static enum ofputil_protocol
607 set_protocol_for_flow_dump(struct vconn *vconn,
608                            enum ofputil_protocol cur_protocol,
609                            enum ofputil_protocol usable_protocols)
610 {
611     char *usable_s;
612     int i;
613
614     for (i = 0; i < ofputil_n_flow_dump_protocols; i++) {
615         enum ofputil_protocol f = ofputil_flow_dump_protocols[i];
616         if (f & usable_protocols & allowed_protocols
617             && try_set_protocol(vconn, f, &cur_protocol)) {
618             return f;
619         }
620     }
621
622     usable_s = ofputil_protocols_to_string(usable_protocols);
623     if (usable_protocols & allowed_protocols) {
624         ovs_fatal(0, "switch does not support any of the usable flow "
625                   "formats (%s)", usable_s);
626     } else {
627         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
628         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
629                   "allowed flow formats (%s)", usable_s, allowed_s);
630     }
631 }
632
633 static void
634 do_dump_flows__(int argc, char *argv[], bool aggregate)
635 {
636     enum ofputil_protocol usable_protocols, protocol;
637     struct ofputil_flow_stats_request fsr;
638     struct ofpbuf *request;
639     struct vconn *vconn;
640
641     parse_ofp_flow_stats_request_str(&fsr, aggregate, argc > 2 ? argv[2] : "");
642     usable_protocols = ofputil_flow_stats_request_usable_protocols(&fsr);
643
644     protocol = open_vconn(argv[1], &vconn);
645     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
646     request = ofputil_encode_flow_stats_request(&fsr, protocol);
647     dump_stats_transaction(argv[1], request);
648     vconn_close(vconn);
649 }
650
651 static void
652 do_dump_flows(int argc, char *argv[])
653 {
654     return do_dump_flows__(argc, argv, false);
655 }
656
657 static void
658 do_dump_aggregate(int argc, char *argv[])
659 {
660     return do_dump_flows__(argc, argv, true);
661 }
662
663 static void
664 do_queue_stats(int argc, char *argv[])
665 {
666     struct ofp_queue_stats_request *req;
667     struct ofpbuf *request;
668
669     req = alloc_stats_request(sizeof *req, OFPST_QUEUE, &request);
670
671     if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
672         req->port_no = htons(str_to_port_no(argv[1], argv[2]));
673     } else {
674         req->port_no = htons(OFPP_ALL);
675     }
676     if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
677         req->queue_id = htonl(atoi(argv[3]));
678     } else {
679         req->queue_id = htonl(OFPQ_ALL);
680     }
681
682     memset(req->pad, 0, sizeof req->pad);
683
684     dump_stats_transaction(argv[1], request);
685 }
686
687 static enum ofputil_protocol
688 open_vconn_for_flow_mod(const char *remote,
689                         const struct ofputil_flow_mod *fms, size_t n_fms,
690                         struct vconn **vconnp)
691 {
692     enum ofputil_protocol usable_protocols;
693     enum ofputil_protocol cur_protocol;
694     char *usable_s;
695     int i;
696
697     /* Figure out what flow formats will work. */
698     usable_protocols = ofputil_flow_mod_usable_protocols(fms, n_fms);
699     if (!(usable_protocols & allowed_protocols)) {
700         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
701         usable_s = ofputil_protocols_to_string(usable_protocols);
702         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
703                   "allowed flow formats (%s)", usable_s, allowed_s);
704     }
705
706     /* If the initial flow format is allowed and usable, keep it. */
707     cur_protocol = open_vconn(remote, vconnp);
708     if (usable_protocols & allowed_protocols & cur_protocol) {
709         return cur_protocol;
710     }
711
712     /* Otherwise try each flow format in turn. */
713     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
714         enum ofputil_protocol f = 1 << i;
715
716         if (f != cur_protocol
717             && f & usable_protocols & allowed_protocols
718             && try_set_protocol(*vconnp, f, &cur_protocol)) {
719             return f;
720         }
721     }
722
723     usable_s = ofputil_protocols_to_string(usable_protocols);
724     ovs_fatal(0, "switch does not support any of the usable flow "
725               "formats (%s)", usable_s);
726 }
727
728 static void
729 do_flow_mod__(const char *remote, struct ofputil_flow_mod *fms, size_t n_fms)
730 {
731     enum ofputil_protocol protocol;
732     struct vconn *vconn;
733     size_t i;
734
735     protocol = open_vconn_for_flow_mod(remote, fms, n_fms, &vconn);
736
737     for (i = 0; i < n_fms; i++) {
738         struct ofputil_flow_mod *fm = &fms[i];
739
740         transact_noreply(vconn, ofputil_encode_flow_mod(fm, protocol));
741         free(fm->actions);
742     }
743     vconn_close(vconn);
744 }
745
746 static void
747 do_flow_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
748 {
749     struct ofputil_flow_mod *fms = NULL;
750     size_t n_fms = 0;
751
752     parse_ofp_flow_mod_file(argv[2], command, &fms, &n_fms);
753     do_flow_mod__(argv[1], fms, n_fms);
754     free(fms);
755 }
756
757 static void
758 do_flow_mod(int argc, char *argv[], uint16_t command)
759 {
760     if (argc > 2 && !strcmp(argv[2], "-")) {
761         do_flow_mod_file(argc, argv, command);
762     } else {
763         struct ofputil_flow_mod fm;
764         parse_ofp_flow_mod_str(&fm, argc > 2 ? argv[2] : "", command, false);
765         do_flow_mod__(argv[1], &fm, 1);
766     }
767 }
768
769 static void
770 do_add_flow(int argc, char *argv[])
771 {
772     do_flow_mod(argc, argv, OFPFC_ADD);
773 }
774
775 static void
776 do_add_flows(int argc, char *argv[])
777 {
778     do_flow_mod_file(argc, argv, OFPFC_ADD);
779 }
780
781 static void
782 do_mod_flows(int argc, char *argv[])
783 {
784     do_flow_mod(argc, argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
785 }
786
787 static void
788 do_del_flows(int argc, char *argv[])
789 {
790     do_flow_mod(argc, argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
791 }
792
793 static void
794 set_packet_in_format(struct vconn *vconn,
795                      enum nx_packet_in_format packet_in_format)
796 {
797     struct ofpbuf *spif = ofputil_make_set_packet_in_format(packet_in_format);
798     transact_noreply(vconn, spif);
799     VLOG_DBG("%s: using user-specified packet in format %s",
800              vconn_get_name(vconn),
801              ofputil_packet_in_format_to_string(packet_in_format));
802 }
803
804 static int
805 monitor_set_invalid_ttl_to_controller(struct vconn *vconn)
806 {
807     struct ofp_switch_config config;
808     enum ofp_config_flags flags;
809
810     fetch_switch_config(vconn, &config);
811     flags = ntohs(config.flags);
812     if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
813         /* Set the invalid ttl config. */
814         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
815
816         config.flags = htons(flags);
817         set_switch_config(vconn, &config);
818
819         /* Then retrieve the configuration to see if it really took.  OpenFlow
820          * doesn't define error reporting for bad modes, so this is all we can
821          * do. */
822         fetch_switch_config(vconn, &config);
823         flags = ntohs(config.flags);
824         if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
825             ovs_fatal(0, "setting invalid_ttl_to_controller failed (this "
826                       "switch probably doesn't support mode)");
827             return -EOPNOTSUPP;
828         }
829     }
830     return 0;
831 }
832
833 /* Converts hex digits in 'hex' to an OpenFlow message in '*msgp'.  The
834  * caller must free '*msgp'.  On success, returns NULL.  On failure, returns
835  * an error message and stores NULL in '*msgp'. */
836 static const char *
837 openflow_from_hex(const char *hex, struct ofpbuf **msgp)
838 {
839     struct ofp_header *oh;
840     struct ofpbuf *msg;
841
842     msg = ofpbuf_new(strlen(hex) / 2);
843     *msgp = NULL;
844
845     if (ofpbuf_put_hex(msg, hex, NULL)[0] != '\0') {
846         ofpbuf_delete(msg);
847         return "Trailing garbage in hex data";
848     }
849
850     if (msg->size < sizeof(struct ofp_header)) {
851         ofpbuf_delete(msg);
852         return "Message too short for OpenFlow";
853     }
854
855     oh = msg->data;
856     if (msg->size != ntohs(oh->length)) {
857         ofpbuf_delete(msg);
858         return "Message size does not match length in OpenFlow header";
859     }
860
861     *msgp = msg;
862     return NULL;
863 }
864
865 static void
866 ofctl_send(struct unixctl_conn *conn, int argc,
867            const char *argv[], void *vconn_)
868 {
869     struct vconn *vconn = vconn_;
870     struct ds reply;
871     bool ok;
872     int i;
873
874     ok = true;
875     ds_init(&reply);
876     for (i = 1; i < argc; i++) {
877         const char *error_msg;
878         struct ofpbuf *msg;
879         int error;
880
881         error_msg = openflow_from_hex(argv[i], &msg);
882         if (error_msg) {
883             ds_put_format(&reply, "%s\n", error_msg);
884             ok = false;
885             continue;
886         }
887
888         fprintf(stderr, "send: ");
889         ofp_print(stderr, msg->data, msg->size, verbosity);
890
891         error = vconn_send_block(vconn, msg);
892         if (error) {
893             ofpbuf_delete(msg);
894             ds_put_format(&reply, "%s\n", strerror(error));
895             ok = false;
896         } else {
897             ds_put_cstr(&reply, "sent\n");
898         }
899     }
900
901     if (ok) {
902         unixctl_command_reply(conn, ds_cstr(&reply));
903     } else {
904         unixctl_command_reply_error(conn, ds_cstr(&reply));
905     }
906     ds_destroy(&reply);
907 }
908
909 struct barrier_aux {
910     struct vconn *vconn;        /* OpenFlow connection for sending barrier. */
911     struct unixctl_conn *conn;  /* Connection waiting for barrier response. */
912 };
913
914 static void
915 ofctl_barrier(struct unixctl_conn *conn, int argc OVS_UNUSED,
916               const char *argv[] OVS_UNUSED, void *aux_)
917 {
918     struct barrier_aux *aux = aux_;
919     struct ofpbuf *msg;
920     int error;
921
922     if (aux->conn) {
923         unixctl_command_reply_error(conn, "already waiting for barrier reply");
924         return;
925     }
926
927     msg = ofputil_encode_barrier_request();
928     error = vconn_send_block(aux->vconn, msg);
929     if (error) {
930         ofpbuf_delete(msg);
931         unixctl_command_reply_error(conn, strerror(error));
932     } else {
933         aux->conn = conn;
934     }
935 }
936
937 static void
938 ofctl_set_output_file(struct unixctl_conn *conn, int argc OVS_UNUSED,
939                       const char *argv[], void *aux OVS_UNUSED)
940 {
941     int fd;
942
943     fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
944     if (fd < 0) {
945         unixctl_command_reply_error(conn, strerror(errno));
946         return;
947     }
948
949     fflush(stderr);
950     dup2(fd, STDERR_FILENO);
951     close(fd);
952     unixctl_command_reply(conn, NULL);
953 }
954
955 static void
956 monitor_vconn(struct vconn *vconn)
957 {
958     struct barrier_aux barrier_aux = { vconn, NULL };
959     struct unixctl_server *server;
960     bool exiting = false;
961     int error;
962
963     daemon_save_fd(STDERR_FILENO);
964     daemonize_start();
965     error = unixctl_server_create(NULL, &server);
966     if (error) {
967         ovs_fatal(error, "failed to create unixctl server");
968     }
969     unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
970     unixctl_command_register("ofctl/send", "OFMSG...", 1, INT_MAX,
971                              ofctl_send, vconn);
972     unixctl_command_register("ofctl/barrier", "", 0, 0,
973                              ofctl_barrier, &barrier_aux);
974     unixctl_command_register("ofctl/set-output-file", "FILE", 1, 1,
975                              ofctl_set_output_file, NULL);
976     daemonize_complete();
977
978     for (;;) {
979         struct ofpbuf *b;
980         int retval;
981
982         unixctl_server_run(server);
983
984         for (;;) {
985             uint8_t msg_type;
986
987             retval = vconn_recv(vconn, &b);
988             if (retval == EAGAIN) {
989                 break;
990             }
991             run(retval, "vconn_recv");
992
993             if (timestamp) {
994                 time_t now = time_wall();
995                 char s[32];
996
997                 strftime(s, sizeof s, "%Y-%m-%d %H:%M:%S: ", localtime(&now));
998                 fputs(s, stderr);
999             }
1000
1001             msg_type = ((const struct ofp_header *) b->data)->type;
1002             ofp_print(stderr, b->data, b->size, verbosity + 2);
1003             ofpbuf_delete(b);
1004
1005             if (barrier_aux.conn && msg_type == OFPT10_BARRIER_REPLY) {
1006                 unixctl_command_reply(barrier_aux.conn, NULL);
1007                 barrier_aux.conn = NULL;
1008             }
1009         }
1010
1011         if (exiting) {
1012             break;
1013         }
1014
1015         vconn_run(vconn);
1016         vconn_run_wait(vconn);
1017         vconn_recv_wait(vconn);
1018         unixctl_server_wait(server);
1019         poll_block();
1020     }
1021     vconn_close(vconn);
1022     unixctl_server_destroy(server);
1023 }
1024
1025 static void
1026 do_monitor(int argc, char *argv[])
1027 {
1028     struct vconn *vconn;
1029
1030     open_vconn(argv[1], &vconn);
1031     if (argc > 2) {
1032         struct ofp_switch_config config;
1033
1034         fetch_switch_config(vconn, &config);
1035         config.miss_send_len = htons(atoi(argv[2]));
1036         set_switch_config(vconn, &config);
1037     }
1038     if (argc > 3) {
1039         if (!strcmp(argv[3], "invalid_ttl")) {
1040             monitor_set_invalid_ttl_to_controller(vconn);
1041         }
1042     }
1043     if (preferred_packet_in_format >= 0) {
1044         set_packet_in_format(vconn, preferred_packet_in_format);
1045     } else {
1046         struct ofpbuf *spif, *reply;
1047
1048         spif = ofputil_make_set_packet_in_format(NXPIF_NXM);
1049         run(vconn_transact_noreply(vconn, spif, &reply),
1050             "talking to %s", vconn_get_name(vconn));
1051         if (reply) {
1052             char *s = ofp_to_string(reply->data, reply->size, 2);
1053             VLOG_DBG("%s: failed to set packet in format to nxm, controller"
1054                      " replied: %s. Falling back to the switch default.",
1055                      vconn_get_name(vconn), s);
1056             free(s);
1057             ofpbuf_delete(reply);
1058         }
1059     }
1060
1061     monitor_vconn(vconn);
1062 }
1063
1064 static void
1065 do_snoop(int argc OVS_UNUSED, char *argv[])
1066 {
1067     struct vconn *vconn;
1068
1069     open_vconn__(argv[1], "snoop", &vconn);
1070     monitor_vconn(vconn);
1071 }
1072
1073 static void
1074 do_dump_ports(int argc, char *argv[])
1075 {
1076     struct ofp_port_stats_request *req;
1077     struct ofpbuf *request;
1078     uint16_t port;
1079
1080     req = alloc_stats_request(sizeof *req, OFPST_PORT, &request);
1081     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_NONE;
1082     req->port_no = htons(port);
1083     dump_stats_transaction(argv[1], request);
1084 }
1085
1086 static void
1087 do_probe(int argc OVS_UNUSED, char *argv[])
1088 {
1089     struct ofpbuf *request;
1090     struct vconn *vconn;
1091     struct ofpbuf *reply;
1092
1093     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
1094     open_vconn(argv[1], &vconn);
1095     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1096     if (reply->size != sizeof(struct ofp_header)) {
1097         ovs_fatal(0, "reply does not match request");
1098     }
1099     ofpbuf_delete(reply);
1100     vconn_close(vconn);
1101 }
1102
1103 static void
1104 do_packet_out(int argc, char *argv[])
1105 {
1106     struct ofputil_packet_out po;
1107     struct ofpbuf actions;
1108     struct vconn *vconn;
1109     int i;
1110
1111     ofpbuf_init(&actions, sizeof(union ofp_action));
1112     parse_ofp_actions(argv[3], &actions);
1113
1114     po.buffer_id = UINT32_MAX;
1115     po.in_port = (!strcasecmp(argv[2], "none") ? OFPP_NONE
1116                   : !strcasecmp(argv[2], "local") ? OFPP_LOCAL
1117                   : str_to_port_no(argv[1], argv[2]));
1118     po.actions = actions.data;
1119     po.n_actions = actions.size / sizeof(union ofp_action);
1120
1121     open_vconn(argv[1], &vconn);
1122     for (i = 4; i < argc; i++) {
1123         struct ofpbuf *packet, *opo;
1124         const char *error_msg;
1125
1126         error_msg = eth_from_hex(argv[i], &packet);
1127         if (error_msg) {
1128             ovs_fatal(0, "%s", error_msg);
1129         }
1130
1131         po.packet = packet->data;
1132         po.packet_len = packet->size;
1133         opo = ofputil_encode_packet_out(&po);
1134         transact_noreply(vconn, opo);
1135         ofpbuf_delete(packet);
1136     }
1137     vconn_close(vconn);
1138 }
1139
1140 static void
1141 do_mod_port(int argc OVS_UNUSED, char *argv[])
1142 {
1143     enum ofputil_protocol protocol;
1144     struct ofputil_port_mod pm;
1145     struct ofputil_phy_port pp;
1146     struct vconn *vconn;
1147
1148     fetch_ofputil_phy_port(argv[1], argv[2], &pp);
1149
1150     pm.port_no = pp.port_no;
1151     memcpy(pm.hw_addr, pp.hw_addr, ETH_ADDR_LEN);
1152     pm.config = 0;
1153     pm.mask = 0;
1154     pm.advertise = 0;
1155
1156     if (!strcasecmp(argv[3], "up")) {
1157         pm.mask |= OFPUTIL_PC_PORT_DOWN;
1158     } else if (!strcasecmp(argv[3], "down")) {
1159         pm.mask |= OFPUTIL_PC_PORT_DOWN;
1160         pm.config |= OFPUTIL_PC_PORT_DOWN;
1161     } else if (!strcasecmp(argv[3], "flood")) {
1162         pm.mask |= OFPUTIL_PC_NO_FLOOD;
1163     } else if (!strcasecmp(argv[3], "noflood")) {
1164         pm.mask |= OFPUTIL_PC_NO_FLOOD;
1165         pm.config |= OFPUTIL_PC_NO_FLOOD;
1166     } else if (!strcasecmp(argv[3], "forward")) {
1167         pm.mask |= OFPUTIL_PC_NO_FWD;
1168     } else if (!strcasecmp(argv[3], "noforward")) {
1169         pm.mask |= OFPUTIL_PC_NO_FWD;
1170         pm.config |= OFPUTIL_PC_NO_FWD;
1171     } else {
1172         ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1173     }
1174
1175     protocol = open_vconn(argv[1], &vconn);
1176     transact_noreply(vconn, ofputil_encode_port_mod(&pm, protocol));
1177     vconn_close(vconn);
1178 }
1179
1180 static void
1181 do_get_frags(int argc OVS_UNUSED, char *argv[])
1182 {
1183     struct ofp_switch_config config;
1184     struct vconn *vconn;
1185
1186     open_vconn(argv[1], &vconn);
1187     fetch_switch_config(vconn, &config);
1188     puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
1189     vconn_close(vconn);
1190 }
1191
1192 static void
1193 do_set_frags(int argc OVS_UNUSED, char *argv[])
1194 {
1195     struct ofp_switch_config config;
1196     enum ofp_config_flags mode;
1197     struct vconn *vconn;
1198     ovs_be16 flags;
1199
1200     if (!ofputil_frag_handling_from_string(argv[2], &mode)) {
1201         ovs_fatal(0, "%s: unknown fragment handling mode", argv[2]);
1202     }
1203
1204     open_vconn(argv[1], &vconn);
1205     fetch_switch_config(vconn, &config);
1206     flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
1207     if (flags != config.flags) {
1208         /* Set the configuration. */
1209         config.flags = flags;
1210         set_switch_config(vconn, &config);
1211
1212         /* Then retrieve the configuration to see if it really took.  OpenFlow
1213          * doesn't define error reporting for bad modes, so this is all we can
1214          * do. */
1215         fetch_switch_config(vconn, &config);
1216         if (flags != config.flags) {
1217             ovs_fatal(0, "%s: setting fragment handling mode failed (this "
1218                       "switch probably doesn't support mode \"%s\")",
1219                       argv[1], ofputil_frag_handling_to_string(mode));
1220         }
1221     }
1222     vconn_close(vconn);
1223 }
1224
1225 static void
1226 do_ping(int argc, char *argv[])
1227 {
1228     size_t max_payload = 65535 - sizeof(struct ofp_header);
1229     unsigned int payload;
1230     struct vconn *vconn;
1231     int i;
1232
1233     payload = argc > 2 ? atoi(argv[2]) : 64;
1234     if (payload > max_payload) {
1235         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1236     }
1237
1238     open_vconn(argv[1], &vconn);
1239     for (i = 0; i < 10; i++) {
1240         struct timeval start, end;
1241         struct ofpbuf *request, *reply;
1242         struct ofp_header *rq_hdr, *rpy_hdr;
1243
1244         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1245                                OFPT_ECHO_REQUEST, &request);
1246         random_bytes(rq_hdr + 1, payload);
1247
1248         xgettimeofday(&start);
1249         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1250         xgettimeofday(&end);
1251
1252         rpy_hdr = reply->data;
1253         if (reply->size != request->size
1254             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1255             || rpy_hdr->xid != rq_hdr->xid
1256             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1257             printf("Reply does not match request.  Request:\n");
1258             ofp_print(stdout, request, request->size, verbosity + 2);
1259             printf("Reply:\n");
1260             ofp_print(stdout, reply, reply->size, verbosity + 2);
1261         }
1262         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1263                reply->size - sizeof *rpy_hdr, argv[1], ntohl(rpy_hdr->xid),
1264                    (1000*(double)(end.tv_sec - start.tv_sec))
1265                    + (.001*(end.tv_usec - start.tv_usec)));
1266         ofpbuf_delete(request);
1267         ofpbuf_delete(reply);
1268     }
1269     vconn_close(vconn);
1270 }
1271
1272 static void
1273 do_benchmark(int argc OVS_UNUSED, char *argv[])
1274 {
1275     size_t max_payload = 65535 - sizeof(struct ofp_header);
1276     struct timeval start, end;
1277     unsigned int payload_size, message_size;
1278     struct vconn *vconn;
1279     double duration;
1280     int count;
1281     int i;
1282
1283     payload_size = atoi(argv[2]);
1284     if (payload_size > max_payload) {
1285         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1286     }
1287     message_size = sizeof(struct ofp_header) + payload_size;
1288
1289     count = atoi(argv[3]);
1290
1291     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1292            count, message_size, count * message_size);
1293
1294     open_vconn(argv[1], &vconn);
1295     xgettimeofday(&start);
1296     for (i = 0; i < count; i++) {
1297         struct ofpbuf *request, *reply;
1298         struct ofp_header *rq_hdr;
1299
1300         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1301         memset(rq_hdr + 1, 0, payload_size);
1302         run(vconn_transact(vconn, request, &reply), "transact");
1303         ofpbuf_delete(reply);
1304     }
1305     xgettimeofday(&end);
1306     vconn_close(vconn);
1307
1308     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1309                 + (.001*(end.tv_usec - start.tv_usec)));
1310     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1311            duration, count / (duration / 1000.0),
1312            count * message_size / (duration / 1000.0));
1313 }
1314
1315 static void
1316 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1317 {
1318     usage();
1319 }
1320 \f
1321 /* replace-flows and diff-flows commands. */
1322
1323 /* A flow table entry, possibly with two different versions. */
1324 struct fte {
1325     struct cls_rule rule;       /* Within a "struct classifier". */
1326     struct fte_version *versions[2];
1327 };
1328
1329 /* One version of a Flow Table Entry. */
1330 struct fte_version {
1331     ovs_be64 cookie;
1332     uint16_t idle_timeout;
1333     uint16_t hard_timeout;
1334     uint16_t flags;
1335     union ofp_action *actions;
1336     size_t n_actions;
1337 };
1338
1339 /* Frees 'version' and the data that it owns. */
1340 static void
1341 fte_version_free(struct fte_version *version)
1342 {
1343     if (version) {
1344         free(version->actions);
1345         free(version);
1346     }
1347 }
1348
1349 /* Returns true if 'a' and 'b' are the same, false if they differ.
1350  *
1351  * Ignores differences in 'flags' because there's no way to retrieve flags from
1352  * an OpenFlow switch.  We have to assume that they are the same. */
1353 static bool
1354 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
1355 {
1356     return (a->cookie == b->cookie
1357             && a->idle_timeout == b->idle_timeout
1358             && a->hard_timeout == b->hard_timeout
1359             && a->n_actions == b->n_actions
1360             && !memcmp(a->actions, b->actions,
1361                        a->n_actions * sizeof *a->actions));
1362 }
1363
1364 /* Prints 'version' on stdout.  Expects the caller to have printed the rule
1365  * associated with the version. */
1366 static void
1367 fte_version_print(const struct fte_version *version)
1368 {
1369     struct ds s;
1370
1371     if (version->cookie != htonll(0)) {
1372         printf(" cookie=0x%"PRIx64, ntohll(version->cookie));
1373     }
1374     if (version->idle_timeout != OFP_FLOW_PERMANENT) {
1375         printf(" idle_timeout=%"PRIu16, version->idle_timeout);
1376     }
1377     if (version->hard_timeout != OFP_FLOW_PERMANENT) {
1378         printf(" hard_timeout=%"PRIu16, version->hard_timeout);
1379     }
1380
1381     ds_init(&s);
1382     ofp_print_actions(&s, version->actions, version->n_actions);
1383     printf(" %s\n", ds_cstr(&s));
1384     ds_destroy(&s);
1385 }
1386
1387 static struct fte *
1388 fte_from_cls_rule(const struct cls_rule *cls_rule)
1389 {
1390     return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
1391 }
1392
1393 /* Frees 'fte' and its versions. */
1394 static void
1395 fte_free(struct fte *fte)
1396 {
1397     if (fte) {
1398         fte_version_free(fte->versions[0]);
1399         fte_version_free(fte->versions[1]);
1400         free(fte);
1401     }
1402 }
1403
1404 /* Frees all of the FTEs within 'cls'. */
1405 static void
1406 fte_free_all(struct classifier *cls)
1407 {
1408     struct cls_cursor cursor;
1409     struct fte *fte, *next;
1410
1411     cls_cursor_init(&cursor, cls, NULL);
1412     CLS_CURSOR_FOR_EACH_SAFE (fte, next, rule, &cursor) {
1413         classifier_remove(cls, &fte->rule);
1414         fte_free(fte);
1415     }
1416 }
1417
1418 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
1419  * necessary.  Sets 'version' as the version of that rule with the given
1420  * 'index', replacing any existing version, if any.
1421  *
1422  * Takes ownership of 'version'. */
1423 static void
1424 fte_insert(struct classifier *cls, const struct cls_rule *rule,
1425            struct fte_version *version, int index)
1426 {
1427     struct fte *old, *fte;
1428
1429     fte = xzalloc(sizeof *fte);
1430     fte->rule = *rule;
1431     fte->versions[index] = version;
1432
1433     old = fte_from_cls_rule(classifier_replace(cls, &fte->rule));
1434     if (old) {
1435         fte_version_free(old->versions[index]);
1436         fte->versions[!index] = old->versions[!index];
1437         free(old);
1438     }
1439 }
1440
1441 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
1442  * with the specified 'index'.  Returns the flow formats able to represent the
1443  * flows that were read. */
1444 static enum ofputil_protocol
1445 read_flows_from_file(const char *filename, struct classifier *cls, int index)
1446 {
1447     enum ofputil_protocol usable_protocols;
1448     struct ds s;
1449     FILE *file;
1450
1451     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
1452     if (file == NULL) {
1453         ovs_fatal(errno, "%s: open", filename);
1454     }
1455
1456     ds_init(&s);
1457     usable_protocols = OFPUTIL_P_ANY;
1458     while (!ds_get_preprocessed_line(&s, file)) {
1459         struct fte_version *version;
1460         struct ofputil_flow_mod fm;
1461
1462         parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), true);
1463
1464         version = xmalloc(sizeof *version);
1465         version->cookie = fm.cookie;
1466         version->idle_timeout = fm.idle_timeout;
1467         version->hard_timeout = fm.hard_timeout;
1468         version->flags = fm.flags & (OFPFF_SEND_FLOW_REM | OFPFF_EMERG);
1469         version->actions = fm.actions;
1470         version->n_actions = fm.n_actions;
1471
1472         usable_protocols &= ofputil_usable_protocols(&fm.cr);
1473
1474         fte_insert(cls, &fm.cr, version, index);
1475     }
1476     ds_destroy(&s);
1477
1478     if (file != stdin) {
1479         fclose(file);
1480     }
1481
1482     return usable_protocols;
1483 }
1484
1485 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
1486  * format 'protocol', and adds them as flow table entries in 'cls' for the
1487  * version with the specified 'index'. */
1488 static void
1489 read_flows_from_switch(struct vconn *vconn,
1490                        enum ofputil_protocol protocol,
1491                        struct classifier *cls, int index)
1492 {
1493     struct ofputil_flow_stats_request fsr;
1494     struct ofpbuf *request;
1495     ovs_be32 send_xid;
1496     bool done;
1497
1498     fsr.aggregate = false;
1499     cls_rule_init_catchall(&fsr.match, 0);
1500     fsr.out_port = OFPP_NONE;
1501     fsr.table_id = 0xff;
1502     fsr.cookie = fsr.cookie_mask = htonll(0);
1503     request = ofputil_encode_flow_stats_request(&fsr, protocol);
1504     send_xid = ((struct ofp_header *) request->data)->xid;
1505     send_openflow_buffer(vconn, request);
1506
1507     done = false;
1508     while (!done) {
1509         ovs_be32 recv_xid;
1510         struct ofpbuf *reply;
1511
1512         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
1513         recv_xid = ((struct ofp_header *) reply->data)->xid;
1514         if (send_xid == recv_xid) {
1515             const struct ofputil_msg_type *type;
1516             const struct ofp_stats_msg *osm;
1517             enum ofputil_msg_code code;
1518
1519             ofputil_decode_msg_type(reply->data, &type);
1520             code = ofputil_msg_type_code(type);
1521             if (code != OFPUTIL_OFPST_FLOW_REPLY &&
1522                 code != OFPUTIL_NXST_FLOW_REPLY) {
1523                 ovs_fatal(0, "received bad reply: %s",
1524                           ofp_to_string(reply->data, reply->size,
1525                                         verbosity + 1));
1526             }
1527
1528             osm = reply->data;
1529             if (!(osm->flags & htons(OFPSF_REPLY_MORE))) {
1530                 done = true;
1531             }
1532
1533             for (;;) {
1534                 struct fte_version *version;
1535                 struct ofputil_flow_stats fs;
1536                 int retval;
1537
1538                 retval = ofputil_decode_flow_stats_reply(&fs, reply, false);
1539                 if (retval) {
1540                     if (retval != EOF) {
1541                         ovs_fatal(0, "parse error in reply");
1542                     }
1543                     break;
1544                 }
1545
1546                 version = xmalloc(sizeof *version);
1547                 version->cookie = fs.cookie;
1548                 version->idle_timeout = fs.idle_timeout;
1549                 version->hard_timeout = fs.hard_timeout;
1550                 version->flags = 0;
1551                 version->n_actions = fs.n_actions;
1552                 version->actions = xmemdup(fs.actions,
1553                                            fs.n_actions * sizeof *fs.actions);
1554
1555                 fte_insert(cls, &fs.rule, version, index);
1556             }
1557         } else {
1558             VLOG_DBG("received reply with xid %08"PRIx32" "
1559                      "!= expected %08"PRIx32, recv_xid, send_xid);
1560         }
1561         ofpbuf_delete(reply);
1562     }
1563 }
1564
1565 static void
1566 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
1567                   enum ofputil_protocol protocol, struct list *packets)
1568 {
1569     const struct fte_version *version = fte->versions[index];
1570     struct ofputil_flow_mod fm;
1571     struct ofpbuf *ofm;
1572
1573     fm.cr = fte->rule;
1574     fm.cookie = version->cookie;
1575     fm.table_id = 0xff;
1576     fm.command = command;
1577     fm.idle_timeout = version->idle_timeout;
1578     fm.hard_timeout = version->hard_timeout;
1579     fm.buffer_id = UINT32_MAX;
1580     fm.out_port = OFPP_NONE;
1581     fm.flags = version->flags;
1582     if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
1583         command == OFPFC_MODIFY_STRICT) {
1584         fm.actions = version->actions;
1585         fm.n_actions = version->n_actions;
1586     } else {
1587         fm.actions = NULL;
1588         fm.n_actions = 0;
1589     }
1590
1591     ofm = ofputil_encode_flow_mod(&fm, protocol);
1592     list_push_back(packets, &ofm->list_node);
1593 }
1594
1595 static void
1596 do_replace_flows(int argc OVS_UNUSED, char *argv[])
1597 {
1598     enum { FILE_IDX = 0, SWITCH_IDX = 1 };
1599     enum ofputil_protocol usable_protocols, protocol;
1600     struct cls_cursor cursor;
1601     struct classifier cls;
1602     struct list requests;
1603     struct vconn *vconn;
1604     struct fte *fte;
1605
1606     classifier_init(&cls);
1607     usable_protocols = read_flows_from_file(argv[2], &cls, FILE_IDX);
1608
1609     protocol = open_vconn(argv[1], &vconn);
1610     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
1611
1612     read_flows_from_switch(vconn, protocol, &cls, SWITCH_IDX);
1613
1614     list_init(&requests);
1615
1616     /* Delete flows that exist on the switch but not in the file. */
1617     cls_cursor_init(&cursor, &cls, NULL);
1618     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1619         struct fte_version *file_ver = fte->versions[FILE_IDX];
1620         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1621
1622         if (sw_ver && !file_ver) {
1623             fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
1624                               protocol, &requests);
1625         }
1626     }
1627
1628     /* Add flows that exist in the file but not on the switch.
1629      * Update flows that exist in both places but differ. */
1630     cls_cursor_init(&cursor, &cls, NULL);
1631     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1632         struct fte_version *file_ver = fte->versions[FILE_IDX];
1633         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1634
1635         if (file_ver
1636             && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
1637             fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, protocol, &requests);
1638         }
1639     }
1640     transact_multiple_noreply(vconn, &requests);
1641     vconn_close(vconn);
1642
1643     fte_free_all(&cls);
1644 }
1645
1646 static void
1647 read_flows_from_source(const char *source, struct classifier *cls, int index)
1648 {
1649     struct stat s;
1650
1651     if (source[0] == '/' || source[0] == '.'
1652         || (!strchr(source, ':') && !stat(source, &s))) {
1653         read_flows_from_file(source, cls, index);
1654     } else {
1655         enum ofputil_protocol protocol;
1656         struct vconn *vconn;
1657
1658         protocol = open_vconn(source, &vconn);
1659         protocol = set_protocol_for_flow_dump(vconn, protocol, OFPUTIL_P_ANY);
1660         read_flows_from_switch(vconn, protocol, cls, index);
1661         vconn_close(vconn);
1662     }
1663 }
1664
1665 static void
1666 do_diff_flows(int argc OVS_UNUSED, char *argv[])
1667 {
1668     bool differences = false;
1669     struct cls_cursor cursor;
1670     struct classifier cls;
1671     struct fte *fte;
1672
1673     classifier_init(&cls);
1674     read_flows_from_source(argv[1], &cls, 0);
1675     read_flows_from_source(argv[2], &cls, 1);
1676
1677     cls_cursor_init(&cursor, &cls, NULL);
1678     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1679         struct fte_version *a = fte->versions[0];
1680         struct fte_version *b = fte->versions[1];
1681
1682         if (!a || !b || !fte_version_equals(a, b)) {
1683             char *rule_s = cls_rule_to_string(&fte->rule);
1684             if (a) {
1685                 printf("-%s", rule_s);
1686                 fte_version_print(a);
1687             }
1688             if (b) {
1689                 printf("+%s", rule_s);
1690                 fte_version_print(b);
1691             }
1692             free(rule_s);
1693
1694             differences = true;
1695         }
1696     }
1697
1698     fte_free_all(&cls);
1699
1700     if (differences) {
1701         exit(2);
1702     }
1703 }
1704 \f
1705 /* Undocumented commands for unit testing. */
1706
1707 static void
1708 do_parse_flows__(struct ofputil_flow_mod *fms, size_t n_fms)
1709 {
1710     enum ofputil_protocol usable_protocols;
1711     enum ofputil_protocol protocol = 0;
1712     char *usable_s;
1713     size_t i;
1714
1715     usable_protocols = ofputil_flow_mod_usable_protocols(fms, n_fms);
1716     usable_s = ofputil_protocols_to_string(usable_protocols);
1717     printf("usable protocols: %s\n", usable_s);
1718     free(usable_s);
1719
1720     if (!(usable_protocols & allowed_protocols)) {
1721         ovs_fatal(0, "no usable protocol");
1722     }
1723     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1724         protocol = 1 << i;
1725         if (protocol & usable_protocols & allowed_protocols) {
1726             break;
1727         }
1728     }
1729     assert(IS_POW2(protocol));
1730
1731     printf("chosen protocol: %s\n", ofputil_protocol_to_string(protocol));
1732
1733     for (i = 0; i < n_fms; i++) {
1734         struct ofputil_flow_mod *fm = &fms[i];
1735         struct ofpbuf *msg;
1736
1737         msg = ofputil_encode_flow_mod(fm, protocol);
1738         ofp_print(stdout, msg->data, msg->size, verbosity);
1739         ofpbuf_delete(msg);
1740
1741         free(fm->actions);
1742     }
1743 }
1744
1745 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
1746  * it back to stdout.  */
1747 static void
1748 do_parse_flow(int argc OVS_UNUSED, char *argv[])
1749 {
1750     struct ofputil_flow_mod fm;
1751
1752     parse_ofp_flow_mod_str(&fm, argv[1], OFPFC_ADD, false);
1753     do_parse_flows__(&fm, 1);
1754 }
1755
1756 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
1757  * add-flows) and prints each of the flows back to stdout.  */
1758 static void
1759 do_parse_flows(int argc OVS_UNUSED, char *argv[])
1760 {
1761     struct ofputil_flow_mod *fms = NULL;
1762     size_t n_fms = 0;
1763
1764     parse_ofp_flow_mod_file(argv[1], OFPFC_ADD, &fms, &n_fms);
1765     do_parse_flows__(fms, n_fms);
1766     free(fms);
1767 }
1768
1769 /* "parse-nx-match": reads a series of nx_match specifications as strings from
1770  * stdin, does some internal fussing with them, and then prints them back as
1771  * strings on stdout. */
1772 static void
1773 do_parse_nx_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1774 {
1775     struct ds in;
1776
1777     ds_init(&in);
1778     while (!ds_get_line(&in, stdin)) {
1779         struct ofpbuf nx_match;
1780         struct cls_rule rule;
1781         ovs_be64 cookie, cookie_mask;
1782         enum ofperr error;
1783         int match_len;
1784         char *s;
1785
1786         /* Delete comments, skip blank lines. */
1787         s = ds_cstr(&in);
1788         if (*s == '#') {
1789             puts(s);
1790             continue;
1791         }
1792         if (strchr(s, '#')) {
1793             *strchr(s, '#') = '\0';
1794         }
1795         if (s[strspn(s, " ")] == '\0') {
1796             putchar('\n');
1797             continue;
1798         }
1799
1800         /* Convert string to nx_match. */
1801         ofpbuf_init(&nx_match, 0);
1802         match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
1803
1804         /* Convert nx_match to cls_rule. */
1805         if (strict) {
1806             error = nx_pull_match(&nx_match, match_len, 0, &rule,
1807                                   &cookie, &cookie_mask);
1808         } else {
1809             error = nx_pull_match_loose(&nx_match, match_len, 0, &rule,
1810                                         &cookie, &cookie_mask);
1811         }
1812
1813         if (!error) {
1814             char *out;
1815
1816             /* Convert cls_rule back to nx_match. */
1817             ofpbuf_uninit(&nx_match);
1818             ofpbuf_init(&nx_match, 0);
1819             match_len = nx_put_match(&nx_match, &rule, cookie, cookie_mask);
1820
1821             /* Convert nx_match to string. */
1822             out = nx_match_to_string(nx_match.data, match_len);
1823             puts(out);
1824             free(out);
1825         } else {
1826             printf("nx_pull_match() returned error %s\n",
1827                    ofperr_get_name(error));
1828         }
1829
1830         ofpbuf_uninit(&nx_match);
1831     }
1832     ds_destroy(&in);
1833 }
1834
1835 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
1836  * binary data, interpreting them as an OpenFlow message, and prints the
1837  * OpenFlow message on stdout, at VERBOSITY (level 2 by default).  */
1838 static void
1839 do_ofp_print(int argc, char *argv[])
1840 {
1841     struct ofpbuf packet;
1842
1843     ofpbuf_init(&packet, strlen(argv[1]) / 2);
1844     if (ofpbuf_put_hex(&packet, argv[1], NULL)[0] != '\0') {
1845         ovs_fatal(0, "trailing garbage following hex bytes");
1846     }
1847     ofp_print(stdout, packet.data, packet.size, argc > 2 ? atoi(argv[2]) : 2);
1848     ofpbuf_uninit(&packet);
1849 }
1850
1851 static const struct command all_commands[] = {
1852     { "show", 1, 1, do_show },
1853     { "monitor", 1, 3, do_monitor },
1854     { "snoop", 1, 1, do_snoop },
1855     { "dump-desc", 1, 1, do_dump_desc },
1856     { "dump-tables", 1, 1, do_dump_tables },
1857     { "dump-flows", 1, 2, do_dump_flows },
1858     { "dump-aggregate", 1, 2, do_dump_aggregate },
1859     { "queue-stats", 1, 3, do_queue_stats },
1860     { "add-flow", 2, 2, do_add_flow },
1861     { "add-flows", 2, 2, do_add_flows },
1862     { "mod-flows", 2, 2, do_mod_flows },
1863     { "del-flows", 1, 2, do_del_flows },
1864     { "replace-flows", 2, 2, do_replace_flows },
1865     { "diff-flows", 2, 2, do_diff_flows },
1866     { "packet-out", 4, INT_MAX, do_packet_out },
1867     { "dump-ports", 1, 2, do_dump_ports },
1868     { "mod-port", 3, 3, do_mod_port },
1869     { "get-frags", 1, 1, do_get_frags },
1870     { "set-frags", 2, 2, do_set_frags },
1871     { "probe", 1, 1, do_probe },
1872     { "ping", 1, 2, do_ping },
1873     { "benchmark", 3, 3, do_benchmark },
1874     { "help", 0, INT_MAX, do_help },
1875
1876     /* Undocumented commands for testing. */
1877     { "parse-flow", 1, 1, do_parse_flow },
1878     { "parse-flows", 1, 1, do_parse_flows },
1879     { "parse-nx-match", 0, 0, do_parse_nx_match },
1880     { "ofp-print", 1, 2, do_ofp_print },
1881
1882     { NULL, 0, 0, NULL },
1883 };