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