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