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