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