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