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