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