ovs-ofctl: Add "packet-out" 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 static void
835 monitor_vconn(struct vconn *vconn)
836 {
837     struct unixctl_server *server;
838     bool exiting = false;
839     int error;
840
841     daemon_save_fd(STDERR_FILENO);
842     daemonize_start();
843     error = unixctl_server_create(NULL, &server);
844     if (error) {
845         ovs_fatal(error, "failed to create unixctl server");
846     }
847     unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
848     daemonize_complete();
849
850     for (;;) {
851         struct ofpbuf *b;
852         int retval;
853
854         unixctl_server_run(server);
855
856         for (;;) {
857             retval = vconn_recv(vconn, &b);
858             if (retval == EAGAIN) {
859                 break;
860             }
861
862             run(retval, "vconn_recv");
863             ofp_print(stderr, b->data, b->size, verbosity + 2);
864             ofpbuf_delete(b);
865         }
866
867         if (exiting) {
868             break;
869         }
870
871         vconn_run(vconn);
872         vconn_run_wait(vconn);
873         vconn_recv_wait(vconn);
874         unixctl_server_wait(server);
875         poll_block();
876     }
877     vconn_close(vconn);
878     unixctl_server_destroy(server);
879 }
880
881 static void
882 do_monitor(int argc, char *argv[])
883 {
884     struct vconn *vconn;
885
886     open_vconn(argv[1], &vconn);
887     if (argc > 2) {
888         struct ofp_switch_config config;
889
890         fetch_switch_config(vconn, &config);
891         config.miss_send_len = htons(atoi(argv[2]));
892         set_switch_config(vconn, &config);
893     }
894     if (argc > 3) {
895         if (!strcmp(argv[3], "invalid_ttl")) {
896             monitor_set_invalid_ttl_to_controller(vconn);
897         }
898     }
899     if (preferred_packet_in_format >= 0) {
900         set_packet_in_format(vconn, preferred_packet_in_format);
901     } else {
902         struct ofpbuf *spif, *reply;
903
904         spif = ofputil_make_set_packet_in_format(NXPIF_NXM);
905         run(vconn_transact_noreply(vconn, spif, &reply),
906             "talking to %s", vconn_get_name(vconn));
907         if (reply) {
908             char *s = ofp_to_string(reply->data, reply->size, 2);
909             VLOG_DBG("%s: failed to set packet in format to nxm, controller"
910                      " replied: %s. Falling back to the switch default.",
911                      vconn_get_name(vconn), s);
912             free(s);
913             ofpbuf_delete(reply);
914         }
915     }
916
917     monitor_vconn(vconn);
918 }
919
920 static void
921 do_snoop(int argc OVS_UNUSED, char *argv[])
922 {
923     struct vconn *vconn;
924
925     open_vconn__(argv[1], "snoop", &vconn);
926     monitor_vconn(vconn);
927 }
928
929 static void
930 do_dump_ports(int argc, char *argv[])
931 {
932     struct ofp_port_stats_request *req;
933     struct ofpbuf *request;
934     uint16_t port;
935
936     req = alloc_stats_request(sizeof *req, OFPST_PORT, &request);
937     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_NONE;
938     req->port_no = htons(port);
939     dump_stats_transaction(argv[1], request);
940 }
941
942 static void
943 do_probe(int argc OVS_UNUSED, char *argv[])
944 {
945     struct ofpbuf *request;
946     struct vconn *vconn;
947     struct ofpbuf *reply;
948
949     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
950     open_vconn(argv[1], &vconn);
951     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
952     if (reply->size != sizeof(struct ofp_header)) {
953         ovs_fatal(0, "reply does not match request");
954     }
955     ofpbuf_delete(reply);
956     vconn_close(vconn);
957 }
958
959 static void
960 do_packet_out(int argc, char *argv[])
961 {
962     struct ofputil_packet_out po;
963     struct ofpbuf actions;
964     struct vconn *vconn;
965     int i;
966
967     ofpbuf_init(&actions, sizeof(union ofp_action));
968     parse_ofp_actions(argv[3], &actions);
969
970     po.buffer_id = UINT32_MAX;
971     po.in_port = (!strcasecmp(argv[2], "none") ? OFPP_NONE
972                   : !strcasecmp(argv[2], "local") ? OFPP_LOCAL
973                   : str_to_port_no(argv[1], argv[2]));
974     po.actions = actions.data;
975     po.n_actions = actions.size / sizeof(union ofp_action);
976
977     open_vconn(argv[1], &vconn);
978     for (i = 4; i < argc; i++) {
979         struct ofpbuf *packet, *opo;
980         const char *error_msg;
981
982         error_msg = eth_from_hex(argv[i], &packet);
983         if (error_msg) {
984             ovs_fatal(0, "%s", error_msg);
985         }
986
987         po.packet = packet->data;
988         po.packet_len = packet->size;
989         opo = ofputil_encode_packet_out(&po);
990         transact_noreply(vconn, opo);
991         ofpbuf_delete(packet);
992     }
993     vconn_close(vconn);
994 }
995
996 static void
997 do_mod_port(int argc OVS_UNUSED, char *argv[])
998 {
999     struct ofp_port_mod *opm;
1000     struct ofp_phy_port opp;
1001     struct ofpbuf *request;
1002     struct vconn *vconn;
1003
1004     fetch_ofp_phy_port(argv[1], argv[2], &opp);
1005
1006     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
1007     opm->port_no = opp.port_no;
1008     memcpy(opm->hw_addr, opp.hw_addr, sizeof opm->hw_addr);
1009     opm->config = htonl(0);
1010     opm->mask = htonl(0);
1011     opm->advertise = htonl(0);
1012
1013     if (!strcasecmp(argv[3], "up")) {
1014         opm->mask |= htonl(OFPPC_PORT_DOWN);
1015     } else if (!strcasecmp(argv[3], "down")) {
1016         opm->mask |= htonl(OFPPC_PORT_DOWN);
1017         opm->config |= htonl(OFPPC_PORT_DOWN);
1018     } else if (!strcasecmp(argv[3], "flood")) {
1019         opm->mask |= htonl(OFPPC_NO_FLOOD);
1020     } else if (!strcasecmp(argv[3], "noflood")) {
1021         opm->mask |= htonl(OFPPC_NO_FLOOD);
1022         opm->config |= htonl(OFPPC_NO_FLOOD);
1023     } else if (!strcasecmp(argv[3], "forward")) {
1024         opm->mask |= htonl(OFPPC_NO_FWD);
1025     } else if (!strcasecmp(argv[3], "noforward")) {
1026         opm->mask |= htonl(OFPPC_NO_FWD);
1027         opm->config |= htonl(OFPPC_NO_FWD);
1028     } else {
1029         ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1030     }
1031
1032     open_vconn(argv[1], &vconn);
1033     transact_noreply(vconn, request);
1034     vconn_close(vconn);
1035 }
1036
1037 static void
1038 do_get_frags(int argc OVS_UNUSED, char *argv[])
1039 {
1040     struct ofp_switch_config config;
1041     struct vconn *vconn;
1042
1043     open_vconn(argv[1], &vconn);
1044     fetch_switch_config(vconn, &config);
1045     puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
1046     vconn_close(vconn);
1047 }
1048
1049 static void
1050 do_set_frags(int argc OVS_UNUSED, char *argv[])
1051 {
1052     struct ofp_switch_config config;
1053     enum ofp_config_flags mode;
1054     struct vconn *vconn;
1055     ovs_be16 flags;
1056
1057     if (!ofputil_frag_handling_from_string(argv[2], &mode)) {
1058         ovs_fatal(0, "%s: unknown fragment handling mode", argv[2]);
1059     }
1060
1061     open_vconn(argv[1], &vconn);
1062     fetch_switch_config(vconn, &config);
1063     flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
1064     if (flags != config.flags) {
1065         /* Set the configuration. */
1066         config.flags = flags;
1067         set_switch_config(vconn, &config);
1068
1069         /* Then retrieve the configuration to see if it really took.  OpenFlow
1070          * doesn't define error reporting for bad modes, so this is all we can
1071          * do. */
1072         fetch_switch_config(vconn, &config);
1073         if (flags != config.flags) {
1074             ovs_fatal(0, "%s: setting fragment handling mode failed (this "
1075                       "switch probably doesn't support mode \"%s\")",
1076                       argv[1], ofputil_frag_handling_to_string(mode));
1077         }
1078     }
1079     vconn_close(vconn);
1080 }
1081
1082 static void
1083 do_ping(int argc, char *argv[])
1084 {
1085     size_t max_payload = 65535 - sizeof(struct ofp_header);
1086     unsigned int payload;
1087     struct vconn *vconn;
1088     int i;
1089
1090     payload = argc > 2 ? atoi(argv[2]) : 64;
1091     if (payload > max_payload) {
1092         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1093     }
1094
1095     open_vconn(argv[1], &vconn);
1096     for (i = 0; i < 10; i++) {
1097         struct timeval start, end;
1098         struct ofpbuf *request, *reply;
1099         struct ofp_header *rq_hdr, *rpy_hdr;
1100
1101         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1102                                OFPT_ECHO_REQUEST, &request);
1103         random_bytes(rq_hdr + 1, payload);
1104
1105         xgettimeofday(&start);
1106         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1107         xgettimeofday(&end);
1108
1109         rpy_hdr = reply->data;
1110         if (reply->size != request->size
1111             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1112             || rpy_hdr->xid != rq_hdr->xid
1113             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1114             printf("Reply does not match request.  Request:\n");
1115             ofp_print(stdout, request, request->size, verbosity + 2);
1116             printf("Reply:\n");
1117             ofp_print(stdout, reply, reply->size, verbosity + 2);
1118         }
1119         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1120                reply->size - sizeof *rpy_hdr, argv[1], ntohl(rpy_hdr->xid),
1121                    (1000*(double)(end.tv_sec - start.tv_sec))
1122                    + (.001*(end.tv_usec - start.tv_usec)));
1123         ofpbuf_delete(request);
1124         ofpbuf_delete(reply);
1125     }
1126     vconn_close(vconn);
1127 }
1128
1129 static void
1130 do_benchmark(int argc OVS_UNUSED, char *argv[])
1131 {
1132     size_t max_payload = 65535 - sizeof(struct ofp_header);
1133     struct timeval start, end;
1134     unsigned int payload_size, message_size;
1135     struct vconn *vconn;
1136     double duration;
1137     int count;
1138     int i;
1139
1140     payload_size = atoi(argv[2]);
1141     if (payload_size > max_payload) {
1142         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1143     }
1144     message_size = sizeof(struct ofp_header) + payload_size;
1145
1146     count = atoi(argv[3]);
1147
1148     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1149            count, message_size, count * message_size);
1150
1151     open_vconn(argv[1], &vconn);
1152     xgettimeofday(&start);
1153     for (i = 0; i < count; i++) {
1154         struct ofpbuf *request, *reply;
1155         struct ofp_header *rq_hdr;
1156
1157         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1158         memset(rq_hdr + 1, 0, payload_size);
1159         run(vconn_transact(vconn, request, &reply), "transact");
1160         ofpbuf_delete(reply);
1161     }
1162     xgettimeofday(&end);
1163     vconn_close(vconn);
1164
1165     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1166                 + (.001*(end.tv_usec - start.tv_usec)));
1167     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1168            duration, count / (duration / 1000.0),
1169            count * message_size / (duration / 1000.0));
1170 }
1171
1172 static void
1173 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1174 {
1175     usage();
1176 }
1177 \f
1178 /* replace-flows and diff-flows commands. */
1179
1180 /* A flow table entry, possibly with two different versions. */
1181 struct fte {
1182     struct cls_rule rule;       /* Within a "struct classifier". */
1183     struct fte_version *versions[2];
1184 };
1185
1186 /* One version of a Flow Table Entry. */
1187 struct fte_version {
1188     ovs_be64 cookie;
1189     uint16_t idle_timeout;
1190     uint16_t hard_timeout;
1191     uint16_t flags;
1192     union ofp_action *actions;
1193     size_t n_actions;
1194 };
1195
1196 /* Frees 'version' and the data that it owns. */
1197 static void
1198 fte_version_free(struct fte_version *version)
1199 {
1200     if (version) {
1201         free(version->actions);
1202         free(version);
1203     }
1204 }
1205
1206 /* Returns true if 'a' and 'b' are the same, false if they differ.
1207  *
1208  * Ignores differences in 'flags' because there's no way to retrieve flags from
1209  * an OpenFlow switch.  We have to assume that they are the same. */
1210 static bool
1211 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
1212 {
1213     return (a->cookie == b->cookie
1214             && a->idle_timeout == b->idle_timeout
1215             && a->hard_timeout == b->hard_timeout
1216             && a->n_actions == b->n_actions
1217             && !memcmp(a->actions, b->actions,
1218                        a->n_actions * sizeof *a->actions));
1219 }
1220
1221 /* Prints 'version' on stdout.  Expects the caller to have printed the rule
1222  * associated with the version. */
1223 static void
1224 fte_version_print(const struct fte_version *version)
1225 {
1226     struct ds s;
1227
1228     if (version->cookie != htonll(0)) {
1229         printf(" cookie=0x%"PRIx64, ntohll(version->cookie));
1230     }
1231     if (version->idle_timeout != OFP_FLOW_PERMANENT) {
1232         printf(" idle_timeout=%"PRIu16, version->idle_timeout);
1233     }
1234     if (version->hard_timeout != OFP_FLOW_PERMANENT) {
1235         printf(" hard_timeout=%"PRIu16, version->hard_timeout);
1236     }
1237
1238     ds_init(&s);
1239     ofp_print_actions(&s, version->actions, version->n_actions);
1240     printf(" %s\n", ds_cstr(&s));
1241     ds_destroy(&s);
1242 }
1243
1244 static struct fte *
1245 fte_from_cls_rule(const struct cls_rule *cls_rule)
1246 {
1247     return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
1248 }
1249
1250 /* Frees 'fte' and its versions. */
1251 static void
1252 fte_free(struct fte *fte)
1253 {
1254     if (fte) {
1255         fte_version_free(fte->versions[0]);
1256         fte_version_free(fte->versions[1]);
1257         free(fte);
1258     }
1259 }
1260
1261 /* Frees all of the FTEs within 'cls'. */
1262 static void
1263 fte_free_all(struct classifier *cls)
1264 {
1265     struct cls_cursor cursor;
1266     struct fte *fte, *next;
1267
1268     cls_cursor_init(&cursor, cls, NULL);
1269     CLS_CURSOR_FOR_EACH_SAFE (fte, next, rule, &cursor) {
1270         classifier_remove(cls, &fte->rule);
1271         fte_free(fte);
1272     }
1273 }
1274
1275 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
1276  * necessary.  Sets 'version' as the version of that rule with the given
1277  * 'index', replacing any existing version, if any.
1278  *
1279  * Takes ownership of 'version'. */
1280 static void
1281 fte_insert(struct classifier *cls, const struct cls_rule *rule,
1282            struct fte_version *version, int index)
1283 {
1284     struct fte *old, *fte;
1285
1286     fte = xzalloc(sizeof *fte);
1287     fte->rule = *rule;
1288     fte->versions[index] = version;
1289
1290     old = fte_from_cls_rule(classifier_replace(cls, &fte->rule));
1291     if (old) {
1292         fte_version_free(old->versions[index]);
1293         fte->versions[!index] = old->versions[!index];
1294         free(old);
1295     }
1296 }
1297
1298 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
1299  * with the specified 'index'.  Returns the minimum flow format required to
1300  * represent the flows that were read. */
1301 static enum nx_flow_format
1302 read_flows_from_file(const char *filename, struct classifier *cls, int index)
1303 {
1304     enum nx_flow_format min_flow_format;
1305     struct ds s;
1306     FILE *file;
1307
1308     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
1309     if (file == NULL) {
1310         ovs_fatal(errno, "%s: open", filename);
1311     }
1312
1313     ds_init(&s);
1314     min_flow_format = NXFF_OPENFLOW10;
1315     while (!ds_get_preprocessed_line(&s, file)) {
1316         struct fte_version *version;
1317         struct ofputil_flow_mod fm;
1318         enum nx_flow_format min_ff;
1319
1320         parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), true);
1321
1322         version = xmalloc(sizeof *version);
1323         version->cookie = fm.cookie;
1324         version->idle_timeout = fm.idle_timeout;
1325         version->hard_timeout = fm.hard_timeout;
1326         version->flags = fm.flags & (OFPFF_SEND_FLOW_REM | OFPFF_EMERG);
1327         version->actions = fm.actions;
1328         version->n_actions = fm.n_actions;
1329
1330         min_ff = ofputil_min_flow_format(&fm.cr);
1331         min_flow_format = MAX(min_flow_format, min_ff);
1332         check_final_format_for_flow_mod(min_flow_format);
1333
1334         fte_insert(cls, &fm.cr, version, index);
1335     }
1336     ds_destroy(&s);
1337
1338     if (file != stdin) {
1339         fclose(file);
1340     }
1341
1342     return min_flow_format;
1343 }
1344
1345 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
1346  * format 'flow_format', and adds them as flow table entries in 'cls' for the
1347  * version with the specified 'index'. */
1348 static void
1349 read_flows_from_switch(struct vconn *vconn, enum nx_flow_format flow_format,
1350                        struct classifier *cls, int index)
1351 {
1352     struct ofputil_flow_stats_request fsr;
1353     struct ofpbuf *request;
1354     ovs_be32 send_xid;
1355     bool done;
1356
1357     fsr.aggregate = false;
1358     cls_rule_init_catchall(&fsr.match, 0);
1359     fsr.out_port = OFPP_NONE;
1360     fsr.table_id = 0xff;
1361     fsr.cookie = fsr.cookie_mask = htonll(0);
1362     request = ofputil_encode_flow_stats_request(&fsr, flow_format);
1363     send_xid = ((struct ofp_header *) request->data)->xid;
1364     send_openflow_buffer(vconn, request);
1365
1366     done = false;
1367     while (!done) {
1368         ovs_be32 recv_xid;
1369         struct ofpbuf *reply;
1370
1371         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
1372         recv_xid = ((struct ofp_header *) reply->data)->xid;
1373         if (send_xid == recv_xid) {
1374             const struct ofputil_msg_type *type;
1375             const struct ofp_stats_msg *osm;
1376             enum ofputil_msg_code code;
1377
1378             ofputil_decode_msg_type(reply->data, &type);
1379             code = ofputil_msg_type_code(type);
1380             if (code != OFPUTIL_OFPST_FLOW_REPLY &&
1381                 code != OFPUTIL_NXST_FLOW_REPLY) {
1382                 ovs_fatal(0, "received bad reply: %s",
1383                           ofp_to_string(reply->data, reply->size,
1384                                         verbosity + 1));
1385             }
1386
1387             osm = reply->data;
1388             if (!(osm->flags & htons(OFPSF_REPLY_MORE))) {
1389                 done = true;
1390             }
1391
1392             for (;;) {
1393                 struct fte_version *version;
1394                 struct ofputil_flow_stats fs;
1395                 int retval;
1396
1397                 retval = ofputil_decode_flow_stats_reply(&fs, reply, false);
1398                 if (retval) {
1399                     if (retval != EOF) {
1400                         ovs_fatal(0, "parse error in reply");
1401                     }
1402                     break;
1403                 }
1404
1405                 version = xmalloc(sizeof *version);
1406                 version->cookie = fs.cookie;
1407                 version->idle_timeout = fs.idle_timeout;
1408                 version->hard_timeout = fs.hard_timeout;
1409                 version->flags = 0;
1410                 version->n_actions = fs.n_actions;
1411                 version->actions = xmemdup(fs.actions,
1412                                            fs.n_actions * sizeof *fs.actions);
1413
1414                 fte_insert(cls, &fs.rule, version, index);
1415             }
1416         } else {
1417             VLOG_DBG("received reply with xid %08"PRIx32" "
1418                      "!= expected %08"PRIx32, recv_xid, send_xid);
1419         }
1420         ofpbuf_delete(reply);
1421     }
1422 }
1423
1424 static void
1425 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
1426                   enum nx_flow_format flow_format, struct list *packets)
1427 {
1428     const struct fte_version *version = fte->versions[index];
1429     struct ofputil_flow_mod fm;
1430     struct ofpbuf *ofm;
1431
1432     fm.cr = fte->rule;
1433     fm.cookie = version->cookie;
1434     fm.table_id = 0xff;
1435     fm.command = command;
1436     fm.idle_timeout = version->idle_timeout;
1437     fm.hard_timeout = version->hard_timeout;
1438     fm.buffer_id = UINT32_MAX;
1439     fm.out_port = OFPP_NONE;
1440     fm.flags = version->flags;
1441     if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
1442         command == OFPFC_MODIFY_STRICT) {
1443         fm.actions = version->actions;
1444         fm.n_actions = version->n_actions;
1445     } else {
1446         fm.actions = NULL;
1447         fm.n_actions = 0;
1448     }
1449
1450     ofm = ofputil_encode_flow_mod(&fm, flow_format, false);
1451     list_push_back(packets, &ofm->list_node);
1452 }
1453
1454 static void
1455 do_replace_flows(int argc OVS_UNUSED, char *argv[])
1456 {
1457     enum { FILE_IDX = 0, SWITCH_IDX = 1 };
1458     enum nx_flow_format min_flow_format, flow_format;
1459     struct cls_cursor cursor;
1460     struct classifier cls;
1461     struct list requests;
1462     struct vconn *vconn;
1463     struct fte *fte;
1464
1465     classifier_init(&cls);
1466     min_flow_format = read_flows_from_file(argv[2], &cls, FILE_IDX);
1467
1468     open_vconn(argv[1], &vconn);
1469     flow_format = negotiate_highest_flow_format(vconn, min_flow_format);
1470     read_flows_from_switch(vconn, flow_format, &cls, SWITCH_IDX);
1471
1472     list_init(&requests);
1473
1474     /* Delete flows that exist on the switch but not in the file. */
1475     cls_cursor_init(&cursor, &cls, NULL);
1476     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1477         struct fte_version *file_ver = fte->versions[FILE_IDX];
1478         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1479
1480         if (sw_ver && !file_ver) {
1481             fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
1482                               flow_format, &requests);
1483         }
1484     }
1485
1486     /* Add flows that exist in the file but not on the switch.
1487      * Update flows that exist in both places but differ. */
1488     cls_cursor_init(&cursor, &cls, NULL);
1489     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1490         struct fte_version *file_ver = fte->versions[FILE_IDX];
1491         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
1492
1493         if (file_ver
1494             && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
1495             fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, flow_format,
1496                               &requests);
1497         }
1498     }
1499     transact_multiple_noreply(vconn, &requests);
1500     vconn_close(vconn);
1501
1502     fte_free_all(&cls);
1503 }
1504
1505 static void
1506 read_flows_from_source(const char *source, struct classifier *cls, int index)
1507 {
1508     struct stat s;
1509
1510     if (source[0] == '/' || source[0] == '.'
1511         || (!strchr(source, ':') && !stat(source, &s))) {
1512         read_flows_from_file(source, cls, index);
1513     } else {
1514         enum nx_flow_format flow_format;
1515         struct vconn *vconn;
1516
1517         open_vconn(source, &vconn);
1518         flow_format = negotiate_highest_flow_format(vconn, NXFF_OPENFLOW10);
1519         read_flows_from_switch(vconn, flow_format, cls, index);
1520         vconn_close(vconn);
1521     }
1522 }
1523
1524 static void
1525 do_diff_flows(int argc OVS_UNUSED, char *argv[])
1526 {
1527     bool differences = false;
1528     struct cls_cursor cursor;
1529     struct classifier cls;
1530     struct fte *fte;
1531
1532     classifier_init(&cls);
1533     read_flows_from_source(argv[1], &cls, 0);
1534     read_flows_from_source(argv[2], &cls, 1);
1535
1536     cls_cursor_init(&cursor, &cls, NULL);
1537     CLS_CURSOR_FOR_EACH (fte, rule, &cursor) {
1538         struct fte_version *a = fte->versions[0];
1539         struct fte_version *b = fte->versions[1];
1540
1541         if (!a || !b || !fte_version_equals(a, b)) {
1542             char *rule_s = cls_rule_to_string(&fte->rule);
1543             if (a) {
1544                 printf("-%s", rule_s);
1545                 fte_version_print(a);
1546             }
1547             if (b) {
1548                 printf("+%s", rule_s);
1549                 fte_version_print(b);
1550             }
1551             free(rule_s);
1552
1553             differences = true;
1554         }
1555     }
1556
1557     fte_free_all(&cls);
1558
1559     if (differences) {
1560         exit(2);
1561     }
1562 }
1563 \f
1564 /* Undocumented commands for unit testing. */
1565
1566 static void
1567 print_packet_list(struct list *packets)
1568 {
1569     struct ofpbuf *packet, *next;
1570
1571     LIST_FOR_EACH_SAFE (packet, next, list_node, packets) {
1572         ofp_print(stdout, packet->data, packet->size, verbosity);
1573         list_remove(&packet->list_node);
1574         ofpbuf_delete(packet);
1575     }
1576 }
1577
1578 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
1579  * it back to stdout.  */
1580 static void
1581 do_parse_flow(int argc OVS_UNUSED, char *argv[])
1582 {
1583     enum nx_flow_format flow_format;
1584     bool flow_mod_table_id;
1585     struct list packets;
1586
1587     flow_format = NXFF_OPENFLOW10;
1588     if (preferred_flow_format > 0) {
1589         flow_format = preferred_flow_format;
1590     }
1591     flow_mod_table_id = false;
1592
1593     list_init(&packets);
1594     parse_ofp_flow_mod_str(&packets, &flow_format, &flow_mod_table_id,
1595                            argv[1], OFPFC_ADD, false);
1596     print_packet_list(&packets);
1597 }
1598
1599 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
1600  * add-flows) and prints each of the flows back to stdout.  */
1601 static void
1602 do_parse_flows(int argc OVS_UNUSED, char *argv[])
1603 {
1604     enum nx_flow_format flow_format;
1605     bool flow_mod_table_id;
1606     struct list packets;
1607     FILE *file;
1608
1609     file = fopen(argv[1], "r");
1610     if (file == NULL) {
1611         ovs_fatal(errno, "%s: open", argv[1]);
1612     }
1613
1614     flow_format = NXFF_OPENFLOW10;
1615     if (preferred_flow_format > 0) {
1616         flow_format = preferred_flow_format;
1617     }
1618     flow_mod_table_id = false;
1619
1620     list_init(&packets);
1621     while (parse_ofp_flow_mod_file(&packets, &flow_format, &flow_mod_table_id,
1622                                    file, OFPFC_ADD)) {
1623         print_packet_list(&packets);
1624     }
1625     fclose(file);
1626 }
1627
1628 /* "parse-nx-match": reads a series of nx_match specifications as strings from
1629  * stdin, does some internal fussing with them, and then prints them back as
1630  * strings on stdout. */
1631 static void
1632 do_parse_nx_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1633 {
1634     struct ds in;
1635
1636     ds_init(&in);
1637     while (!ds_get_line(&in, stdin)) {
1638         struct ofpbuf nx_match;
1639         struct cls_rule rule;
1640         ovs_be64 cookie, cookie_mask;
1641         enum ofperr error;
1642         int match_len;
1643         char *s;
1644
1645         /* Delete comments, skip blank lines. */
1646         s = ds_cstr(&in);
1647         if (*s == '#') {
1648             puts(s);
1649             continue;
1650         }
1651         if (strchr(s, '#')) {
1652             *strchr(s, '#') = '\0';
1653         }
1654         if (s[strspn(s, " ")] == '\0') {
1655             putchar('\n');
1656             continue;
1657         }
1658
1659         /* Convert string to nx_match. */
1660         ofpbuf_init(&nx_match, 0);
1661         match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
1662
1663         /* Convert nx_match to cls_rule. */
1664         if (strict) {
1665             error = nx_pull_match(&nx_match, match_len, 0, &rule,
1666                                   &cookie, &cookie_mask);
1667         } else {
1668             error = nx_pull_match_loose(&nx_match, match_len, 0, &rule,
1669                                         &cookie, &cookie_mask);
1670         }
1671
1672         if (!error) {
1673             char *out;
1674
1675             /* Convert cls_rule back to nx_match. */
1676             ofpbuf_uninit(&nx_match);
1677             ofpbuf_init(&nx_match, 0);
1678             match_len = nx_put_match(&nx_match, &rule, cookie, cookie_mask);
1679
1680             /* Convert nx_match to string. */
1681             out = nx_match_to_string(nx_match.data, match_len);
1682             puts(out);
1683             free(out);
1684         } else {
1685             printf("nx_pull_match() returned error %s\n",
1686                    ofperr_get_name(error));
1687         }
1688
1689         ofpbuf_uninit(&nx_match);
1690     }
1691     ds_destroy(&in);
1692 }
1693
1694 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
1695  * binary data, interpreting them as an OpenFlow message, and prints the
1696  * OpenFlow message on stdout, at VERBOSITY (level 2 by default).  */
1697 static void
1698 do_ofp_print(int argc, char *argv[])
1699 {
1700     struct ofpbuf packet;
1701
1702     ofpbuf_init(&packet, strlen(argv[1]) / 2);
1703     if (ofpbuf_put_hex(&packet, argv[1], NULL)[0] != '\0') {
1704         ovs_fatal(0, "trailing garbage following hex bytes");
1705     }
1706     ofp_print(stdout, packet.data, packet.size, argc > 2 ? atoi(argv[2]) : 2);
1707     ofpbuf_uninit(&packet);
1708 }
1709
1710 static const struct command all_commands[] = {
1711     { "show", 1, 1, do_show },
1712     { "monitor", 1, 3, do_monitor },
1713     { "snoop", 1, 1, do_snoop },
1714     { "dump-desc", 1, 1, do_dump_desc },
1715     { "dump-tables", 1, 1, do_dump_tables },
1716     { "dump-flows", 1, 2, do_dump_flows },
1717     { "dump-aggregate", 1, 2, do_dump_aggregate },
1718     { "queue-stats", 1, 3, do_queue_stats },
1719     { "add-flow", 2, 2, do_add_flow },
1720     { "add-flows", 2, 2, do_add_flows },
1721     { "mod-flows", 2, 2, do_mod_flows },
1722     { "del-flows", 1, 2, do_del_flows },
1723     { "replace-flows", 2, 2, do_replace_flows },
1724     { "diff-flows", 2, 2, do_diff_flows },
1725     { "packet-out", 4, INT_MAX, do_packet_out },
1726     { "dump-ports", 1, 2, do_dump_ports },
1727     { "mod-port", 3, 3, do_mod_port },
1728     { "get-frags", 1, 1, do_get_frags },
1729     { "set-frags", 2, 2, do_set_frags },
1730     { "probe", 1, 1, do_probe },
1731     { "ping", 1, 2, do_ping },
1732     { "benchmark", 3, 3, do_benchmark },
1733     { "help", 0, INT_MAX, do_help },
1734
1735     /* Undocumented commands for testing. */
1736     { "parse-flow", 1, 1, do_parse_flow },
1737     { "parse-flows", 1, 1, do_parse_flows },
1738     { "parse-nx-match", 0, 0, do_parse_nx_match },
1739     { "ofp-print", 1, 2, do_ofp_print },
1740
1741     { NULL, 0, 0, NULL },
1742 };