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