ovs-ofctl: Fix replace-flows.
[cascardo/ovs.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
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 <ctype.h>
19 #include <errno.h>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <sys/socket.h>
23 #include <net/if.h>
24 #include <signal.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31
32 #include "byte-order.h"
33 #include "classifier.h"
34 #include "command-line.h"
35 #include "daemon.h"
36 #include "compiler.h"
37 #include "dirs.h"
38 #include "dynamic-string.h"
39 #include "fatal-signal.h"
40 #include "nx-match.h"
41 #include "odp-util.h"
42 #include "ofp-actions.h"
43 #include "ofp-errors.h"
44 #include "ofp-msgs.h"
45 #include "ofp-parse.h"
46 #include "ofp-print.h"
47 #include "ofp-util.h"
48 #include "ofp-version-opt.h"
49 #include "ofpbuf.h"
50 #include "ofproto/ofproto.h"
51 #include "openflow/nicira-ext.h"
52 #include "openflow/openflow.h"
53 #include "dp-packet.h"
54 #include "packets.h"
55 #include "pcap-file.h"
56 #include "poll-loop.h"
57 #include "random.h"
58 #include "stream-ssl.h"
59 #include "socket-util.h"
60 #include "timeval.h"
61 #include "unixctl.h"
62 #include "util.h"
63 #include "openvswitch/vconn.h"
64 #include "openvswitch/vlog.h"
65 #include "meta-flow.h"
66 #include "sort.h"
67
68 VLOG_DEFINE_THIS_MODULE(ofctl);
69
70 /* --bundle: Use OpenFlow 1.4 bundle for making the flow table change atomic.
71  * NOTE: Also the flow mod will use OpenFlow 1.4, so the semantics may be
72  * different (see the comment in parse_options() for details).
73  */
74 static bool bundle = false;
75
76 /* --strict: Use strict matching for flow mod commands?  Additionally governs
77  * use of nx_pull_match() instead of nx_pull_match_loose() in parse-nx-match.
78  */
79 static bool strict;
80
81 /* --readd: If true, on replace-flows, re-add even flows that have not changed
82  * (to reset flow counters). */
83 static bool readd;
84
85 /* -F, --flow-format: Allowed protocols.  By default, any protocol is
86  * allowed. */
87 static enum ofputil_protocol allowed_protocols = OFPUTIL_P_ANY;
88
89 /* -P, --packet-in-format: Packet IN format to use in monitor and snoop
90  * commands.  Either one of NXPIF_* to force a particular packet_in format, or
91  * -1 to let ovs-ofctl choose the default. */
92 static int preferred_packet_in_format = -1;
93
94 /* -m, --more: Additional verbosity for ofp-print functions. */
95 static int verbosity;
96
97 /* --timestamp: Print a timestamp before each received packet on "monitor" and
98  * "snoop" command? */
99 static bool timestamp;
100
101 /* --unixctl-path: Path to use for unixctl server, for "monitor" and "snoop"
102      commands. */
103 static char *unixctl_path;
104
105 /* --sort, --rsort: Sort order. */
106 enum sort_order { SORT_ASC, SORT_DESC };
107 struct sort_criterion {
108     const struct mf_field *field; /* NULL means to sort by priority. */
109     enum sort_order order;
110 };
111 static struct sort_criterion *criteria;
112 static size_t n_criteria, allocated_criteria;
113
114 static const struct ovs_cmdl_command *get_all_commands(void);
115
116 OVS_NO_RETURN static void usage(void);
117 static void parse_options(int argc, char *argv[]);
118
119 static bool recv_flow_stats_reply(struct vconn *, ovs_be32 send_xid,
120                                   struct ofpbuf **replyp,
121                                   struct ofputil_flow_stats *,
122                                   struct ofpbuf *ofpacts);
123 int
124 main(int argc, char *argv[])
125 {
126     struct ovs_cmdl_context ctx = { .argc = 0, };
127     set_program_name(argv[0]);
128     service_start(&argc, &argv);
129     parse_options(argc, argv);
130     fatal_ignore_sigpipe();
131     ctx.argc = argc - optind;
132     ctx.argv = argv + optind;
133
134     daemon_become_new_user(false);
135     ovs_cmdl_run_command(&ctx, get_all_commands());
136     return 0;
137 }
138
139 static void
140 add_sort_criterion(enum sort_order order, const char *field)
141 {
142     struct sort_criterion *sc;
143
144     if (n_criteria >= allocated_criteria) {
145         criteria = x2nrealloc(criteria, &allocated_criteria, sizeof *criteria);
146     }
147
148     sc = &criteria[n_criteria++];
149     if (!field || !strcasecmp(field, "priority")) {
150         sc->field = NULL;
151     } else {
152         sc->field = mf_from_name(field);
153         if (!sc->field) {
154             ovs_fatal(0, "%s: unknown field name", field);
155         }
156     }
157     sc->order = order;
158 }
159
160 static void
161 parse_options(int argc, char *argv[])
162 {
163     enum {
164         OPT_STRICT = UCHAR_MAX + 1,
165         OPT_READD,
166         OPT_TIMESTAMP,
167         OPT_SORT,
168         OPT_RSORT,
169         OPT_UNIXCTL,
170         OPT_BUNDLE,
171         DAEMON_OPTION_ENUMS,
172         OFP_VERSION_OPTION_ENUMS,
173         VLOG_OPTION_ENUMS
174     };
175     static const struct option long_options[] = {
176         {"timeout", required_argument, NULL, 't'},
177         {"strict", no_argument, NULL, OPT_STRICT},
178         {"readd", no_argument, NULL, OPT_READD},
179         {"flow-format", required_argument, NULL, 'F'},
180         {"packet-in-format", required_argument, NULL, 'P'},
181         {"more", no_argument, NULL, 'm'},
182         {"timestamp", no_argument, NULL, OPT_TIMESTAMP},
183         {"sort", optional_argument, NULL, OPT_SORT},
184         {"rsort", optional_argument, NULL, OPT_RSORT},
185         {"unixctl",     required_argument, NULL, OPT_UNIXCTL},
186         {"help", no_argument, NULL, 'h'},
187         {"option", no_argument, NULL, 'o'},
188         {"bundle", no_argument, NULL, OPT_BUNDLE},
189         DAEMON_LONG_OPTIONS,
190         OFP_VERSION_LONG_OPTIONS,
191         VLOG_LONG_OPTIONS,
192         STREAM_SSL_LONG_OPTIONS,
193         {NULL, 0, NULL, 0},
194     };
195     char *short_options = ovs_cmdl_long_options_to_short_options(long_options);
196     uint32_t versions;
197     enum ofputil_protocol version_protocols;
198
199     /* For now, ovs-ofctl only enables OpenFlow 1.0 by default.  This is
200      * because ovs-ofctl implements command such as "add-flow" as raw OpenFlow
201      * requests, but those requests have subtly different semantics in
202      * different OpenFlow versions.  For example:
203      *
204      *     - In OpenFlow 1.0, a "mod-flow" operation that does not find any
205      *       existing flow to modify adds a new flow.
206      *
207      *     - In OpenFlow 1.1, a "mod-flow" operation that does not find any
208      *       existing flow to modify adds a new flow, but only if the mod-flow
209      *       did not match on the flow cookie.
210      *
211      *     - In OpenFlow 1.2 and a later, a "mod-flow" operation never adds a
212      *       new flow.
213      */
214     set_allowed_ofp_versions("OpenFlow10");
215
216     for (;;) {
217         unsigned long int timeout;
218         int c;
219
220         c = getopt_long(argc, argv, short_options, long_options, NULL);
221         if (c == -1) {
222             break;
223         }
224
225         switch (c) {
226         case 't':
227             timeout = strtoul(optarg, NULL, 10);
228             if (timeout <= 0) {
229                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
230                           optarg);
231             } else {
232                 time_alarm(timeout);
233             }
234             break;
235
236         case 'F':
237             allowed_protocols = ofputil_protocols_from_string(optarg);
238             if (!allowed_protocols) {
239                 ovs_fatal(0, "%s: invalid flow format(s)", optarg);
240             }
241             break;
242
243         case 'P':
244             preferred_packet_in_format =
245                 ofputil_packet_in_format_from_string(optarg);
246             if (preferred_packet_in_format < 0) {
247                 ovs_fatal(0, "unknown packet-in format `%s'", optarg);
248             }
249             break;
250
251         case 'm':
252             verbosity++;
253             break;
254
255         case 'h':
256             usage();
257
258         case 'o':
259             ovs_cmdl_print_options(long_options);
260             exit(EXIT_SUCCESS);
261
262         case OPT_BUNDLE:
263             bundle = true;
264             break;
265
266         case OPT_STRICT:
267             strict = true;
268             break;
269
270         case OPT_READD:
271             readd = true;
272             break;
273
274         case OPT_TIMESTAMP:
275             timestamp = true;
276             break;
277
278         case OPT_SORT:
279             add_sort_criterion(SORT_ASC, optarg);
280             break;
281
282         case OPT_RSORT:
283             add_sort_criterion(SORT_DESC, optarg);
284             break;
285
286         case OPT_UNIXCTL:
287             unixctl_path = optarg;
288             break;
289
290         DAEMON_OPTION_HANDLERS
291         OFP_VERSION_OPTION_HANDLERS
292         VLOG_OPTION_HANDLERS
293         STREAM_SSL_OPTION_HANDLERS
294
295         case '?':
296             exit(EXIT_FAILURE);
297
298         default:
299             abort();
300         }
301     }
302
303     if (n_criteria) {
304         /* Always do a final sort pass based on priority. */
305         add_sort_criterion(SORT_DESC, "priority");
306     }
307
308     free(short_options);
309
310     /* Implicit OpenFlow 1.4 with the '--bundle' option. */
311     if (bundle) {
312         /* Add implicit allowance for OpenFlow 1.4. */
313         add_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
314                                      OFPUTIL_P_OF14_OXM));
315     }
316     versions = get_allowed_ofp_versions();
317     version_protocols = ofputil_protocols_from_version_bitmap(versions);
318     if (!(allowed_protocols & version_protocols)) {
319         char *protocols = ofputil_protocols_to_string(allowed_protocols);
320         struct ds version_s = DS_EMPTY_INITIALIZER;
321
322         ofputil_format_version_bitmap_names(&version_s, versions);
323         ovs_fatal(0, "None of the enabled OpenFlow versions (%s) supports "
324                   "any of the enabled flow formats (%s).  (Use -O to enable "
325                   "additional OpenFlow versions or -F to enable additional "
326                   "flow formats.)", ds_cstr(&version_s), protocols);
327     }
328     allowed_protocols &= version_protocols;
329     mask_allowed_ofp_versions(ofputil_protocols_to_version_bitmap(
330                                   allowed_protocols));
331 }
332
333 static void
334 usage(void)
335 {
336     printf("%s: OpenFlow switch management utility\n"
337            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
338            "\nFor OpenFlow switches:\n"
339            "  show SWITCH                 show OpenFlow information\n"
340            "  dump-desc SWITCH            print switch description\n"
341            "  dump-tables SWITCH          print table stats\n"
342            "  dump-table-features SWITCH  print table features\n"
343            "  dump-table-desc SWITCH      print table description (OF1.4+)\n"
344            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
345            "  mod-table SWITCH MOD        modify flow table behavior\n"
346            "      OF1.1/1.2 MOD: controller, continue, drop\n"
347            "      OF1.4+ MOD: evict, noevict\n"
348            "  get-frags SWITCH            print fragment handling behavior\n"
349            "  set-frags SWITCH FRAG_MODE  set fragment handling behavior\n"
350            "      FRAG_MODE: normal, drop, reassemble, nx-match\n"
351            "  dump-ports SWITCH [PORT]    print port statistics\n"
352            "  dump-ports-desc SWITCH [PORT]  print port descriptions\n"
353            "  dump-flows SWITCH           print all flow entries\n"
354            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
355            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
356            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
357            "  queue-stats SWITCH [PORT [QUEUE]]  dump queue stats\n"
358            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
359            "  add-flows SWITCH FILE       add flows from FILE\n"
360            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
361            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
362            "  replace-flows SWITCH FILE   replace flows with those in FILE\n"
363            "  diff-flows SOURCE1 SOURCE2  compare flows from two sources\n"
364            "  packet-out SWITCH IN_PORT ACTIONS PACKET...\n"
365            "                              execute ACTIONS on PACKET\n"
366            "  monitor SWITCH [MISSLEN] [invalid_ttl] [watch:[...]]\n"
367            "                              print packets received from SWITCH\n"
368            "  snoop SWITCH                snoop on SWITCH and its controller\n"
369            "  add-group SWITCH GROUP      add group described by GROUP\n"
370            "  add-groups SWITCH FILE      add group from FILE\n"
371            "  mod-group SWITCH GROUP      modify specific group\n"
372            "  del-groups SWITCH [GROUP]   delete matching GROUPs\n"
373            "  insert-buckets SWITCH [GROUP] add buckets to GROUP\n"
374            "  remove-buckets SWITCH [GROUP] remove buckets from GROUP\n"
375            "  dump-group-features SWITCH  print group features\n"
376            "  dump-groups SWITCH [GROUP]  print group description\n"
377            "  dump-group-stats SWITCH [GROUP]  print group statistics\n"
378            "  queue-get-config SWITCH PORT  print queue information for port\n"
379            "  add-meter SWITCH METER      add meter described by METER\n"
380            "  mod-meter SWITCH METER      modify specific METER\n"
381            "  del-meter SWITCH METER      delete METER\n"
382            "  del-meters SWITCH           delete all meters\n"
383            "  dump-meter SWITCH METER     print METER configuration\n"
384            "  dump-meters SWITCH          print all meter configuration\n"
385            "  meter-stats SWITCH [METER]  print meter statistics\n"
386            "  meter-features SWITCH       print meter features\n"
387            "  add-geneve-map SWITCH MAP   add Geneve option MAPpings\n"
388            "  del-geneve-map SWITCH [MAP] delete Geneve option MAPpings\n"
389            "  dump-geneve-map SWITCH      print Geneve option mappings\n"
390            "\nFor OpenFlow switches and controllers:\n"
391            "  probe TARGET                probe whether TARGET is up\n"
392            "  ping TARGET [N]             latency of N-byte echos\n"
393            "  benchmark TARGET N COUNT    bandwidth of COUNT N-byte echos\n"
394            "SWITCH or TARGET is an active OpenFlow connection method.\n"
395            "\nOther commands:\n"
396            "  ofp-parse FILE              print messages read from FILE\n"
397            "  ofp-parse-pcap PCAP         print OpenFlow read from PCAP\n",
398            program_name, program_name);
399     vconn_usage(true, false, false);
400     daemon_usage();
401     ofp_version_usage();
402     vlog_usage();
403     printf("\nOther options:\n"
404            "  --strict                    use strict match for flow commands\n"
405            "  --readd                     replace flows that haven't changed\n"
406            "  -F, --flow-format=FORMAT    force particular flow format\n"
407            "  -P, --packet-in-format=FRMT force particular packet in format\n"
408            "  -m, --more                  be more verbose printing OpenFlow\n"
409            "  --timestamp                 (monitor, snoop) print timestamps\n"
410            "  -t, --timeout=SECS          give up after SECS seconds\n"
411            "  --sort[=field]              sort in ascending order\n"
412            "  --rsort[=field]             sort in descending order\n"
413            "  --unixctl=SOCKET            set control socket name\n"
414            "  -h, --help                  display this help message\n"
415            "  -V, --version               display version information\n");
416     exit(EXIT_SUCCESS);
417 }
418
419 static void
420 ofctl_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
421            const char *argv[] OVS_UNUSED, void *exiting_)
422 {
423     bool *exiting = exiting_;
424     *exiting = true;
425     unixctl_command_reply(conn, NULL);
426 }
427
428 static void run(int retval, const char *message, ...)
429     OVS_PRINTF_FORMAT(2, 3);
430
431 static void
432 run(int retval, const char *message, ...)
433 {
434     if (retval) {
435         va_list args;
436
437         va_start(args, message);
438         ovs_fatal_valist(retval, message, args);
439     }
440 }
441 \f
442 /* Generic commands. */
443
444 static int
445 open_vconn_socket(const char *name, struct vconn **vconnp)
446 {
447     char *vconn_name = xasprintf("unix:%s", name);
448     int error;
449
450     error = vconn_open(vconn_name, get_allowed_ofp_versions(), DSCP_DEFAULT,
451                        vconnp);
452     if (error && error != ENOENT) {
453         ovs_fatal(0, "%s: failed to open socket (%s)", name,
454                   ovs_strerror(error));
455     }
456     free(vconn_name);
457
458     return error;
459 }
460
461 enum open_target { MGMT, SNOOP };
462
463 static enum ofputil_protocol
464 open_vconn__(const char *name, enum open_target target,
465              struct vconn **vconnp)
466 {
467     const char *suffix = target == MGMT ? "mgmt" : "snoop";
468     char *datapath_name, *datapath_type, *socket_name;
469     enum ofputil_protocol protocol;
470     char *bridge_path;
471     int ofp_version;
472     int error;
473
474     bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, suffix);
475
476     ofproto_parse_name(name, &datapath_name, &datapath_type);
477     socket_name = xasprintf("%s/%s.%s", ovs_rundir(), datapath_name, suffix);
478     free(datapath_name);
479     free(datapath_type);
480
481     if (strchr(name, ':')) {
482         run(vconn_open(name, get_allowed_ofp_versions(), DSCP_DEFAULT, vconnp),
483             "connecting to %s", name);
484     } else if (!open_vconn_socket(name, vconnp)) {
485         /* Fall Through. */
486     } else if (!open_vconn_socket(bridge_path, vconnp)) {
487         /* Fall Through. */
488     } else if (!open_vconn_socket(socket_name, vconnp)) {
489         /* Fall Through. */
490     } else {
491         ovs_fatal(0, "%s is not a bridge or a socket", name);
492     }
493
494     if (target == SNOOP) {
495         vconn_set_recv_any_version(*vconnp);
496     }
497
498     free(bridge_path);
499     free(socket_name);
500
501     VLOG_DBG("connecting to %s", vconn_get_name(*vconnp));
502     error = vconn_connect_block(*vconnp);
503     if (error) {
504         ovs_fatal(0, "%s: failed to connect to socket (%s)", name,
505                   ovs_strerror(error));
506     }
507
508     ofp_version = vconn_get_version(*vconnp);
509     protocol = ofputil_protocol_from_ofp_version(ofp_version);
510     if (!protocol) {
511         ovs_fatal(0, "%s: unsupported OpenFlow version 0x%02x",
512                   name, ofp_version);
513     }
514     return protocol;
515 }
516
517 static enum ofputil_protocol
518 open_vconn(const char *name, struct vconn **vconnp)
519 {
520     return open_vconn__(name, MGMT, vconnp);
521 }
522
523 static void
524 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
525 {
526     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
527 }
528
529 static void
530 dump_transaction(struct vconn *vconn, struct ofpbuf *request)
531 {
532     struct ofpbuf *reply;
533
534     run(vconn_transact(vconn, request, &reply), "talking to %s",
535         vconn_get_name(vconn));
536     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
537     ofpbuf_delete(reply);
538 }
539
540 static void
541 dump_trivial_transaction(const char *vconn_name, enum ofpraw raw)
542 {
543     struct ofpbuf *request;
544     struct vconn *vconn;
545
546     open_vconn(vconn_name, &vconn);
547     request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
548     dump_transaction(vconn, request);
549     vconn_close(vconn);
550 }
551
552 static void
553 dump_stats_transaction(struct vconn *vconn, struct ofpbuf *request)
554 {
555     const struct ofp_header *request_oh = request->data;
556     ovs_be32 send_xid = request_oh->xid;
557     enum ofpraw request_raw;
558     enum ofpraw reply_raw;
559     bool done = false;
560
561     ofpraw_decode_partial(&request_raw, request->data, request->size);
562     reply_raw = ofpraw_stats_request_to_reply(request_raw,
563                                               request_oh->version);
564
565     send_openflow_buffer(vconn, request);
566     while (!done) {
567         ovs_be32 recv_xid;
568         struct ofpbuf *reply;
569
570         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
571         recv_xid = ((struct ofp_header *) reply->data)->xid;
572         if (send_xid == recv_xid) {
573             enum ofpraw raw;
574
575             ofp_print(stdout, reply->data, reply->size, verbosity + 1);
576
577             ofpraw_decode(&raw, reply->data);
578             if (ofptype_from_ofpraw(raw) == OFPTYPE_ERROR) {
579                 done = true;
580             } else if (raw == reply_raw) {
581                 done = !ofpmp_more(reply->data);
582             } else {
583                 ovs_fatal(0, "received bad reply: %s",
584                           ofp_to_string(reply->data, reply->size,
585                                         verbosity + 1));
586             }
587         } else {
588             VLOG_DBG("received reply with xid %08"PRIx32" "
589                      "!= expected %08"PRIx32, recv_xid, send_xid);
590         }
591         ofpbuf_delete(reply);
592     }
593 }
594
595 static void
596 dump_trivial_stats_transaction(const char *vconn_name, enum ofpraw raw)
597 {
598     struct ofpbuf *request;
599     struct vconn *vconn;
600
601     open_vconn(vconn_name, &vconn);
602     request = ofpraw_alloc(raw, vconn_get_version(vconn), 0);
603     dump_stats_transaction(vconn, request);
604     vconn_close(vconn);
605 }
606
607 /* Sends all of the 'requests', which should be requests that only have replies
608  * if an error occurs, and waits for them to succeed or fail.  If an error does
609  * occur, prints it and exits with an error.
610  *
611  * Destroys all of the 'requests'. */
612 static void
613 transact_multiple_noreply(struct vconn *vconn, struct ovs_list *requests)
614 {
615     struct ofpbuf *reply;
616
617     run(vconn_transact_multiple_noreply(vconn, requests, &reply),
618         "talking to %s", vconn_get_name(vconn));
619     if (reply) {
620         ofp_print(stderr, reply->data, reply->size, verbosity + 2);
621         exit(1);
622     }
623     ofpbuf_delete(reply);
624 }
625
626 static void
627 bundle_error_reporter(const struct ofp_header *oh)
628 {
629     ofp_print(stderr, oh, ntohs(oh->length), verbosity + 1);
630     fflush(stderr);
631 }
632
633 static void
634 bundle_transact(struct vconn *vconn, struct ovs_list *requests, uint16_t flags)
635 {
636     run(vconn_bundle_transact(vconn, requests, flags, bundle_error_reporter),
637         "talking to %s", vconn_get_name(vconn));
638 }
639
640 /* Sends 'request', which should be a request that only has a reply if an error
641  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
642  * it and exits with an error.
643  *
644  * Destroys 'request'. */
645 static void
646 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
647 {
648     struct ovs_list requests;
649
650     list_init(&requests);
651     list_push_back(&requests, &request->list_node);
652     transact_multiple_noreply(vconn, &requests);
653 }
654
655 static void
656 fetch_switch_config(struct vconn *vconn, struct ofp_switch_config *config_)
657 {
658     struct ofp_switch_config *config;
659     struct ofpbuf *request;
660     struct ofpbuf *reply;
661     enum ofptype type;
662
663     request = ofpraw_alloc(OFPRAW_OFPT_GET_CONFIG_REQUEST,
664                            vconn_get_version(vconn), 0);
665     run(vconn_transact(vconn, request, &reply),
666         "talking to %s", vconn_get_name(vconn));
667
668     if (ofptype_pull(&type, reply) || type != OFPTYPE_GET_CONFIG_REPLY) {
669         ovs_fatal(0, "%s: bad reply to config request", vconn_get_name(vconn));
670     }
671
672     config = ofpbuf_pull(reply, sizeof *config);
673     *config_ = *config;
674
675     ofpbuf_delete(reply);
676 }
677
678 static void
679 set_switch_config(struct vconn *vconn, const struct ofp_switch_config *config)
680 {
681     struct ofpbuf *request;
682
683     request = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG, vconn_get_version(vconn), 0);
684     ofpbuf_put(request, config, sizeof *config);
685
686     transact_noreply(vconn, request);
687 }
688
689 static void
690 ofctl_show(struct ovs_cmdl_context *ctx)
691 {
692     const char *vconn_name = ctx->argv[1];
693     enum ofp_version version;
694     struct vconn *vconn;
695     struct ofpbuf *request;
696     struct ofpbuf *reply;
697     bool has_ports;
698
699     open_vconn(vconn_name, &vconn);
700     version = vconn_get_version(vconn);
701     request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST, version, 0);
702     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
703
704     has_ports = ofputil_switch_features_has_ports(reply);
705     ofp_print(stdout, reply->data, reply->size, verbosity + 1);
706     ofpbuf_delete(reply);
707
708     if (!has_ports) {
709         request = ofputil_encode_port_desc_stats_request(version, OFPP_ANY);
710         dump_stats_transaction(vconn, request);
711     }
712     dump_trivial_transaction(vconn_name, OFPRAW_OFPT_GET_CONFIG_REQUEST);
713     vconn_close(vconn);
714 }
715
716 static void
717 ofctl_dump_desc(struct ovs_cmdl_context *ctx)
718 {
719     dump_trivial_stats_transaction(ctx->argv[1], OFPRAW_OFPST_DESC_REQUEST);
720 }
721
722 static void
723 ofctl_dump_tables(struct ovs_cmdl_context *ctx)
724 {
725     dump_trivial_stats_transaction(ctx->argv[1], OFPRAW_OFPST_TABLE_REQUEST);
726 }
727
728 static void
729 ofctl_dump_table_features(struct ovs_cmdl_context *ctx)
730 {
731     struct ofpbuf *request;
732     struct vconn *vconn;
733
734     open_vconn(ctx->argv[1], &vconn);
735     request = ofputil_encode_table_features_request(vconn_get_version(vconn));
736
737     /* The following is similar to dump_trivial_stats_transaction(), but it
738      * maintains the previous 'ofputil_table_features' from one stats reply
739      * message to the next, which allows duplication to be eliminated in the
740      * output across messages.  Otherwise the output is much larger and harder
741      * to read, because only 17 or so ofputil_table_features elements fit in a
742      * single 64 kB OpenFlow message and therefore you get a ton of repetition
743      * (every 17th element is printed in full instead of abbreviated). */
744
745     const struct ofp_header *request_oh = request->data;
746     ovs_be32 send_xid = request_oh->xid;
747     bool done = false;
748
749     struct ofputil_table_features prev;
750     int n = 0;
751
752     send_openflow_buffer(vconn, request);
753     while (!done) {
754         ovs_be32 recv_xid;
755         struct ofpbuf *reply;
756
757         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
758         recv_xid = ((struct ofp_header *) reply->data)->xid;
759         if (send_xid == recv_xid) {
760             enum ofptype type;
761             enum ofperr error;
762             error = ofptype_decode(&type, reply->data);
763             if (error) {
764                 ovs_fatal(0, "decode error: %s", ofperr_get_name(error));
765             } else if (type == OFPTYPE_ERROR) {
766                 ofp_print(stdout, reply->data, reply->size, verbosity + 1);
767                 done = true;
768             } else if (type == OFPTYPE_TABLE_FEATURES_STATS_REPLY) {
769                 done = !ofpmp_more(reply->data);
770                 for (;;) {
771                     struct ofputil_table_features tf;
772                     int retval;
773
774                     retval = ofputil_decode_table_features(reply, &tf, true);
775                     if (retval) {
776                         if (retval != EOF) {
777                             ovs_fatal(0, "decode error: %s",
778                                       ofperr_get_name(retval));
779                         }
780                         break;
781                     }
782
783                     struct ds s = DS_EMPTY_INITIALIZER;
784                     ofp_print_table_features(&s, &tf, n ? &prev : NULL,
785                                              NULL, NULL);
786                     puts(ds_cstr(&s));
787                     ds_destroy(&s);
788
789                     prev = tf;
790                     n++;
791                 }
792             } else {
793                 ovs_fatal(0, "received bad reply: %s",
794                           ofp_to_string(reply->data, reply->size,
795                                         verbosity + 1));
796             }
797         } else {
798             VLOG_DBG("received reply with xid %08"PRIx32" "
799                      "!= expected %08"PRIx32, recv_xid, send_xid);
800         }
801         ofpbuf_delete(reply);
802     }
803
804     vconn_close(vconn);
805 }
806
807 static void
808 ofctl_dump_table_desc(struct ovs_cmdl_context *ctx)
809 {
810     struct ofpbuf *request;
811     struct vconn *vconn;
812
813     open_vconn(ctx->argv[1], &vconn);
814     request = ofputil_encode_table_desc_request(vconn_get_version(vconn));
815     if (request) {
816         dump_stats_transaction(vconn, request);
817     }
818
819     vconn_close(vconn);
820 }
821
822
823 static bool fetch_port_by_stats(struct vconn *,
824                                 const char *port_name, ofp_port_t port_no,
825                                 struct ofputil_phy_port *);
826
827 /* Uses OFPT_FEATURES_REQUEST to attempt to fetch information about the port
828  * named 'port_name' or numbered 'port_no' into '*pp'.  Returns true if
829  * successful, false on failure.
830  *
831  * This is only appropriate for OpenFlow 1.0, 1.1, and 1.2, which include a
832  * list of ports in OFPT_FEATURES_REPLY. */
833 static bool
834 fetch_port_by_features(struct vconn *vconn,
835                        const char *port_name, ofp_port_t port_no,
836                        struct ofputil_phy_port *pp)
837 {
838     struct ofputil_switch_features features;
839     const struct ofp_header *oh;
840     struct ofpbuf *request, *reply;
841     enum ofperr error;
842     enum ofptype type;
843     struct ofpbuf b;
844     bool found = false;
845
846     /* Fetch the switch's ofp_switch_features. */
847     request = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST,
848                            vconn_get_version(vconn), 0);
849     run(vconn_transact(vconn, request, &reply),
850         "talking to %s", vconn_get_name(vconn));
851
852     oh = reply->data;
853     if (ofptype_decode(&type, reply->data)
854         || type != OFPTYPE_FEATURES_REPLY) {
855         ovs_fatal(0, "%s: received bad features reply", vconn_get_name(vconn));
856     }
857     if (!ofputil_switch_features_has_ports(reply)) {
858         /* The switch features reply does not contain a complete list of ports.
859          * Probably, there are more ports than will fit into a single 64 kB
860          * OpenFlow message.  Use OFPST_PORT_DESC to get a complete list of
861          * ports. */
862         ofpbuf_delete(reply);
863         return fetch_port_by_stats(vconn, port_name, port_no, pp);
864     }
865
866     error = ofputil_decode_switch_features(oh, &features, &b);
867     if (error) {
868         ovs_fatal(0, "%s: failed to decode features reply (%s)",
869                   vconn_get_name(vconn), ofperr_to_string(error));
870     }
871
872     while (!ofputil_pull_phy_port(oh->version, &b, pp)) {
873         if (port_no != OFPP_NONE
874             ? port_no == pp->port_no
875             : !strcmp(pp->name, port_name)) {
876             found = true;
877             break;
878         }
879     }
880     ofpbuf_delete(reply);
881     return found;
882 }
883
884 /* Uses a OFPST_PORT_DESC request to attempt to fetch information about the
885  * port named 'port_name' or numbered 'port_no' into '*pp'.  Returns true if
886  * successful, false on failure.
887  *
888  * This is most appropriate for OpenFlow 1.3 and later.  Open vSwitch 1.7 and
889  * later also implements OFPST_PORT_DESC, as an extension, for OpenFlow 1.0,
890  * 1.1, and 1.2, so this can be used as a fallback in those versions when there
891  * are too many ports than fit in an OFPT_FEATURES_REPLY. */
892 static bool
893 fetch_port_by_stats(struct vconn *vconn,
894                     const char *port_name, ofp_port_t port_no,
895                     struct ofputil_phy_port *pp)
896 {
897     struct ofpbuf *request;
898     ovs_be32 send_xid;
899     bool done = false;
900     bool found = false;
901
902     request = ofputil_encode_port_desc_stats_request(vconn_get_version(vconn),
903                                                      port_no);
904     send_xid = ((struct ofp_header *) request->data)->xid;
905
906     send_openflow_buffer(vconn, request);
907     while (!done) {
908         ovs_be32 recv_xid;
909         struct ofpbuf *reply;
910
911         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
912         recv_xid = ((struct ofp_header *) reply->data)->xid;
913         if (send_xid == recv_xid) {
914             struct ofp_header *oh = reply->data;
915             enum ofptype type;
916             struct ofpbuf b;
917             uint16_t flags;
918
919             ofpbuf_use_const(&b, oh, ntohs(oh->length));
920             if (ofptype_pull(&type, &b)
921                 || type != OFPTYPE_PORT_DESC_STATS_REPLY) {
922                 ovs_fatal(0, "received bad reply: %s",
923                           ofp_to_string(reply->data, reply->size,
924                                         verbosity + 1));
925             }
926
927             flags = ofpmp_flags(oh);
928             done = !(flags & OFPSF_REPLY_MORE);
929
930             if (found) {
931                 /* We've already found the port, but we need to drain
932                  * the queue of any other replies for this request. */
933                 continue;
934             }
935
936             while (!ofputil_pull_phy_port(oh->version, &b, pp)) {
937                 if (port_no != OFPP_NONE ? port_no == pp->port_no
938                                          : !strcmp(pp->name, port_name)) {
939                     found = true;
940                     break;
941                 }
942             }
943         } else {
944             VLOG_DBG("received reply with xid %08"PRIx32" "
945                      "!= expected %08"PRIx32, recv_xid, send_xid);
946         }
947         ofpbuf_delete(reply);
948     }
949
950     return found;
951 }
952
953 static bool
954 str_to_ofp(const char *s, ofp_port_t *ofp_port)
955 {
956     bool ret;
957     uint32_t port_;
958
959     ret = str_to_uint(s, 10, &port_);
960     *ofp_port = u16_to_ofp(port_);
961     return ret;
962 }
963
964 /* Opens a connection to 'vconn_name', fetches the port structure for
965  * 'port_name' (which may be a port name or number), and copies it into
966  * '*pp'. */
967 static void
968 fetch_ofputil_phy_port(const char *vconn_name, const char *port_name,
969                        struct ofputil_phy_port *pp)
970 {
971     struct vconn *vconn;
972     ofp_port_t port_no;
973     bool found;
974
975     /* Try to interpret the argument as a port number. */
976     if (!str_to_ofp(port_name, &port_no)) {
977         port_no = OFPP_NONE;
978     }
979
980     /* OpenFlow 1.0, 1.1, and 1.2 put the list of ports in the
981      * OFPT_FEATURES_REPLY message.  OpenFlow 1.3 and later versions put it
982      * into the OFPST_PORT_DESC reply.  Try it the correct way. */
983     open_vconn(vconn_name, &vconn);
984     found = (vconn_get_version(vconn) < OFP13_VERSION
985              ? fetch_port_by_features(vconn, port_name, port_no, pp)
986              : fetch_port_by_stats(vconn, port_name, port_no, pp));
987     vconn_close(vconn);
988
989     if (!found) {
990         ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
991     }
992 }
993
994 /* Returns the port number corresponding to 'port_name' (which may be a port
995  * name or number) within the switch 'vconn_name'. */
996 static ofp_port_t
997 str_to_port_no(const char *vconn_name, const char *port_name)
998 {
999     ofp_port_t port_no;
1000
1001     if (ofputil_port_from_string(port_name, &port_no)) {
1002         return port_no;
1003     } else {
1004         struct ofputil_phy_port pp;
1005
1006         fetch_ofputil_phy_port(vconn_name, port_name, &pp);
1007         return pp.port_no;
1008     }
1009 }
1010
1011 static bool
1012 try_set_protocol(struct vconn *vconn, enum ofputil_protocol want,
1013                  enum ofputil_protocol *cur)
1014 {
1015     for (;;) {
1016         struct ofpbuf *request, *reply;
1017         enum ofputil_protocol next;
1018
1019         request = ofputil_encode_set_protocol(*cur, want, &next);
1020         if (!request) {
1021             return *cur == want;
1022         }
1023
1024         run(vconn_transact_noreply(vconn, request, &reply),
1025             "talking to %s", vconn_get_name(vconn));
1026         if (reply) {
1027             char *s = ofp_to_string(reply->data, reply->size, 2);
1028             VLOG_DBG("%s: failed to set protocol, switch replied: %s",
1029                      vconn_get_name(vconn), s);
1030             free(s);
1031             ofpbuf_delete(reply);
1032             return false;
1033         }
1034
1035         *cur = next;
1036     }
1037 }
1038
1039 static enum ofputil_protocol
1040 set_protocol_for_flow_dump(struct vconn *vconn,
1041                            enum ofputil_protocol cur_protocol,
1042                            enum ofputil_protocol usable_protocols)
1043 {
1044     char *usable_s;
1045     int i;
1046
1047     for (i = 0; i < ofputil_n_flow_dump_protocols; i++) {
1048         enum ofputil_protocol f = ofputil_flow_dump_protocols[i];
1049         if (f & usable_protocols & allowed_protocols
1050             && try_set_protocol(vconn, f, &cur_protocol)) {
1051             return f;
1052         }
1053     }
1054
1055     usable_s = ofputil_protocols_to_string(usable_protocols);
1056     if (usable_protocols & allowed_protocols) {
1057         ovs_fatal(0, "switch does not support any of the usable flow "
1058                   "formats (%s)", usable_s);
1059     } else {
1060         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
1061         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
1062                   "allowed flow formats (%s)", usable_s, allowed_s);
1063     }
1064 }
1065
1066 static struct vconn *
1067 prepare_dump_flows(int argc, char *argv[], bool aggregate,
1068                    struct ofpbuf **requestp)
1069 {
1070     enum ofputil_protocol usable_protocols, protocol;
1071     struct ofputil_flow_stats_request fsr;
1072     struct vconn *vconn;
1073     char *error;
1074
1075     error = parse_ofp_flow_stats_request_str(&fsr, aggregate,
1076                                              argc > 2 ? argv[2] : "",
1077                                              &usable_protocols);
1078     if (error) {
1079         ovs_fatal(0, "%s", error);
1080     }
1081
1082     protocol = open_vconn(argv[1], &vconn);
1083     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
1084     *requestp = ofputil_encode_flow_stats_request(&fsr, protocol);
1085     return vconn;
1086 }
1087
1088 static void
1089 ofctl_dump_flows__(int argc, char *argv[], bool aggregate)
1090 {
1091     struct ofpbuf *request;
1092     struct vconn *vconn;
1093
1094     vconn = prepare_dump_flows(argc, argv, aggregate, &request);
1095     dump_stats_transaction(vconn, request);
1096     vconn_close(vconn);
1097 }
1098
1099 static int
1100 compare_flows(const void *afs_, const void *bfs_)
1101 {
1102     const struct ofputil_flow_stats *afs = afs_;
1103     const struct ofputil_flow_stats *bfs = bfs_;
1104     const struct match *a = &afs->match;
1105     const struct match *b = &bfs->match;
1106     const struct sort_criterion *sc;
1107
1108     for (sc = criteria; sc < &criteria[n_criteria]; sc++) {
1109         const struct mf_field *f = sc->field;
1110         int ret;
1111
1112         if (!f) {
1113             int a_pri = afs->priority;
1114             int b_pri = bfs->priority;
1115             ret = a_pri < b_pri ? -1 : a_pri > b_pri;
1116         } else {
1117             bool ina, inb;
1118
1119             ina = mf_are_prereqs_ok(f, &a->flow) && !mf_is_all_wild(f, &a->wc);
1120             inb = mf_are_prereqs_ok(f, &b->flow) && !mf_is_all_wild(f, &b->wc);
1121             if (ina != inb) {
1122                 /* Skip the test for sc->order, so that missing fields always
1123                  * sort to the end whether we're sorting in ascending or
1124                  * descending order. */
1125                 return ina ? -1 : 1;
1126             } else {
1127                 union mf_value aval, bval;
1128
1129                 mf_get_value(f, &a->flow, &aval);
1130                 mf_get_value(f, &b->flow, &bval);
1131                 ret = memcmp(&aval, &bval, f->n_bytes);
1132             }
1133         }
1134
1135         if (ret) {
1136             return sc->order == SORT_ASC ? ret : -ret;
1137         }
1138     }
1139
1140     return 0;
1141 }
1142
1143 static void
1144 ofctl_dump_flows(struct ovs_cmdl_context *ctx)
1145 {
1146     if (!n_criteria) {
1147         ofctl_dump_flows__(ctx->argc, ctx->argv, false);
1148         return;
1149     } else {
1150         struct ofputil_flow_stats *fses;
1151         size_t n_fses, allocated_fses;
1152         struct ofpbuf *request;
1153         struct ofpbuf ofpacts;
1154         struct ofpbuf *reply;
1155         struct vconn *vconn;
1156         ovs_be32 send_xid;
1157         struct ds s;
1158         size_t i;
1159
1160         vconn = prepare_dump_flows(ctx->argc, ctx->argv, false, &request);
1161         send_xid = ((struct ofp_header *) request->data)->xid;
1162         send_openflow_buffer(vconn, request);
1163
1164         fses = NULL;
1165         n_fses = allocated_fses = 0;
1166         reply = NULL;
1167         ofpbuf_init(&ofpacts, 0);
1168         for (;;) {
1169             struct ofputil_flow_stats *fs;
1170
1171             if (n_fses >= allocated_fses) {
1172                 fses = x2nrealloc(fses, &allocated_fses, sizeof *fses);
1173             }
1174
1175             fs = &fses[n_fses];
1176             if (!recv_flow_stats_reply(vconn, send_xid, &reply, fs,
1177                                        &ofpacts)) {
1178                 break;
1179             }
1180             fs->ofpacts = xmemdup(fs->ofpacts, fs->ofpacts_len);
1181             n_fses++;
1182         }
1183         ofpbuf_uninit(&ofpacts);
1184
1185         qsort(fses, n_fses, sizeof *fses, compare_flows);
1186
1187         ds_init(&s);
1188         for (i = 0; i < n_fses; i++) {
1189             ds_clear(&s);
1190             ofp_print_flow_stats(&s, &fses[i]);
1191             puts(ds_cstr(&s));
1192         }
1193         ds_destroy(&s);
1194
1195         for (i = 0; i < n_fses; i++) {
1196             free(CONST_CAST(struct ofpact *, fses[i].ofpacts));
1197         }
1198         free(fses);
1199
1200         vconn_close(vconn);
1201     }
1202 }
1203
1204 static void
1205 ofctl_dump_aggregate(struct ovs_cmdl_context *ctx)
1206 {
1207     ofctl_dump_flows__(ctx->argc, ctx->argv, true);
1208 }
1209
1210 static void
1211 ofctl_queue_stats(struct ovs_cmdl_context *ctx)
1212 {
1213     struct ofpbuf *request;
1214     struct vconn *vconn;
1215     struct ofputil_queue_stats_request oqs;
1216
1217     open_vconn(ctx->argv[1], &vconn);
1218
1219     if (ctx->argc > 2 && ctx->argv[2][0] && strcasecmp(ctx->argv[2], "all")) {
1220         oqs.port_no = str_to_port_no(ctx->argv[1], ctx->argv[2]);
1221     } else {
1222         oqs.port_no = OFPP_ANY;
1223     }
1224     if (ctx->argc > 3 && ctx->argv[3][0] && strcasecmp(ctx->argv[3], "all")) {
1225         oqs.queue_id = atoi(ctx->argv[3]);
1226     } else {
1227         oqs.queue_id = OFPQ_ALL;
1228     }
1229
1230     request = ofputil_encode_queue_stats_request(vconn_get_version(vconn), &oqs);
1231     dump_stats_transaction(vconn, request);
1232     vconn_close(vconn);
1233 }
1234
1235 static void
1236 ofctl_queue_get_config(struct ovs_cmdl_context *ctx)
1237 {
1238     const char *vconn_name = ctx->argv[1];
1239     const char *port_name = ctx->argv[2];
1240     enum ofputil_protocol protocol;
1241     enum ofp_version version;
1242     struct ofpbuf *request;
1243     struct vconn *vconn;
1244     ofp_port_t port;
1245
1246     port = str_to_port_no(vconn_name, port_name);
1247
1248     protocol = open_vconn(vconn_name, &vconn);
1249     version = ofputil_protocol_to_ofp_version(protocol);
1250     request = ofputil_encode_queue_get_config_request(version, port);
1251     dump_transaction(vconn, request);
1252     vconn_close(vconn);
1253 }
1254
1255 static enum ofputil_protocol
1256 open_vconn_for_flow_mod(const char *remote, struct vconn **vconnp,
1257                         enum ofputil_protocol usable_protocols)
1258 {
1259     enum ofputil_protocol cur_protocol;
1260     char *usable_s;
1261     int i;
1262
1263     if (!(usable_protocols & allowed_protocols)) {
1264         char *allowed_s = ofputil_protocols_to_string(allowed_protocols);
1265         usable_s = ofputil_protocols_to_string(usable_protocols);
1266         ovs_fatal(0, "none of the usable flow formats (%s) is among the "
1267                   "allowed flow formats (%s)", usable_s, allowed_s);
1268     }
1269
1270     /* If the initial flow format is allowed and usable, keep it. */
1271     cur_protocol = open_vconn(remote, vconnp);
1272     if (usable_protocols & allowed_protocols & cur_protocol) {
1273         return cur_protocol;
1274     }
1275
1276     /* Otherwise try each flow format in turn. */
1277     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
1278         enum ofputil_protocol f = 1 << i;
1279
1280         if (f != cur_protocol
1281             && f & usable_protocols & allowed_protocols
1282             && try_set_protocol(*vconnp, f, &cur_protocol)) {
1283             return f;
1284         }
1285     }
1286
1287     usable_s = ofputil_protocols_to_string(usable_protocols);
1288     ovs_fatal(0, "switch does not support any of the usable flow "
1289               "formats (%s)", usable_s);
1290 }
1291
1292 static void
1293 bundle_flow_mod__(const char *remote, struct ofputil_flow_mod *fms,
1294                   size_t n_fms, enum ofputil_protocol usable_protocols)
1295 {
1296     enum ofputil_protocol protocol;
1297     struct vconn *vconn;
1298     struct ovs_list requests;
1299     size_t i;
1300
1301     list_init(&requests);
1302
1303     /* Bundles need OpenFlow 1.4+. */
1304     usable_protocols &= OFPUTIL_P_OF14_UP;
1305     protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
1306
1307     for (i = 0; i < n_fms; i++) {
1308         struct ofputil_flow_mod *fm = &fms[i];
1309         struct ofpbuf *request = ofputil_encode_flow_mod(fm, protocol);
1310
1311         list_push_back(&requests, &request->list_node);
1312         free(CONST_CAST(struct ofpact *, fm->ofpacts));
1313     }
1314
1315     bundle_transact(vconn, &requests, OFPBF_ORDERED | OFPBF_ATOMIC);
1316     vconn_close(vconn);
1317 }
1318
1319 static void
1320 ofctl_flow_mod__(const char *remote, struct ofputil_flow_mod *fms,
1321                  size_t n_fms, enum ofputil_protocol usable_protocols)
1322 {
1323     enum ofputil_protocol protocol;
1324     struct vconn *vconn;
1325     size_t i;
1326
1327     if (bundle) {
1328         bundle_flow_mod__(remote, fms, n_fms, usable_protocols);
1329         return;
1330     }
1331
1332     protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
1333
1334     for (i = 0; i < n_fms; i++) {
1335         struct ofputil_flow_mod *fm = &fms[i];
1336
1337         transact_noreply(vconn, ofputil_encode_flow_mod(fm, protocol));
1338         free(CONST_CAST(struct ofpact *, fm->ofpacts));
1339     }
1340     vconn_close(vconn);
1341 }
1342
1343 static void
1344 ofctl_flow_mod_file(int argc OVS_UNUSED, char *argv[], int command)
1345 {
1346     enum ofputil_protocol usable_protocols;
1347     struct ofputil_flow_mod *fms = NULL;
1348     size_t n_fms = 0;
1349     char *error;
1350
1351     if (command == OFPFC_ADD) {
1352         /* Allow the file to specify a mix of commands.  If none specified at
1353          * the beginning of any given line, then the default is OFPFC_ADD, so
1354          * this is backwards compatible. */
1355         command = -2;
1356     }
1357     error = parse_ofp_flow_mod_file(argv[2], command, &fms, &n_fms,
1358                                     &usable_protocols);
1359     if (error) {
1360         ovs_fatal(0, "%s", error);
1361     }
1362     ofctl_flow_mod__(argv[1], fms, n_fms, usable_protocols);
1363     free(fms);
1364 }
1365
1366 static void
1367 ofctl_flow_mod(int argc, char *argv[], uint16_t command)
1368 {
1369     if (argc > 2 && !strcmp(argv[2], "-")) {
1370         ofctl_flow_mod_file(argc, argv, command);
1371     } else {
1372         struct ofputil_flow_mod fm;
1373         char *error;
1374         enum ofputil_protocol usable_protocols;
1375
1376         error = parse_ofp_flow_mod_str(&fm, argc > 2 ? argv[2] : "", command,
1377                                        &usable_protocols);
1378         if (error) {
1379             ovs_fatal(0, "%s", error);
1380         }
1381         ofctl_flow_mod__(argv[1], &fm, 1, usable_protocols);
1382     }
1383 }
1384
1385 static void
1386 ofctl_add_flow(struct ovs_cmdl_context *ctx)
1387 {
1388     ofctl_flow_mod(ctx->argc, ctx->argv, OFPFC_ADD);
1389 }
1390
1391 static void
1392 ofctl_add_flows(struct ovs_cmdl_context *ctx)
1393 {
1394     ofctl_flow_mod_file(ctx->argc, ctx->argv, OFPFC_ADD);
1395 }
1396
1397 static void
1398 ofctl_mod_flows(struct ovs_cmdl_context *ctx)
1399 {
1400     ofctl_flow_mod(ctx->argc, ctx->argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
1401 }
1402
1403 static void
1404 ofctl_del_flows(struct ovs_cmdl_context *ctx)
1405 {
1406     ofctl_flow_mod(ctx->argc, ctx->argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
1407 }
1408
1409 static void
1410 set_packet_in_format(struct vconn *vconn,
1411                      enum nx_packet_in_format packet_in_format)
1412 {
1413     struct ofpbuf *spif;
1414
1415     spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1416                                              packet_in_format);
1417     transact_noreply(vconn, spif);
1418     VLOG_DBG("%s: using user-specified packet in format %s",
1419              vconn_get_name(vconn),
1420              ofputil_packet_in_format_to_string(packet_in_format));
1421 }
1422
1423 static int
1424 monitor_set_invalid_ttl_to_controller(struct vconn *vconn)
1425 {
1426     struct ofp_switch_config config;
1427     enum ofp_config_flags flags;
1428
1429     fetch_switch_config(vconn, &config);
1430     flags = ntohs(config.flags);
1431     if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
1432         /* Set the invalid ttl config. */
1433         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
1434
1435         config.flags = htons(flags);
1436         set_switch_config(vconn, &config);
1437
1438         /* Then retrieve the configuration to see if it really took.  OpenFlow
1439          * doesn't define error reporting for bad modes, so this is all we can
1440          * do. */
1441         fetch_switch_config(vconn, &config);
1442         flags = ntohs(config.flags);
1443         if (!(flags & OFPC_INVALID_TTL_TO_CONTROLLER)) {
1444             ovs_fatal(0, "setting invalid_ttl_to_controller failed (this "
1445                       "switch probably doesn't support mode)");
1446             return -EOPNOTSUPP;
1447         }
1448     }
1449     return 0;
1450 }
1451
1452 /* Converts hex digits in 'hex' to an OpenFlow message in '*msgp'.  The
1453  * caller must free '*msgp'.  On success, returns NULL.  On failure, returns
1454  * an error message and stores NULL in '*msgp'. */
1455 static const char *
1456 openflow_from_hex(const char *hex, struct ofpbuf **msgp)
1457 {
1458     struct ofp_header *oh;
1459     struct ofpbuf *msg;
1460
1461     msg = ofpbuf_new(strlen(hex) / 2);
1462     *msgp = NULL;
1463
1464     if (ofpbuf_put_hex(msg, hex, NULL)[0] != '\0') {
1465         ofpbuf_delete(msg);
1466         return "Trailing garbage in hex data";
1467     }
1468
1469     if (msg->size < sizeof(struct ofp_header)) {
1470         ofpbuf_delete(msg);
1471         return "Message too short for OpenFlow";
1472     }
1473
1474     oh = msg->data;
1475     if (msg->size != ntohs(oh->length)) {
1476         ofpbuf_delete(msg);
1477         return "Message size does not match length in OpenFlow header";
1478     }
1479
1480     *msgp = msg;
1481     return NULL;
1482 }
1483
1484 static void
1485 ofctl_send(struct unixctl_conn *conn, int argc,
1486            const char *argv[], void *vconn_)
1487 {
1488     struct vconn *vconn = vconn_;
1489     struct ds reply;
1490     bool ok;
1491     int i;
1492
1493     ok = true;
1494     ds_init(&reply);
1495     for (i = 1; i < argc; i++) {
1496         const char *error_msg;
1497         struct ofpbuf *msg;
1498         int error;
1499
1500         error_msg = openflow_from_hex(argv[i], &msg);
1501         if (error_msg) {
1502             ds_put_format(&reply, "%s\n", error_msg);
1503             ok = false;
1504             continue;
1505         }
1506
1507         fprintf(stderr, "send: ");
1508         ofp_print(stderr, msg->data, msg->size, verbosity);
1509
1510         error = vconn_send_block(vconn, msg);
1511         if (error) {
1512             ofpbuf_delete(msg);
1513             ds_put_format(&reply, "%s\n", ovs_strerror(error));
1514             ok = false;
1515         } else {
1516             ds_put_cstr(&reply, "sent\n");
1517         }
1518     }
1519
1520     if (ok) {
1521         unixctl_command_reply(conn, ds_cstr(&reply));
1522     } else {
1523         unixctl_command_reply_error(conn, ds_cstr(&reply));
1524     }
1525     ds_destroy(&reply);
1526 }
1527
1528 struct barrier_aux {
1529     struct vconn *vconn;        /* OpenFlow connection for sending barrier. */
1530     struct unixctl_conn *conn;  /* Connection waiting for barrier response. */
1531 };
1532
1533 static void
1534 ofctl_barrier(struct unixctl_conn *conn, int argc OVS_UNUSED,
1535               const char *argv[] OVS_UNUSED, void *aux_)
1536 {
1537     struct barrier_aux *aux = aux_;
1538     struct ofpbuf *msg;
1539     int error;
1540
1541     if (aux->conn) {
1542         unixctl_command_reply_error(conn, "already waiting for barrier reply");
1543         return;
1544     }
1545
1546     msg = ofputil_encode_barrier_request(vconn_get_version(aux->vconn));
1547     error = vconn_send_block(aux->vconn, msg);
1548     if (error) {
1549         ofpbuf_delete(msg);
1550         unixctl_command_reply_error(conn, ovs_strerror(error));
1551     } else {
1552         aux->conn = conn;
1553     }
1554 }
1555
1556 static void
1557 ofctl_set_output_file(struct unixctl_conn *conn, int argc OVS_UNUSED,
1558                       const char *argv[], void *aux OVS_UNUSED)
1559 {
1560     int fd;
1561
1562     fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
1563     if (fd < 0) {
1564         unixctl_command_reply_error(conn, ovs_strerror(errno));
1565         return;
1566     }
1567
1568     fflush(stderr);
1569     dup2(fd, STDERR_FILENO);
1570     close(fd);
1571     unixctl_command_reply(conn, NULL);
1572 }
1573
1574 static void
1575 ofctl_block(struct unixctl_conn *conn, int argc OVS_UNUSED,
1576             const char *argv[] OVS_UNUSED, void *blocked_)
1577 {
1578     bool *blocked = blocked_;
1579
1580     if (!*blocked) {
1581         *blocked = true;
1582         unixctl_command_reply(conn, NULL);
1583     } else {
1584         unixctl_command_reply(conn, "already blocking");
1585     }
1586 }
1587
1588 static void
1589 ofctl_unblock(struct unixctl_conn *conn, int argc OVS_UNUSED,
1590               const char *argv[] OVS_UNUSED, void *blocked_)
1591 {
1592     bool *blocked = blocked_;
1593
1594     if (*blocked) {
1595         *blocked = false;
1596         unixctl_command_reply(conn, NULL);
1597     } else {
1598         unixctl_command_reply(conn, "already unblocked");
1599     }
1600 }
1601
1602 /* Prints to stdout all of the messages received on 'vconn'.
1603  *
1604  * Iff 'reply_to_echo_requests' is true, sends a reply to any echo request
1605  * received on 'vconn'. */
1606 static void
1607 monitor_vconn(struct vconn *vconn, bool reply_to_echo_requests)
1608 {
1609     struct barrier_aux barrier_aux = { vconn, NULL };
1610     struct unixctl_server *server;
1611     bool exiting = false;
1612     bool blocked = false;
1613     int error;
1614
1615     daemon_save_fd(STDERR_FILENO);
1616     daemonize_start(false);
1617     error = unixctl_server_create(unixctl_path, &server);
1618     if (error) {
1619         ovs_fatal(error, "failed to create unixctl server");
1620     }
1621     unixctl_command_register("exit", "", 0, 0, ofctl_exit, &exiting);
1622     unixctl_command_register("ofctl/send", "OFMSG...", 1, INT_MAX,
1623                              ofctl_send, vconn);
1624     unixctl_command_register("ofctl/barrier", "", 0, 0,
1625                              ofctl_barrier, &barrier_aux);
1626     unixctl_command_register("ofctl/set-output-file", "FILE", 1, 1,
1627                              ofctl_set_output_file, NULL);
1628
1629     unixctl_command_register("ofctl/block", "", 0, 0, ofctl_block, &blocked);
1630     unixctl_command_register("ofctl/unblock", "", 0, 0, ofctl_unblock,
1631                              &blocked);
1632
1633     daemonize_complete();
1634
1635     for (;;) {
1636         struct ofpbuf *b;
1637         int retval;
1638
1639         unixctl_server_run(server);
1640
1641         while (!blocked) {
1642             enum ofptype type;
1643
1644             retval = vconn_recv(vconn, &b);
1645             if (retval == EAGAIN) {
1646                 break;
1647             }
1648             run(retval, "vconn_recv");
1649
1650             if (timestamp) {
1651                 char *s = xastrftime_msec("%Y-%m-%d %H:%M:%S.###: ",
1652                                           time_wall_msec(), true);
1653                 fputs(s, stderr);
1654                 free(s);
1655             }
1656
1657             ofptype_decode(&type, b->data);
1658             ofp_print(stderr, b->data, b->size, verbosity + 2);
1659             fflush(stderr);
1660
1661             switch ((int) type) {
1662             case OFPTYPE_BARRIER_REPLY:
1663                 if (barrier_aux.conn) {
1664                     unixctl_command_reply(barrier_aux.conn, NULL);
1665                     barrier_aux.conn = NULL;
1666                 }
1667                 break;
1668
1669             case OFPTYPE_ECHO_REQUEST:
1670                 if (reply_to_echo_requests) {
1671                     struct ofpbuf *reply;
1672
1673                     reply = make_echo_reply(b->data);
1674                     retval = vconn_send_block(vconn, reply);
1675                     if (retval) {
1676                         ovs_fatal(retval, "failed to send echo reply");
1677                     }
1678                 }
1679                 break;
1680             }
1681             ofpbuf_delete(b);
1682         }
1683
1684         if (exiting) {
1685             break;
1686         }
1687
1688         vconn_run(vconn);
1689         vconn_run_wait(vconn);
1690         if (!blocked) {
1691             vconn_recv_wait(vconn);
1692         }
1693         unixctl_server_wait(server);
1694         poll_block();
1695     }
1696     vconn_close(vconn);
1697     unixctl_server_destroy(server);
1698 }
1699
1700 static void
1701 ofctl_monitor(struct ovs_cmdl_context *ctx)
1702 {
1703     struct vconn *vconn;
1704     int i;
1705     enum ofputil_protocol usable_protocols;
1706
1707     open_vconn(ctx->argv[1], &vconn);
1708     for (i = 2; i < ctx->argc; i++) {
1709         const char *arg = ctx->argv[i];
1710
1711         if (isdigit((unsigned char) *arg)) {
1712             struct ofp_switch_config config;
1713
1714             fetch_switch_config(vconn, &config);
1715             config.miss_send_len = htons(atoi(arg));
1716             set_switch_config(vconn, &config);
1717         } else if (!strcmp(arg, "invalid_ttl")) {
1718             monitor_set_invalid_ttl_to_controller(vconn);
1719         } else if (!strncmp(arg, "watch:", 6)) {
1720             struct ofputil_flow_monitor_request fmr;
1721             struct ofpbuf *msg;
1722             char *error;
1723
1724             error = parse_flow_monitor_request(&fmr, arg + 6,
1725                                                &usable_protocols);
1726             if (error) {
1727                 ovs_fatal(0, "%s", error);
1728             }
1729
1730             msg = ofpbuf_new(0);
1731             ofputil_append_flow_monitor_request(&fmr, msg);
1732             dump_stats_transaction(vconn, msg);
1733             fflush(stdout);
1734         } else {
1735             ovs_fatal(0, "%s: unsupported \"monitor\" argument", arg);
1736         }
1737     }
1738
1739     if (preferred_packet_in_format >= 0) {
1740         set_packet_in_format(vconn, preferred_packet_in_format);
1741     } else {
1742         enum ofp_version version = vconn_get_version(vconn);
1743
1744         switch (version) {
1745         case OFP10_VERSION: {
1746             struct ofpbuf *spif, *reply;
1747
1748             spif = ofputil_make_set_packet_in_format(vconn_get_version(vconn),
1749                                                      NXPIF_NXM);
1750             run(vconn_transact_noreply(vconn, spif, &reply),
1751                 "talking to %s", vconn_get_name(vconn));
1752             if (reply) {
1753                 char *s = ofp_to_string(reply->data, reply->size, 2);
1754                 VLOG_DBG("%s: failed to set packet in format to nxm, controller"
1755                         " replied: %s. Falling back to the switch default.",
1756                         vconn_get_name(vconn), s);
1757                 free(s);
1758                 ofpbuf_delete(reply);
1759             }
1760             break;
1761         }
1762         case OFP11_VERSION:
1763         case OFP12_VERSION:
1764         case OFP13_VERSION:
1765         case OFP14_VERSION:
1766         case OFP15_VERSION:
1767             break;
1768         default:
1769             OVS_NOT_REACHED();
1770         }
1771     }
1772
1773     monitor_vconn(vconn, true);
1774 }
1775
1776 static void
1777 ofctl_snoop(struct ovs_cmdl_context *ctx)
1778 {
1779     struct vconn *vconn;
1780
1781     open_vconn__(ctx->argv[1], SNOOP, &vconn);
1782     monitor_vconn(vconn, false);
1783 }
1784
1785 static void
1786 ofctl_dump_ports(struct ovs_cmdl_context *ctx)
1787 {
1788     struct ofpbuf *request;
1789     struct vconn *vconn;
1790     ofp_port_t port;
1791
1792     open_vconn(ctx->argv[1], &vconn);
1793     port = ctx->argc > 2 ? str_to_port_no(ctx->argv[1], ctx->argv[2]) : OFPP_ANY;
1794     request = ofputil_encode_dump_ports_request(vconn_get_version(vconn), port);
1795     dump_stats_transaction(vconn, request);
1796     vconn_close(vconn);
1797 }
1798
1799 static void
1800 ofctl_dump_ports_desc(struct ovs_cmdl_context *ctx)
1801 {
1802     struct ofpbuf *request;
1803     struct vconn *vconn;
1804     ofp_port_t port;
1805
1806     open_vconn(ctx->argv[1], &vconn);
1807     port = ctx->argc > 2 ? str_to_port_no(ctx->argv[1], ctx->argv[2]) : OFPP_ANY;
1808     request = ofputil_encode_port_desc_stats_request(vconn_get_version(vconn),
1809                                                      port);
1810     dump_stats_transaction(vconn, request);
1811     vconn_close(vconn);
1812 }
1813
1814 static void
1815 ofctl_probe(struct ovs_cmdl_context *ctx)
1816 {
1817     struct ofpbuf *request;
1818     struct vconn *vconn;
1819     struct ofpbuf *reply;
1820
1821     open_vconn(ctx->argv[1], &vconn);
1822     request = make_echo_request(vconn_get_version(vconn));
1823     run(vconn_transact(vconn, request, &reply), "talking to %s", ctx->argv[1]);
1824     if (reply->size != sizeof(struct ofp_header)) {
1825         ovs_fatal(0, "reply does not match request");
1826     }
1827     ofpbuf_delete(reply);
1828     vconn_close(vconn);
1829 }
1830
1831 static void
1832 ofctl_packet_out(struct ovs_cmdl_context *ctx)
1833 {
1834     enum ofputil_protocol protocol;
1835     struct ofputil_packet_out po;
1836     struct ofpbuf ofpacts;
1837     struct vconn *vconn;
1838     char *error;
1839     int i;
1840     enum ofputil_protocol usable_protocols; /* XXX: Use in proto selection */
1841
1842     ofpbuf_init(&ofpacts, 64);
1843     error = ofpacts_parse_actions(ctx->argv[3], &ofpacts, &usable_protocols);
1844     if (error) {
1845         ovs_fatal(0, "%s", error);
1846     }
1847
1848     po.buffer_id = UINT32_MAX;
1849     po.in_port = str_to_port_no(ctx->argv[1], ctx->argv[2]);
1850     po.ofpacts = ofpacts.data;
1851     po.ofpacts_len = ofpacts.size;
1852
1853     protocol = open_vconn(ctx->argv[1], &vconn);
1854     for (i = 4; i < ctx->argc; i++) {
1855         struct dp_packet *packet;
1856         struct ofpbuf *opo;
1857         const char *error_msg;
1858
1859         error_msg = eth_from_hex(ctx->argv[i], &packet);
1860         if (error_msg) {
1861             ovs_fatal(0, "%s", error_msg);
1862         }
1863
1864         po.packet = dp_packet_data(packet);
1865         po.packet_len = dp_packet_size(packet);
1866         opo = ofputil_encode_packet_out(&po, protocol);
1867         transact_noreply(vconn, opo);
1868         dp_packet_delete(packet);
1869     }
1870     vconn_close(vconn);
1871     ofpbuf_uninit(&ofpacts);
1872 }
1873
1874 static void
1875 ofctl_mod_port(struct ovs_cmdl_context *ctx)
1876 {
1877     struct ofp_config_flag {
1878         const char *name;             /* The flag's name. */
1879         enum ofputil_port_config bit; /* Bit to turn on or off. */
1880         bool on;                      /* Value to set the bit to. */
1881     };
1882     static const struct ofp_config_flag flags[] = {
1883         { "up",          OFPUTIL_PC_PORT_DOWN,    false },
1884         { "down",        OFPUTIL_PC_PORT_DOWN,    true  },
1885         { "stp",         OFPUTIL_PC_NO_STP,       false },
1886         { "receive",     OFPUTIL_PC_NO_RECV,      false },
1887         { "receive-stp", OFPUTIL_PC_NO_RECV_STP,  false },
1888         { "flood",       OFPUTIL_PC_NO_FLOOD,     false },
1889         { "forward",     OFPUTIL_PC_NO_FWD,       false },
1890         { "packet-in",   OFPUTIL_PC_NO_PACKET_IN, false },
1891     };
1892
1893     const struct ofp_config_flag *flag;
1894     enum ofputil_protocol protocol;
1895     struct ofputil_port_mod pm;
1896     struct ofputil_phy_port pp;
1897     struct vconn *vconn;
1898     const char *command;
1899     bool not;
1900
1901     fetch_ofputil_phy_port(ctx->argv[1], ctx->argv[2], &pp);
1902
1903     pm.port_no = pp.port_no;
1904     pm.hw_addr = pp.hw_addr;
1905     pm.config = 0;
1906     pm.mask = 0;
1907     pm.advertise = 0;
1908
1909     if (!strncasecmp(ctx->argv[3], "no-", 3)) {
1910         command = ctx->argv[3] + 3;
1911         not = true;
1912     } else if (!strncasecmp(ctx->argv[3], "no", 2)) {
1913         command = ctx->argv[3] + 2;
1914         not = true;
1915     } else {
1916         command = ctx->argv[3];
1917         not = false;
1918     }
1919     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1920         if (!strcasecmp(command, flag->name)) {
1921             pm.mask = flag->bit;
1922             pm.config = flag->on ^ not ? flag->bit : 0;
1923             goto found;
1924         }
1925     }
1926     ovs_fatal(0, "unknown mod-port command '%s'", ctx->argv[3]);
1927
1928 found:
1929     protocol = open_vconn(ctx->argv[1], &vconn);
1930     transact_noreply(vconn, ofputil_encode_port_mod(&pm, protocol));
1931     vconn_close(vconn);
1932 }
1933
1934 static void
1935 ofctl_mod_table(struct ovs_cmdl_context *ctx)
1936 {
1937     uint32_t usable_versions;
1938     struct ofputil_table_mod tm;
1939     struct vconn *vconn;
1940     char *error;
1941
1942     error = parse_ofp_table_mod(&tm, ctx->argv[2], ctx->argv[3],
1943                                 &usable_versions);
1944     if (error) {
1945         ovs_fatal(0, "%s", error);
1946     }
1947
1948     uint32_t allowed_versions = get_allowed_ofp_versions();
1949     if (!(allowed_versions & usable_versions)) {
1950         struct ds versions = DS_EMPTY_INITIALIZER;
1951         ofputil_format_version_bitmap_names(&versions, allowed_versions);
1952         ovs_fatal(0, "table_mod '%s' requires one of the OpenFlow "
1953                   "versions %s but none is enabled (use -O)",
1954                   ctx->argv[3], ds_cstr(&versions));
1955     }
1956     mask_allowed_ofp_versions(usable_versions);
1957
1958     enum ofputil_protocol protocol = open_vconn(ctx->argv[1], &vconn);
1959     transact_noreply(vconn, ofputil_encode_table_mod(&tm, protocol));
1960     vconn_close(vconn);
1961 }
1962
1963 static void
1964 ofctl_get_frags(struct ovs_cmdl_context *ctx)
1965 {
1966     struct ofp_switch_config config;
1967     struct vconn *vconn;
1968
1969     open_vconn(ctx->argv[1], &vconn);
1970     fetch_switch_config(vconn, &config);
1971     puts(ofputil_frag_handling_to_string(ntohs(config.flags)));
1972     vconn_close(vconn);
1973 }
1974
1975 static void
1976 ofctl_set_frags(struct ovs_cmdl_context *ctx)
1977 {
1978     struct ofp_switch_config config;
1979     enum ofp_config_flags mode;
1980     struct vconn *vconn;
1981     ovs_be16 flags;
1982
1983     if (!ofputil_frag_handling_from_string(ctx->argv[2], &mode)) {
1984         ovs_fatal(0, "%s: unknown fragment handling mode", ctx->argv[2]);
1985     }
1986
1987     open_vconn(ctx->argv[1], &vconn);
1988     fetch_switch_config(vconn, &config);
1989     flags = htons(mode) | (config.flags & htons(~OFPC_FRAG_MASK));
1990     if (flags != config.flags) {
1991         /* Set the configuration. */
1992         config.flags = flags;
1993         set_switch_config(vconn, &config);
1994
1995         /* Then retrieve the configuration to see if it really took.  OpenFlow
1996          * doesn't define error reporting for bad modes, so this is all we can
1997          * do. */
1998         fetch_switch_config(vconn, &config);
1999         if (flags != config.flags) {
2000             ovs_fatal(0, "%s: setting fragment handling mode failed (this "
2001                       "switch probably doesn't support mode \"%s\")",
2002                       ctx->argv[1], ofputil_frag_handling_to_string(mode));
2003         }
2004     }
2005     vconn_close(vconn);
2006 }
2007
2008 static void
2009 ofctl_ofp_parse(struct ovs_cmdl_context *ctx)
2010 {
2011     const char *filename = ctx->argv[1];
2012     struct ofpbuf b;
2013     FILE *file;
2014
2015     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
2016     if (file == NULL) {
2017         ovs_fatal(errno, "%s: open", filename);
2018     }
2019
2020     ofpbuf_init(&b, 65536);
2021     for (;;) {
2022         struct ofp_header *oh;
2023         size_t length, tail_len;
2024         void *tail;
2025         size_t n;
2026
2027         ofpbuf_clear(&b);
2028         oh = ofpbuf_put_uninit(&b, sizeof *oh);
2029         n = fread(oh, 1, sizeof *oh, file);
2030         if (n == 0) {
2031             break;
2032         } else if (n < sizeof *oh) {
2033             ovs_fatal(0, "%s: unexpected end of file mid-message", filename);
2034         }
2035
2036         length = ntohs(oh->length);
2037         if (length < sizeof *oh) {
2038             ovs_fatal(0, "%s: %"PRIuSIZE"-byte message is too short for OpenFlow",
2039                       filename, length);
2040         }
2041
2042         tail_len = length - sizeof *oh;
2043         tail = ofpbuf_put_uninit(&b, tail_len);
2044         n = fread(tail, 1, tail_len, file);
2045         if (n < tail_len) {
2046             ovs_fatal(0, "%s: unexpected end of file mid-message", filename);
2047         }
2048
2049         ofp_print(stdout, b.data, b.size, verbosity + 2);
2050     }
2051     ofpbuf_uninit(&b);
2052
2053     if (file != stdin) {
2054         fclose(file);
2055     }
2056 }
2057
2058 static bool
2059 is_openflow_port(ovs_be16 port_, char *ports[])
2060 {
2061     uint16_t port = ntohs(port_);
2062     if (ports[0]) {
2063         int i;
2064
2065         for (i = 0; ports[i]; i++) {
2066             if (port == atoi(ports[i])) {
2067                 return true;
2068             }
2069         }
2070         return false;
2071     } else {
2072         return port == OFP_PORT || port == OFP_OLD_PORT;
2073     }
2074 }
2075
2076 static void
2077 ofctl_ofp_parse_pcap(struct ovs_cmdl_context *ctx)
2078 {
2079     struct tcp_reader *reader;
2080     FILE *file;
2081     int error;
2082     bool first;
2083
2084     file = ovs_pcap_open(ctx->argv[1], "rb");
2085     if (!file) {
2086         ovs_fatal(errno, "%s: open failed", ctx->argv[1]);
2087     }
2088
2089     reader = tcp_reader_open();
2090     first = true;
2091     for (;;) {
2092         struct dp_packet *packet;
2093         long long int when;
2094         struct flow flow;
2095
2096         error = ovs_pcap_read(file, &packet, &when);
2097         if (error) {
2098             break;
2099         }
2100         pkt_metadata_init(&packet->md, ODPP_NONE);
2101         flow_extract(packet, &flow);
2102         if (flow.dl_type == htons(ETH_TYPE_IP)
2103             && flow.nw_proto == IPPROTO_TCP
2104             && (is_openflow_port(flow.tp_src, ctx->argv + 2) ||
2105                 is_openflow_port(flow.tp_dst, ctx->argv + 2))) {
2106             struct dp_packet *payload = tcp_reader_run(reader, &flow, packet);
2107             if (payload) {
2108                 while (dp_packet_size(payload) >= sizeof(struct ofp_header)) {
2109                     const struct ofp_header *oh;
2110                     void *data = dp_packet_data(payload);
2111                     int length;
2112
2113                     /* Align OpenFlow on 8-byte boundary for safe access. */
2114                     dp_packet_shift(payload, -((intptr_t) data & 7));
2115
2116                     oh = dp_packet_data(payload);
2117                     length = ntohs(oh->length);
2118                     if (dp_packet_size(payload) < length) {
2119                         break;
2120                     }
2121
2122                     if (!first) {
2123                         putchar('\n');
2124                     }
2125                     first = false;
2126
2127                     if (timestamp) {
2128                         char *s = xastrftime_msec("%H:%M:%S.### ", when, true);
2129                         fputs(s, stdout);
2130                         free(s);
2131                     }
2132
2133                     printf(IP_FMT".%"PRIu16" > "IP_FMT".%"PRIu16":\n",
2134                            IP_ARGS(flow.nw_src), ntohs(flow.tp_src),
2135                            IP_ARGS(flow.nw_dst), ntohs(flow.tp_dst));
2136                     ofp_print(stdout, dp_packet_data(payload), length, verbosity + 1);
2137                     dp_packet_pull(payload, length);
2138                 }
2139             }
2140         }
2141         dp_packet_delete(packet);
2142     }
2143     tcp_reader_close(reader);
2144 }
2145
2146 static void
2147 ofctl_ping(struct ovs_cmdl_context *ctx)
2148 {
2149     size_t max_payload = 65535 - sizeof(struct ofp_header);
2150     unsigned int payload;
2151     struct vconn *vconn;
2152     int i;
2153
2154     payload = ctx->argc > 2 ? atoi(ctx->argv[2]) : 64;
2155     if (payload > max_payload) {
2156         ovs_fatal(0, "payload must be between 0 and %"PRIuSIZE" bytes", max_payload);
2157     }
2158
2159     open_vconn(ctx->argv[1], &vconn);
2160     for (i = 0; i < 10; i++) {
2161         struct timeval start, end;
2162         struct ofpbuf *request, *reply;
2163         const struct ofp_header *rpy_hdr;
2164         enum ofptype type;
2165
2166         request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
2167                                vconn_get_version(vconn), payload);
2168         random_bytes(ofpbuf_put_uninit(request, payload), payload);
2169
2170         xgettimeofday(&start);
2171         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
2172         xgettimeofday(&end);
2173
2174         rpy_hdr = reply->data;
2175         if (ofptype_pull(&type, reply)
2176             || type != OFPTYPE_ECHO_REPLY
2177             || reply->size != payload
2178             || memcmp(request->msg, reply->msg, payload)) {
2179             printf("Reply does not match request.  Request:\n");
2180             ofp_print(stdout, request, request->size, verbosity + 2);
2181             printf("Reply:\n");
2182             ofp_print(stdout, reply, reply->size, verbosity + 2);
2183         }
2184         printf("%"PRIu32" bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
2185                reply->size, ctx->argv[1], ntohl(rpy_hdr->xid),
2186                    (1000*(double)(end.tv_sec - start.tv_sec))
2187                    + (.001*(end.tv_usec - start.tv_usec)));
2188         ofpbuf_delete(request);
2189         ofpbuf_delete(reply);
2190     }
2191     vconn_close(vconn);
2192 }
2193
2194 static void
2195 ofctl_benchmark(struct ovs_cmdl_context *ctx)
2196 {
2197     size_t max_payload = 65535 - sizeof(struct ofp_header);
2198     struct timeval start, end;
2199     unsigned int payload_size, message_size;
2200     struct vconn *vconn;
2201     double duration;
2202     int count;
2203     int i;
2204
2205     payload_size = atoi(ctx->argv[2]);
2206     if (payload_size > max_payload) {
2207         ovs_fatal(0, "payload must be between 0 and %"PRIuSIZE" bytes", max_payload);
2208     }
2209     message_size = sizeof(struct ofp_header) + payload_size;
2210
2211     count = atoi(ctx->argv[3]);
2212
2213     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
2214            count, message_size, count * message_size);
2215
2216     open_vconn(ctx->argv[1], &vconn);
2217     xgettimeofday(&start);
2218     for (i = 0; i < count; i++) {
2219         struct ofpbuf *request, *reply;
2220
2221         request = ofpraw_alloc(OFPRAW_OFPT_ECHO_REQUEST,
2222                                vconn_get_version(vconn), payload_size);
2223         ofpbuf_put_zeros(request, payload_size);
2224         run(vconn_transact(vconn, request, &reply), "transact");
2225         ofpbuf_delete(reply);
2226     }
2227     xgettimeofday(&end);
2228     vconn_close(vconn);
2229
2230     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
2231                 + (.001*(end.tv_usec - start.tv_usec)));
2232     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
2233            duration, count / (duration / 1000.0),
2234            count * message_size / (duration / 1000.0));
2235 }
2236
2237 static void
2238 ofctl_group_mod__(const char *remote, struct ofputil_group_mod *gms,
2239                   size_t n_gms, enum ofputil_protocol usable_protocols)
2240 {
2241     enum ofputil_protocol protocol;
2242     struct ofputil_group_mod *gm;
2243     enum ofp_version version;
2244     struct ofpbuf *request;
2245
2246     struct vconn *vconn;
2247     size_t i;
2248
2249     protocol = open_vconn_for_flow_mod(remote, &vconn, usable_protocols);
2250     version = ofputil_protocol_to_ofp_version(protocol);
2251
2252     for (i = 0; i < n_gms; i++) {
2253         gm = &gms[i];
2254         request = ofputil_encode_group_mod(version, gm);
2255         if (request) {
2256             transact_noreply(vconn, request);
2257         }
2258     }
2259
2260     vconn_close(vconn);
2261
2262 }
2263
2264
2265 static void
2266 ofctl_group_mod_file(int argc OVS_UNUSED, char *argv[], uint16_t command)
2267 {
2268     struct ofputil_group_mod *gms = NULL;
2269     enum ofputil_protocol usable_protocols;
2270     size_t n_gms = 0;
2271     char *error;
2272     int i;
2273
2274     error = parse_ofp_group_mod_file(argv[2], command, &gms, &n_gms,
2275                                      &usable_protocols);
2276     if (error) {
2277         ovs_fatal(0, "%s", error);
2278     }
2279     ofctl_group_mod__(argv[1], gms, n_gms, usable_protocols);
2280     for (i = 0; i < n_gms; i++) {
2281         ofputil_bucket_list_destroy(&gms[i].buckets);
2282     }
2283     free(gms);
2284 }
2285
2286 static void
2287 ofctl_group_mod(int argc, char *argv[], uint16_t command)
2288 {
2289     if (argc > 2 && !strcmp(argv[2], "-")) {
2290         ofctl_group_mod_file(argc, argv, command);
2291     } else {
2292         enum ofputil_protocol usable_protocols;
2293         struct ofputil_group_mod gm;
2294         char *error;
2295
2296         error = parse_ofp_group_mod_str(&gm, command, argc > 2 ? argv[2] : "",
2297                                         &usable_protocols);
2298         if (error) {
2299             ovs_fatal(0, "%s", error);
2300         }
2301         ofctl_group_mod__(argv[1], &gm, 1, usable_protocols);
2302         ofputil_bucket_list_destroy(&gm.buckets);
2303     }
2304 }
2305
2306 static void
2307 ofctl_add_group(struct ovs_cmdl_context *ctx)
2308 {
2309     ofctl_group_mod(ctx->argc, ctx->argv, OFPGC11_ADD);
2310 }
2311
2312 static void
2313 ofctl_add_groups(struct ovs_cmdl_context *ctx)
2314 {
2315     ofctl_group_mod_file(ctx->argc, ctx->argv, OFPGC11_ADD);
2316 }
2317
2318 static void
2319 ofctl_mod_group(struct ovs_cmdl_context *ctx)
2320 {
2321     ofctl_group_mod(ctx->argc, ctx->argv, OFPGC11_MODIFY);
2322 }
2323
2324 static void
2325 ofctl_del_groups(struct ovs_cmdl_context *ctx)
2326 {
2327     ofctl_group_mod(ctx->argc, ctx->argv, OFPGC11_DELETE);
2328 }
2329
2330 static void
2331 ofctl_insert_bucket(struct ovs_cmdl_context *ctx)
2332 {
2333     ofctl_group_mod(ctx->argc, ctx->argv, OFPGC15_INSERT_BUCKET);
2334 }
2335
2336 static void
2337 ofctl_remove_bucket(struct ovs_cmdl_context *ctx)
2338 {
2339     ofctl_group_mod(ctx->argc, ctx->argv, OFPGC15_REMOVE_BUCKET);
2340 }
2341
2342 static void
2343 ofctl_dump_group_stats(struct ovs_cmdl_context *ctx)
2344 {
2345     enum ofputil_protocol usable_protocols;
2346     struct ofputil_group_mod gm;
2347     struct ofpbuf *request;
2348     struct vconn *vconn;
2349     uint32_t group_id;
2350     char *error;
2351
2352     memset(&gm, 0, sizeof gm);
2353
2354     error = parse_ofp_group_mod_str(&gm, OFPGC11_DELETE,
2355                                     ctx->argc > 2 ? ctx->argv[2] : "",
2356                                     &usable_protocols);
2357     if (error) {
2358         ovs_fatal(0, "%s", error);
2359     }
2360
2361     group_id = gm.group_id;
2362
2363     open_vconn(ctx->argv[1], &vconn);
2364     request = ofputil_encode_group_stats_request(vconn_get_version(vconn),
2365                                                  group_id);
2366     if (request) {
2367         dump_stats_transaction(vconn, request);
2368     }
2369
2370     vconn_close(vconn);
2371 }
2372
2373 static void
2374 ofctl_dump_group_desc(struct ovs_cmdl_context *ctx)
2375 {
2376     struct ofpbuf *request;
2377     struct vconn *vconn;
2378     uint32_t group_id;
2379
2380     open_vconn(ctx->argv[1], &vconn);
2381
2382     if (ctx->argc < 3 || !ofputil_group_from_string(ctx->argv[2], &group_id)) {
2383         group_id = OFPG11_ALL;
2384     }
2385
2386     request = ofputil_encode_group_desc_request(vconn_get_version(vconn),
2387                                                 group_id);
2388     if (request) {
2389         dump_stats_transaction(vconn, request);
2390     }
2391
2392     vconn_close(vconn);
2393 }
2394
2395 static void
2396 ofctl_dump_group_features(struct ovs_cmdl_context *ctx)
2397 {
2398     struct ofpbuf *request;
2399     struct vconn *vconn;
2400
2401     open_vconn(ctx->argv[1], &vconn);
2402     request = ofputil_encode_group_features_request(vconn_get_version(vconn));
2403     if (request) {
2404         dump_stats_transaction(vconn, request);
2405     }
2406
2407     vconn_close(vconn);
2408 }
2409
2410 static void
2411 ofctl_geneve_mod(struct ovs_cmdl_context *ctx, uint16_t command)
2412 {
2413     enum ofputil_protocol usable_protocols;
2414     enum ofputil_protocol protocol;
2415     struct ofputil_geneve_table_mod gtm;
2416     char *error;
2417     enum ofp_version version;
2418     struct ofpbuf *request;
2419     struct vconn *vconn;
2420
2421     error = parse_ofp_geneve_table_mod_str(&gtm, command, ctx->argc > 2 ?
2422                                            ctx->argv[2] : "",
2423                                            &usable_protocols);
2424     if (error) {
2425         ovs_fatal(0, "%s", error);
2426     }
2427
2428     protocol = open_vconn_for_flow_mod(ctx->argv[1], &vconn, usable_protocols);
2429     version = ofputil_protocol_to_ofp_version(protocol);
2430
2431     request = ofputil_encode_geneve_table_mod(version, &gtm);
2432     if (request) {
2433         transact_noreply(vconn, request);
2434     }
2435
2436     vconn_close(vconn);
2437     ofputil_uninit_geneve_table(&gtm.mappings);
2438 }
2439
2440 static void
2441 ofctl_add_geneve_map(struct ovs_cmdl_context *ctx)
2442 {
2443     ofctl_geneve_mod(ctx, NXGTMC_ADD);
2444 }
2445
2446 static void
2447 ofctl_del_geneve_map(struct ovs_cmdl_context *ctx)
2448 {
2449     ofctl_geneve_mod(ctx, ctx->argc > 2 ? NXGTMC_DELETE : NXGTMC_CLEAR);
2450 }
2451
2452 static void
2453 ofctl_dump_geneve_map(struct ovs_cmdl_context *ctx)
2454 {
2455     dump_trivial_transaction(ctx->argv[1], OFPRAW_NXT_GENEVE_TABLE_REQUEST);
2456 }
2457
2458 static void
2459 ofctl_help(struct ovs_cmdl_context *ctx OVS_UNUSED)
2460 {
2461     usage();
2462 }
2463
2464 static void
2465 ofctl_list_commands(struct ovs_cmdl_context *ctx OVS_UNUSED)
2466 {
2467     ovs_cmdl_print_commands(get_all_commands());
2468 }
2469 \f
2470 /* replace-flows and diff-flows commands. */
2471
2472 /* A flow table entry, possibly with two different versions. */
2473 struct fte {
2474     struct cls_rule rule;       /* Within a "struct classifier". */
2475     struct fte_version *versions[2];
2476 };
2477
2478 /* One version of a Flow Table Entry. */
2479 struct fte_version {
2480     ovs_be64 cookie;
2481     uint16_t idle_timeout;
2482     uint16_t hard_timeout;
2483     uint16_t importance;
2484     uint16_t flags;
2485     struct ofpact *ofpacts;
2486     size_t ofpacts_len;
2487 };
2488
2489 /* Frees 'version' and the data that it owns. */
2490 static void
2491 fte_version_free(struct fte_version *version)
2492 {
2493     if (version) {
2494         free(CONST_CAST(struct ofpact *, version->ofpacts));
2495         free(version);
2496     }
2497 }
2498
2499 /* Returns true if 'a' and 'b' are the same, false if they differ.
2500  *
2501  * Ignores differences in 'flags' because there's no way to retrieve flags from
2502  * an OpenFlow switch.  We have to assume that they are the same. */
2503 static bool
2504 fte_version_equals(const struct fte_version *a, const struct fte_version *b)
2505 {
2506     return (a->cookie == b->cookie
2507             && a->idle_timeout == b->idle_timeout
2508             && a->hard_timeout == b->hard_timeout
2509             && a->importance == b->importance
2510             && ofpacts_equal(a->ofpacts, a->ofpacts_len,
2511                              b->ofpacts, b->ofpacts_len));
2512 }
2513
2514 /* Clears 's', then if 's' has a version 'index', formats 'fte' and version
2515  * 'index' into 's', followed by a new-line. */
2516 static void
2517 fte_version_format(const struct fte *fte, int index, struct ds *s)
2518 {
2519     const struct fte_version *version = fte->versions[index];
2520
2521     ds_clear(s);
2522     if (!version) {
2523         return;
2524     }
2525
2526     cls_rule_format(&fte->rule, s);
2527     if (version->cookie != htonll(0)) {
2528         ds_put_format(s, " cookie=0x%"PRIx64, ntohll(version->cookie));
2529     }
2530     if (version->idle_timeout != OFP_FLOW_PERMANENT) {
2531         ds_put_format(s, " idle_timeout=%"PRIu16, version->idle_timeout);
2532     }
2533     if (version->hard_timeout != OFP_FLOW_PERMANENT) {
2534         ds_put_format(s, " hard_timeout=%"PRIu16, version->hard_timeout);
2535     }
2536     if (version->importance != 0) {
2537         ds_put_format(s, " importance=%"PRIu16, version->importance);
2538     }
2539
2540     ds_put_cstr(s, " actions=");
2541     ofpacts_format(version->ofpacts, version->ofpacts_len, s);
2542
2543     ds_put_char(s, '\n');
2544 }
2545
2546 static struct fte *
2547 fte_from_cls_rule(const struct cls_rule *cls_rule)
2548 {
2549     return cls_rule ? CONTAINER_OF(cls_rule, struct fte, rule) : NULL;
2550 }
2551
2552 /* Frees 'fte' and its versions. */
2553 static void
2554 fte_free(struct fte *fte)
2555 {
2556     if (fte) {
2557         fte_version_free(fte->versions[0]);
2558         fte_version_free(fte->versions[1]);
2559         cls_rule_destroy(&fte->rule);
2560         free(fte);
2561     }
2562 }
2563
2564 /* Frees all of the FTEs within 'cls'. */
2565 static void
2566 fte_free_all(struct classifier *cls)
2567 {
2568     struct fte *fte;
2569
2570     classifier_defer(cls);
2571     CLS_FOR_EACH (fte, rule, cls) {
2572         classifier_remove(cls, &fte->rule);
2573         ovsrcu_postpone(fte_free, fte);
2574     }
2575     classifier_destroy(cls);
2576 }
2577
2578 /* Searches 'cls' for an FTE matching 'rule', inserting a new one if
2579  * necessary.  Sets 'version' as the version of that rule with the given
2580  * 'index', replacing any existing version, if any.
2581  *
2582  * Takes ownership of 'version'. */
2583 static void
2584 fte_insert(struct classifier *cls, const struct match *match,
2585            int priority, struct fte_version *version, int index)
2586 {
2587     struct fte *old, *fte;
2588
2589     fte = xzalloc(sizeof *fte);
2590     cls_rule_init(&fte->rule, match, priority);
2591     fte->versions[index] = version;
2592
2593     old = fte_from_cls_rule(classifier_replace(cls, &fte->rule,
2594                                                CLS_MIN_VERSION, NULL, 0));
2595     if (old) {
2596         fte->versions[!index] = old->versions[!index];
2597         old->versions[!index] = NULL;
2598
2599         ovsrcu_postpone(fte_free, old);
2600     }
2601 }
2602
2603 /* Reads the flows in 'filename' as flow table entries in 'cls' for the version
2604  * with the specified 'index'.  Returns the flow formats able to represent the
2605  * flows that were read. */
2606 static enum ofputil_protocol
2607 read_flows_from_file(const char *filename, struct classifier *cls, int index)
2608 {
2609     enum ofputil_protocol usable_protocols;
2610     int line_number;
2611     struct ds s;
2612     FILE *file;
2613
2614     file = !strcmp(filename, "-") ? stdin : fopen(filename, "r");
2615     if (file == NULL) {
2616         ovs_fatal(errno, "%s: open", filename);
2617     }
2618
2619     ds_init(&s);
2620     usable_protocols = OFPUTIL_P_ANY;
2621     line_number = 0;
2622     classifier_defer(cls);
2623     while (!ds_get_preprocessed_line(&s, file, &line_number)) {
2624         struct fte_version *version;
2625         struct ofputil_flow_mod fm;
2626         char *error;
2627         enum ofputil_protocol usable;
2628
2629         error = parse_ofp_str(&fm, OFPFC_ADD, ds_cstr(&s), &usable);
2630         if (error) {
2631             ovs_fatal(0, "%s:%d: %s", filename, line_number, error);
2632         }
2633         usable_protocols &= usable;
2634
2635         version = xmalloc(sizeof *version);
2636         version->cookie = fm.new_cookie;
2637         version->idle_timeout = fm.idle_timeout;
2638         version->hard_timeout = fm.hard_timeout;
2639         version->importance = fm.importance;
2640         version->flags = fm.flags & (OFPUTIL_FF_SEND_FLOW_REM
2641                                      | OFPUTIL_FF_EMERG);
2642         version->ofpacts = fm.ofpacts;
2643         version->ofpacts_len = fm.ofpacts_len;
2644
2645         fte_insert(cls, &fm.match, fm.priority, version, index);
2646     }
2647     classifier_publish(cls);
2648     ds_destroy(&s);
2649
2650     if (file != stdin) {
2651         fclose(file);
2652     }
2653
2654     return usable_protocols;
2655 }
2656
2657 static bool
2658 recv_flow_stats_reply(struct vconn *vconn, ovs_be32 send_xid,
2659                       struct ofpbuf **replyp,
2660                       struct ofputil_flow_stats *fs, struct ofpbuf *ofpacts)
2661 {
2662     struct ofpbuf *reply = *replyp;
2663
2664     for (;;) {
2665         int retval;
2666         bool more;
2667
2668         /* Get a flow stats reply message, if we don't already have one. */
2669         if (!reply) {
2670             enum ofptype type;
2671             enum ofperr error;
2672
2673             do {
2674                 run(vconn_recv_block(vconn, &reply),
2675                     "OpenFlow packet receive failed");
2676             } while (((struct ofp_header *) reply->data)->xid != send_xid);
2677
2678             error = ofptype_decode(&type, reply->data);
2679             if (error || type != OFPTYPE_FLOW_STATS_REPLY) {
2680                 ovs_fatal(0, "received bad reply: %s",
2681                           ofp_to_string(reply->data, reply->size,
2682                                         verbosity + 1));
2683             }
2684         }
2685
2686         /* Pull an individual flow stats reply out of the message. */
2687         retval = ofputil_decode_flow_stats_reply(fs, reply, false, ofpacts);
2688         switch (retval) {
2689         case 0:
2690             *replyp = reply;
2691             return true;
2692
2693         case EOF:
2694             more = ofpmp_more(reply->header);
2695             ofpbuf_delete(reply);
2696             reply = NULL;
2697             if (!more) {
2698                 *replyp = NULL;
2699                 return false;
2700             }
2701             break;
2702
2703         default:
2704             ovs_fatal(0, "parse error in reply (%s)",
2705                       ofperr_to_string(retval));
2706         }
2707     }
2708 }
2709
2710 /* Reads the OpenFlow flow table from 'vconn', which has currently active flow
2711  * format 'protocol', and adds them as flow table entries in 'cls' for the
2712  * version with the specified 'index'. */
2713 static void
2714 read_flows_from_switch(struct vconn *vconn,
2715                        enum ofputil_protocol protocol,
2716                        struct classifier *cls, int index)
2717 {
2718     struct ofputil_flow_stats_request fsr;
2719     struct ofputil_flow_stats fs;
2720     struct ofpbuf *request;
2721     struct ofpbuf ofpacts;
2722     struct ofpbuf *reply;
2723     ovs_be32 send_xid;
2724
2725     fsr.aggregate = false;
2726     match_init_catchall(&fsr.match);
2727     fsr.out_port = OFPP_ANY;
2728     fsr.out_group = OFPG_ANY;
2729     fsr.table_id = 0xff;
2730     fsr.cookie = fsr.cookie_mask = htonll(0);
2731     request = ofputil_encode_flow_stats_request(&fsr, protocol);
2732     send_xid = ((struct ofp_header *) request->data)->xid;
2733     send_openflow_buffer(vconn, request);
2734
2735     reply = NULL;
2736     ofpbuf_init(&ofpacts, 0);
2737     classifier_defer(cls);
2738     while (recv_flow_stats_reply(vconn, send_xid, &reply, &fs, &ofpacts)) {
2739         struct fte_version *version;
2740
2741         version = xmalloc(sizeof *version);
2742         version->cookie = fs.cookie;
2743         version->idle_timeout = fs.idle_timeout;
2744         version->hard_timeout = fs.hard_timeout;
2745         version->importance = fs.importance;
2746         version->flags = 0;
2747         version->ofpacts_len = fs.ofpacts_len;
2748         version->ofpacts = xmemdup(fs.ofpacts, fs.ofpacts_len);
2749
2750         fte_insert(cls, &fs.match, fs.priority, version, index);
2751     }
2752     classifier_publish(cls);
2753     ofpbuf_uninit(&ofpacts);
2754 }
2755
2756 static void
2757 fte_make_flow_mod(const struct fte *fte, int index, uint16_t command,
2758                   enum ofputil_protocol protocol, struct ovs_list *packets)
2759 {
2760     const struct fte_version *version = fte->versions[index];
2761     struct ofputil_flow_mod fm;
2762     struct ofpbuf *ofm;
2763
2764     minimatch_expand(&fte->rule.match, &fm.match);
2765     fm.priority = fte->rule.priority;
2766     fm.cookie = htonll(0);
2767     fm.cookie_mask = htonll(0);
2768     fm.new_cookie = version->cookie;
2769     fm.modify_cookie = true;
2770     fm.table_id = 0xff;
2771     fm.command = command;
2772     fm.idle_timeout = version->idle_timeout;
2773     fm.hard_timeout = version->hard_timeout;
2774     fm.importance = version->importance;
2775     fm.buffer_id = UINT32_MAX;
2776     fm.out_port = OFPP_ANY;
2777     fm.out_group = OFPG_ANY;
2778     fm.flags = version->flags;
2779     if (command == OFPFC_ADD || command == OFPFC_MODIFY ||
2780         command == OFPFC_MODIFY_STRICT) {
2781         fm.ofpacts = version->ofpacts;
2782         fm.ofpacts_len = version->ofpacts_len;
2783     } else {
2784         fm.ofpacts = NULL;
2785         fm.ofpacts_len = 0;
2786     }
2787     fm.delete_reason = OFPRR_DELETE;
2788
2789     ofm = ofputil_encode_flow_mod(&fm, protocol);
2790     list_push_back(packets, &ofm->list_node);
2791 }
2792
2793 static void
2794 ofctl_replace_flows(struct ovs_cmdl_context *ctx)
2795 {
2796     enum { FILE_IDX = 0, SWITCH_IDX = 1 };
2797     enum ofputil_protocol usable_protocols, protocol;
2798     struct classifier cls;
2799     struct ovs_list requests;
2800     struct vconn *vconn;
2801     struct fte *fte;
2802
2803     classifier_init(&cls, NULL);
2804     usable_protocols = read_flows_from_file(ctx->argv[2], &cls, FILE_IDX);
2805
2806     protocol = open_vconn(ctx->argv[1], &vconn);
2807     protocol = set_protocol_for_flow_dump(vconn, protocol, usable_protocols);
2808
2809     read_flows_from_switch(vconn, protocol, &cls, SWITCH_IDX);
2810
2811     list_init(&requests);
2812
2813     /* Delete flows that exist on the switch but not in the file. */
2814     CLS_FOR_EACH (fte, rule, &cls) {
2815         struct fte_version *file_ver = fte->versions[FILE_IDX];
2816         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
2817
2818         if (sw_ver && !file_ver) {
2819             fte_make_flow_mod(fte, SWITCH_IDX, OFPFC_DELETE_STRICT,
2820                               protocol, &requests);
2821         }
2822     }
2823
2824     /* Add flows that exist in the file but not on the switch.
2825      * Update flows that exist in both places but differ. */
2826     CLS_FOR_EACH (fte, rule, &cls) {
2827         struct fte_version *file_ver = fte->versions[FILE_IDX];
2828         struct fte_version *sw_ver = fte->versions[SWITCH_IDX];
2829
2830         if (file_ver
2831             && (readd || !sw_ver || !fte_version_equals(sw_ver, file_ver))) {
2832             fte_make_flow_mod(fte, FILE_IDX, OFPFC_ADD, protocol, &requests);
2833         }
2834     }
2835     if (bundle) {
2836         bundle_transact(vconn, &requests, OFPBF_ORDERED | OFPBF_ATOMIC);
2837     } else {
2838         transact_multiple_noreply(vconn, &requests);
2839     }
2840     vconn_close(vconn);
2841
2842     fte_free_all(&cls);
2843 }
2844
2845 static void
2846 read_flows_from_source(const char *source, struct classifier *cls, int index)
2847 {
2848     struct stat s;
2849
2850     if (source[0] == '/' || source[0] == '.'
2851         || (!strchr(source, ':') && !stat(source, &s))) {
2852         read_flows_from_file(source, cls, index);
2853     } else {
2854         enum ofputil_protocol protocol;
2855         struct vconn *vconn;
2856
2857         protocol = open_vconn(source, &vconn);
2858         protocol = set_protocol_for_flow_dump(vconn, protocol, OFPUTIL_P_ANY);
2859         read_flows_from_switch(vconn, protocol, cls, index);
2860         vconn_close(vconn);
2861     }
2862 }
2863
2864 static void
2865 ofctl_diff_flows(struct ovs_cmdl_context *ctx)
2866 {
2867     bool differences = false;
2868     struct classifier cls;
2869     struct ds a_s, b_s;
2870     struct fte *fte;
2871
2872     classifier_init(&cls, NULL);
2873     read_flows_from_source(ctx->argv[1], &cls, 0);
2874     read_flows_from_source(ctx->argv[2], &cls, 1);
2875
2876     ds_init(&a_s);
2877     ds_init(&b_s);
2878
2879     CLS_FOR_EACH (fte, rule, &cls) {
2880         struct fte_version *a = fte->versions[0];
2881         struct fte_version *b = fte->versions[1];
2882
2883         if (!a || !b || !fte_version_equals(a, b)) {
2884             fte_version_format(fte, 0, &a_s);
2885             fte_version_format(fte, 1, &b_s);
2886             if (strcmp(ds_cstr(&a_s), ds_cstr(&b_s))) {
2887                 if (a_s.length) {
2888                     printf("-%s", ds_cstr(&a_s));
2889                 }
2890                 if (b_s.length) {
2891                     printf("+%s", ds_cstr(&b_s));
2892                 }
2893                 differences = true;
2894             }
2895         }
2896     }
2897
2898     ds_destroy(&a_s);
2899     ds_destroy(&b_s);
2900
2901     fte_free_all(&cls);
2902
2903     if (differences) {
2904         exit(2);
2905     }
2906 }
2907
2908 static void
2909 ofctl_meter_mod__(const char *bridge, const char *str, int command)
2910 {
2911     struct ofputil_meter_mod mm;
2912     struct vconn *vconn;
2913     enum ofputil_protocol protocol;
2914     enum ofputil_protocol usable_protocols;
2915     enum ofp_version version;
2916
2917     if (str) {
2918         char *error;
2919         error = parse_ofp_meter_mod_str(&mm, str, command, &usable_protocols);
2920         if (error) {
2921             ovs_fatal(0, "%s", error);
2922         }
2923     } else {
2924         usable_protocols = OFPUTIL_P_OF13_UP;
2925         mm.command = command;
2926         mm.meter.meter_id = OFPM13_ALL;
2927     }
2928
2929     protocol = open_vconn_for_flow_mod(bridge, &vconn, usable_protocols);
2930     version = ofputil_protocol_to_ofp_version(protocol);
2931     transact_noreply(vconn, ofputil_encode_meter_mod(version, &mm));
2932     vconn_close(vconn);
2933 }
2934
2935 static void
2936 ofctl_meter_request__(const char *bridge, const char *str,
2937                       enum ofputil_meter_request_type type)
2938 {
2939     struct ofputil_meter_mod mm;
2940     struct vconn *vconn;
2941     enum ofputil_protocol usable_protocols;
2942     enum ofputil_protocol protocol;
2943     enum ofp_version version;
2944
2945     if (str) {
2946         char *error;
2947         error = parse_ofp_meter_mod_str(&mm, str, -1, &usable_protocols);
2948         if (error) {
2949             ovs_fatal(0, "%s", error);
2950         }
2951     } else {
2952         usable_protocols = OFPUTIL_P_OF13_UP;
2953         mm.meter.meter_id = OFPM13_ALL;
2954     }
2955
2956     protocol = open_vconn_for_flow_mod(bridge, &vconn, usable_protocols);
2957     version = ofputil_protocol_to_ofp_version(protocol);
2958     transact_noreply(vconn, ofputil_encode_meter_request(version,
2959                                                          type,
2960                                                          mm.meter.meter_id));
2961     vconn_close(vconn);
2962 }
2963
2964
2965 static void
2966 ofctl_add_meter(struct ovs_cmdl_context *ctx)
2967 {
2968     ofctl_meter_mod__(ctx->argv[1], ctx->argv[2], OFPMC13_ADD);
2969 }
2970
2971 static void
2972 ofctl_mod_meter(struct ovs_cmdl_context *ctx)
2973 {
2974     ofctl_meter_mod__(ctx->argv[1], ctx->argv[2], OFPMC13_MODIFY);
2975 }
2976
2977 static void
2978 ofctl_del_meters(struct ovs_cmdl_context *ctx)
2979 {
2980     ofctl_meter_mod__(ctx->argv[1], ctx->argc > 2 ? ctx->argv[2] : NULL, OFPMC13_DELETE);
2981 }
2982
2983 static void
2984 ofctl_dump_meters(struct ovs_cmdl_context *ctx)
2985 {
2986     ofctl_meter_request__(ctx->argv[1], ctx->argc > 2 ? ctx->argv[2] : NULL,
2987                           OFPUTIL_METER_CONFIG);
2988 }
2989
2990 static void
2991 ofctl_meter_stats(struct ovs_cmdl_context *ctx)
2992 {
2993     ofctl_meter_request__(ctx->argv[1], ctx->argc > 2 ? ctx->argv[2] : NULL,
2994                           OFPUTIL_METER_STATS);
2995 }
2996
2997 static void
2998 ofctl_meter_features(struct ovs_cmdl_context *ctx)
2999 {
3000     ofctl_meter_request__(ctx->argv[1], NULL, OFPUTIL_METER_FEATURES);
3001 }
3002
3003 \f
3004 /* Undocumented commands for unit testing. */
3005
3006 static void
3007 ofctl_parse_flows__(struct ofputil_flow_mod *fms, size_t n_fms,
3008                     enum ofputil_protocol usable_protocols)
3009 {
3010     enum ofputil_protocol protocol = 0;
3011     char *usable_s;
3012     size_t i;
3013
3014     usable_s = ofputil_protocols_to_string(usable_protocols);
3015     printf("usable protocols: %s\n", usable_s);
3016     free(usable_s);
3017
3018     if (!(usable_protocols & allowed_protocols)) {
3019         ovs_fatal(0, "no usable protocol");
3020     }
3021     for (i = 0; i < sizeof(enum ofputil_protocol) * CHAR_BIT; i++) {
3022         protocol = 1 << i;
3023         if (protocol & usable_protocols & allowed_protocols) {
3024             break;
3025         }
3026     }
3027     ovs_assert(is_pow2(protocol));
3028
3029     printf("chosen protocol: %s\n", ofputil_protocol_to_string(protocol));
3030
3031     for (i = 0; i < n_fms; i++) {
3032         struct ofputil_flow_mod *fm = &fms[i];
3033         struct ofpbuf *msg;
3034
3035         msg = ofputil_encode_flow_mod(fm, protocol);
3036         ofp_print(stdout, msg->data, msg->size, verbosity);
3037         ofpbuf_delete(msg);
3038
3039         free(CONST_CAST(struct ofpact *, fm->ofpacts));
3040     }
3041 }
3042
3043 /* "parse-flow FLOW": parses the argument as a flow (like add-flow) and prints
3044  * it back to stdout.  */
3045 static void
3046 ofctl_parse_flow(struct ovs_cmdl_context *ctx)
3047 {
3048     enum ofputil_protocol usable_protocols;
3049     struct ofputil_flow_mod fm;
3050     char *error;
3051
3052     error = parse_ofp_flow_mod_str(&fm, ctx->argv[1], OFPFC_ADD, &usable_protocols);
3053     if (error) {
3054         ovs_fatal(0, "%s", error);
3055     }
3056     ofctl_parse_flows__(&fm, 1, usable_protocols);
3057 }
3058
3059 /* "parse-flows FILENAME": reads the named file as a sequence of flows (like
3060  * add-flows) and prints each of the flows back to stdout.  */
3061 static void
3062 ofctl_parse_flows(struct ovs_cmdl_context *ctx)
3063 {
3064     enum ofputil_protocol usable_protocols;
3065     struct ofputil_flow_mod *fms = NULL;
3066     size_t n_fms = 0;
3067     char *error;
3068
3069     error = parse_ofp_flow_mod_file(ctx->argv[1], OFPFC_ADD, &fms, &n_fms,
3070                                     &usable_protocols);
3071     if (error) {
3072         ovs_fatal(0, "%s", error);
3073     }
3074     ofctl_parse_flows__(fms, n_fms, usable_protocols);
3075     free(fms);
3076 }
3077
3078 static void
3079 ofctl_parse_nxm__(bool oxm, enum ofp_version version)
3080 {
3081     struct ds in;
3082
3083     ds_init(&in);
3084     while (!ds_get_test_line(&in, stdin)) {
3085         struct ofpbuf nx_match;
3086         struct match match;
3087         ovs_be64 cookie, cookie_mask;
3088         enum ofperr error;
3089         int match_len;
3090
3091         /* Convert string to nx_match. */
3092         ofpbuf_init(&nx_match, 0);
3093         if (oxm) {
3094             match_len = oxm_match_from_string(ds_cstr(&in), &nx_match);
3095         } else {
3096             match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
3097         }
3098
3099         /* Convert nx_match to match. */
3100         if (strict) {
3101             if (oxm) {
3102                 error = oxm_pull_match(&nx_match, &match);
3103             } else {
3104                 error = nx_pull_match(&nx_match, match_len, &match,
3105                                       &cookie, &cookie_mask);
3106             }
3107         } else {
3108             if (oxm) {
3109                 error = oxm_pull_match_loose(&nx_match, &match);
3110             } else {
3111                 error = nx_pull_match_loose(&nx_match, match_len, &match,
3112                                             &cookie, &cookie_mask);
3113             }
3114         }
3115
3116
3117         if (!error) {
3118             char *out;
3119
3120             /* Convert match back to nx_match. */
3121             ofpbuf_uninit(&nx_match);
3122             ofpbuf_init(&nx_match, 0);
3123             if (oxm) {
3124                 match_len = oxm_put_match(&nx_match, &match, version);
3125                 out = oxm_match_to_string(&nx_match, match_len);
3126             } else {
3127                 match_len = nx_put_match(&nx_match, &match,
3128                                          cookie, cookie_mask);
3129                 out = nx_match_to_string(nx_match.data, match_len);
3130             }
3131
3132             puts(out);
3133             free(out);
3134
3135             if (verbosity > 0) {
3136                 ovs_hex_dump(stdout, nx_match.data, nx_match.size, 0, false);
3137             }
3138         } else {
3139             printf("nx_pull_match() returned error %s\n",
3140                    ofperr_get_name(error));
3141         }
3142
3143         ofpbuf_uninit(&nx_match);
3144     }
3145     ds_destroy(&in);
3146 }
3147
3148 /* "parse-nxm": reads a series of NXM nx_match specifications as strings from
3149  * stdin, does some internal fussing with them, and then prints them back as
3150  * strings on stdout. */
3151 static void
3152 ofctl_parse_nxm(struct ovs_cmdl_context *ctx OVS_UNUSED)
3153 {
3154     ofctl_parse_nxm__(false, 0);
3155 }
3156
3157 /* "parse-oxm VERSION": reads a series of OXM nx_match specifications as
3158  * strings from stdin, does some internal fussing with them, and then prints
3159  * them back as strings on stdout.  VERSION must specify an OpenFlow version,
3160  * e.g. "OpenFlow12". */
3161 static void
3162 ofctl_parse_oxm(struct ovs_cmdl_context *ctx)
3163 {
3164     enum ofp_version version = ofputil_version_from_string(ctx->argv[1]);
3165     if (version < OFP12_VERSION) {
3166         ovs_fatal(0, "%s: not a valid version for OXM", ctx->argv[1]);
3167     }
3168
3169     ofctl_parse_nxm__(true, version);
3170 }
3171
3172 static void
3173 print_differences(const char *prefix,
3174                   const void *a_, size_t a_len,
3175                   const void *b_, size_t b_len)
3176 {
3177     const uint8_t *a = a_;
3178     const uint8_t *b = b_;
3179     size_t i;
3180
3181     for (i = 0; i < MIN(a_len, b_len); i++) {
3182         if (a[i] != b[i]) {
3183             printf("%s%2"PRIuSIZE": %02"PRIx8" -> %02"PRIx8"\n",
3184                    prefix, i, a[i], b[i]);
3185         }
3186     }
3187     for (i = a_len; i < b_len; i++) {
3188         printf("%s%2"PRIuSIZE": (none) -> %02"PRIx8"\n", prefix, i, b[i]);
3189     }
3190     for (i = b_len; i < a_len; i++) {
3191         printf("%s%2"PRIuSIZE": %02"PRIx8" -> (none)\n", prefix, i, a[i]);
3192     }
3193 }
3194
3195 static void
3196 ofctl_parse_actions__(const char *version_s, bool instructions)
3197 {
3198     enum ofp_version version;
3199     struct ds in;
3200
3201     version = ofputil_version_from_string(version_s);
3202     if (!version) {
3203         ovs_fatal(0, "%s: not a valid OpenFlow version", version_s);
3204     }
3205
3206     ds_init(&in);
3207     while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3208         struct ofpbuf of_out;
3209         struct ofpbuf of_in;
3210         struct ofpbuf ofpacts;
3211         const char *table_id;
3212         char *actions;
3213         enum ofperr error;
3214         size_t size;
3215         struct ds s;
3216
3217         /* Parse table_id separated with the follow-up actions by ",", if
3218          * any. */
3219         actions = ds_cstr(&in);
3220         table_id = NULL;
3221         if (strstr(actions, ",")) {
3222             table_id = strsep(&actions, ",");
3223         }
3224
3225         /* Parse hex bytes. */
3226         ofpbuf_init(&of_in, 0);
3227         if (ofpbuf_put_hex(&of_in, actions, NULL)[0] != '\0') {
3228             ovs_fatal(0, "Trailing garbage in hex data");
3229         }
3230
3231         /* Convert to ofpacts. */
3232         ofpbuf_init(&ofpacts, 0);
3233         size = of_in.size;
3234         error = (instructions
3235                  ? ofpacts_pull_openflow_instructions
3236                  : ofpacts_pull_openflow_actions)(
3237                      &of_in, of_in.size, version, &ofpacts);
3238         if (!error && instructions) {
3239             /* Verify actions, enforce consistency. */
3240             enum ofputil_protocol protocol;
3241             struct flow flow;
3242
3243             memset(&flow, 0, sizeof flow);
3244             protocol = ofputil_protocols_from_ofp_version(version);
3245             error = ofpacts_check_consistency(ofpacts.data, ofpacts.size,
3246                                               &flow, OFPP_MAX,
3247                                               table_id ? atoi(table_id) : 0,
3248                                               255, protocol);
3249         }
3250         if (error) {
3251             printf("bad %s %s: %s\n\n",
3252                    version_s, instructions ? "instructions" : "actions",
3253                    ofperr_get_name(error));
3254             ofpbuf_uninit(&ofpacts);
3255             ofpbuf_uninit(&of_in);
3256             continue;
3257         }
3258         ofpbuf_push_uninit(&of_in, size);
3259
3260         /* Print cls_rule. */
3261         ds_init(&s);
3262         ds_put_cstr(&s, "actions=");
3263         ofpacts_format(ofpacts.data, ofpacts.size, &s);
3264         puts(ds_cstr(&s));
3265         ds_destroy(&s);
3266
3267         /* Convert back to ofp10 actions and print differences from input. */
3268         ofpbuf_init(&of_out, 0);
3269         if (instructions) {
3270            ofpacts_put_openflow_instructions(ofpacts.data, ofpacts.size,
3271                                              &of_out, version);
3272         } else {
3273            ofpacts_put_openflow_actions(ofpacts.data, ofpacts.size,
3274                                          &of_out, version);
3275         }
3276
3277         print_differences("", of_in.data, of_in.size,
3278                           of_out.data, of_out.size);
3279         putchar('\n');
3280
3281         ofpbuf_uninit(&ofpacts);
3282         ofpbuf_uninit(&of_in);
3283         ofpbuf_uninit(&of_out);
3284     }
3285     ds_destroy(&in);
3286 }
3287
3288 /* "parse-actions VERSION": reads a series of action specifications for the
3289  * given OpenFlow VERSION as hex bytes from stdin, converts them to ofpacts,
3290  * prints them as strings on stdout, and then converts them back to hex bytes
3291  * and prints any differences from the input. */
3292 static void
3293 ofctl_parse_actions(struct ovs_cmdl_context *ctx)
3294 {
3295     ofctl_parse_actions__(ctx->argv[1], false);
3296 }
3297
3298 /* "parse-actions VERSION": reads a series of instruction specifications for
3299  * the given OpenFlow VERSION as hex bytes from stdin, converts them to
3300  * ofpacts, prints them as strings on stdout, and then converts them back to
3301  * hex bytes and prints any differences from the input. */
3302 static void
3303 ofctl_parse_instructions(struct ovs_cmdl_context *ctx)
3304 {
3305     ofctl_parse_actions__(ctx->argv[1], true);
3306 }
3307
3308 /* "parse-ofp10-match": reads a series of ofp10_match specifications as hex
3309  * bytes from stdin, converts them to cls_rules, prints them as strings on
3310  * stdout, and then converts them back to hex bytes and prints any differences
3311  * from the input.
3312  *
3313  * The input hex bytes may contain "x"s to represent "don't-cares", bytes whose
3314  * values are ignored in the input and will be set to zero when OVS converts
3315  * them back to hex bytes.  ovs-ofctl actually sets "x"s to random bits when
3316  * it does the conversion to hex, to ensure that in fact they are ignored. */
3317 static void
3318 ofctl_parse_ofp10_match(struct ovs_cmdl_context *ctx OVS_UNUSED)
3319 {
3320     struct ds expout;
3321     struct ds in;
3322
3323     ds_init(&in);
3324     ds_init(&expout);
3325     while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3326         struct ofpbuf match_in, match_expout;
3327         struct ofp10_match match_out;
3328         struct ofp10_match match_normal;
3329         struct match match;
3330         char *p;
3331
3332         /* Parse hex bytes to use for expected output. */
3333         ds_clear(&expout);
3334         ds_put_cstr(&expout, ds_cstr(&in));
3335         for (p = ds_cstr(&expout); *p; p++) {
3336             if (*p == 'x') {
3337                 *p = '0';
3338             }
3339         }
3340         ofpbuf_init(&match_expout, 0);
3341         if (ofpbuf_put_hex(&match_expout, ds_cstr(&expout), NULL)[0] != '\0') {
3342             ovs_fatal(0, "Trailing garbage in hex data");
3343         }
3344         if (match_expout.size != sizeof(struct ofp10_match)) {
3345             ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
3346                       match_expout.size, sizeof(struct ofp10_match));
3347         }
3348
3349         /* Parse hex bytes for input. */
3350         for (p = ds_cstr(&in); *p; p++) {
3351             if (*p == 'x') {
3352                 *p = "0123456789abcdef"[random_uint32() & 0xf];
3353             }
3354         }
3355         ofpbuf_init(&match_in, 0);
3356         if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
3357             ovs_fatal(0, "Trailing garbage in hex data");
3358         }
3359         if (match_in.size != sizeof(struct ofp10_match)) {
3360             ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
3361                       match_in.size, sizeof(struct ofp10_match));
3362         }
3363
3364         /* Convert to cls_rule and print. */
3365         ofputil_match_from_ofp10_match(match_in.data, &match);
3366         match_print(&match);
3367
3368         /* Convert back to ofp10_match and print differences from input. */
3369         ofputil_match_to_ofp10_match(&match, &match_out);
3370         print_differences("", match_expout.data, match_expout.size,
3371                           &match_out, sizeof match_out);
3372
3373         /* Normalize, then convert and compare again. */
3374         ofputil_normalize_match(&match);
3375         ofputil_match_to_ofp10_match(&match, &match_normal);
3376         print_differences("normal: ", &match_out, sizeof match_out,
3377                           &match_normal, sizeof match_normal);
3378         putchar('\n');
3379
3380         ofpbuf_uninit(&match_in);
3381         ofpbuf_uninit(&match_expout);
3382     }
3383     ds_destroy(&in);
3384     ds_destroy(&expout);
3385 }
3386
3387 /* "parse-ofp11-match": reads a series of ofp11_match specifications as hex
3388  * bytes from stdin, converts them to "struct match"es, prints them as strings
3389  * on stdout, and then converts them back to hex bytes and prints any
3390  * differences from the input. */
3391 static void
3392 ofctl_parse_ofp11_match(struct ovs_cmdl_context *ctx OVS_UNUSED)
3393 {
3394     struct ds in;
3395
3396     ds_init(&in);
3397     while (!ds_get_preprocessed_line(&in, stdin, NULL)) {
3398         struct ofpbuf match_in;
3399         struct ofp11_match match_out;
3400         struct match match;
3401         enum ofperr error;
3402
3403         /* Parse hex bytes. */
3404         ofpbuf_init(&match_in, 0);
3405         if (ofpbuf_put_hex(&match_in, ds_cstr(&in), NULL)[0] != '\0') {
3406             ovs_fatal(0, "Trailing garbage in hex data");
3407         }
3408         if (match_in.size != sizeof(struct ofp11_match)) {
3409             ovs_fatal(0, "Input is %"PRIu32" bytes, expected %"PRIuSIZE,
3410                       match_in.size, sizeof(struct ofp11_match));
3411         }
3412
3413         /* Convert to match. */
3414         error = ofputil_match_from_ofp11_match(match_in.data, &match);
3415         if (error) {
3416             printf("bad ofp11_match: %s\n\n", ofperr_get_name(error));
3417             ofpbuf_uninit(&match_in);
3418             continue;
3419         }
3420
3421         /* Print match. */
3422         match_print(&match);
3423
3424         /* Convert back to ofp11_match and print differences from input. */
3425         ofputil_match_to_ofp11_match(&match, &match_out);
3426
3427         print_differences("", match_in.data, match_in.size,
3428                           &match_out, sizeof match_out);
3429         putchar('\n');
3430
3431         ofpbuf_uninit(&match_in);
3432     }
3433     ds_destroy(&in);
3434 }
3435
3436 /* "parse-pcap PCAP": read packets from PCAP and print their flows. */
3437 static void
3438 ofctl_parse_pcap(struct ovs_cmdl_context *ctx)
3439 {
3440     FILE *pcap;
3441
3442     pcap = ovs_pcap_open(ctx->argv[1], "rb");
3443     if (!pcap) {
3444         ovs_fatal(errno, "%s: open failed", ctx->argv[1]);
3445     }
3446
3447     for (;;) {
3448         struct dp_packet *packet;
3449         struct flow flow;
3450         int error;
3451
3452         error = ovs_pcap_read(pcap, &packet, NULL);
3453         if (error == EOF) {
3454             break;
3455         } else if (error) {
3456             ovs_fatal(error, "%s: read failed", ctx->argv[1]);
3457         }
3458
3459         pkt_metadata_init(&packet->md, ODPP_NONE);
3460         flow_extract(packet, &flow);
3461         flow_print(stdout, &flow);
3462         putchar('\n');
3463         dp_packet_delete(packet);
3464     }
3465 }
3466
3467 /* "check-vlan VLAN_TCI VLAN_TCI_MASK": converts the specified vlan_tci and
3468  * mask values to and from various formats and prints the results. */
3469 static void
3470 ofctl_check_vlan(struct ovs_cmdl_context *ctx)
3471 {
3472     struct match match;
3473
3474     char *string_s;
3475     struct ofputil_flow_mod fm;
3476
3477     struct ofpbuf nxm;
3478     struct match nxm_match;
3479     int nxm_match_len;
3480     char *nxm_s;
3481
3482     struct ofp10_match of10_raw;
3483     struct match of10_match;
3484
3485     struct ofp11_match of11_raw;
3486     struct match of11_match;
3487
3488     enum ofperr error;
3489     char *error_s;
3490
3491     enum ofputil_protocol usable_protocols; /* Unused for now. */
3492
3493     match_init_catchall(&match);
3494     match.flow.vlan_tci = htons(strtoul(ctx->argv[1], NULL, 16));
3495     match.wc.masks.vlan_tci = htons(strtoul(ctx->argv[2], NULL, 16));
3496
3497     /* Convert to and from string. */
3498     string_s = match_to_string(&match, OFP_DEFAULT_PRIORITY);
3499     printf("%s -> ", string_s);
3500     fflush(stdout);
3501     error_s = parse_ofp_str(&fm, -1, string_s, &usable_protocols);
3502     if (error_s) {
3503         ovs_fatal(0, "%s", error_s);
3504     }
3505     printf("%04"PRIx16"/%04"PRIx16"\n",
3506            ntohs(fm.match.flow.vlan_tci),
3507            ntohs(fm.match.wc.masks.vlan_tci));
3508     free(string_s);
3509
3510     /* Convert to and from NXM. */
3511     ofpbuf_init(&nxm, 0);
3512     nxm_match_len = nx_put_match(&nxm, &match, htonll(0), htonll(0));
3513     nxm_s = nx_match_to_string(nxm.data, nxm_match_len);
3514     error = nx_pull_match(&nxm, nxm_match_len, &nxm_match, NULL, NULL);
3515     printf("NXM: %s -> ", nxm_s);
3516     if (error) {
3517         printf("%s\n", ofperr_to_string(error));
3518     } else {
3519         printf("%04"PRIx16"/%04"PRIx16"\n",
3520                ntohs(nxm_match.flow.vlan_tci),
3521                ntohs(nxm_match.wc.masks.vlan_tci));
3522     }
3523     free(nxm_s);
3524     ofpbuf_uninit(&nxm);
3525
3526     /* Convert to and from OXM. */
3527     ofpbuf_init(&nxm, 0);
3528     nxm_match_len = oxm_put_match(&nxm, &match, OFP12_VERSION);
3529     nxm_s = oxm_match_to_string(&nxm, nxm_match_len);
3530     error = oxm_pull_match(&nxm, &nxm_match);
3531     printf("OXM: %s -> ", nxm_s);
3532     if (error) {
3533         printf("%s\n", ofperr_to_string(error));
3534     } else {
3535         uint16_t vid = ntohs(nxm_match.flow.vlan_tci) &
3536             (VLAN_VID_MASK | VLAN_CFI);
3537         uint16_t mask = ntohs(nxm_match.wc.masks.vlan_tci) &
3538             (VLAN_VID_MASK | VLAN_CFI);
3539
3540         printf("%04"PRIx16"/%04"PRIx16",", vid, mask);
3541         if (vid && vlan_tci_to_pcp(nxm_match.wc.masks.vlan_tci)) {
3542             printf("%02"PRIx8"\n", vlan_tci_to_pcp(nxm_match.flow.vlan_tci));
3543         } else {
3544             printf("--\n");
3545         }
3546     }
3547     free(nxm_s);
3548     ofpbuf_uninit(&nxm);
3549
3550     /* Convert to and from OpenFlow 1.0. */
3551     ofputil_match_to_ofp10_match(&match, &of10_raw);
3552     ofputil_match_from_ofp10_match(&of10_raw, &of10_match);
3553     printf("OF1.0: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
3554            ntohs(of10_raw.dl_vlan),
3555            (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN)) != 0,
3556            of10_raw.dl_vlan_pcp,
3557            (of10_raw.wildcards & htonl(OFPFW10_DL_VLAN_PCP)) != 0,
3558            ntohs(of10_match.flow.vlan_tci),
3559            ntohs(of10_match.wc.masks.vlan_tci));
3560
3561     /* Convert to and from OpenFlow 1.1. */
3562     ofputil_match_to_ofp11_match(&match, &of11_raw);
3563     ofputil_match_from_ofp11_match(&of11_raw, &of11_match);
3564     printf("OF1.1: %04"PRIx16"/%d,%02"PRIx8"/%d -> %04"PRIx16"/%04"PRIx16"\n",
3565            ntohs(of11_raw.dl_vlan),
3566            (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN)) != 0,
3567            of11_raw.dl_vlan_pcp,
3568            (of11_raw.wildcards & htonl(OFPFW11_DL_VLAN_PCP)) != 0,
3569            ntohs(of11_match.flow.vlan_tci),
3570            ntohs(of11_match.wc.masks.vlan_tci));
3571 }
3572
3573 /* "print-error ENUM": Prints the type and code of ENUM for every OpenFlow
3574  * version. */
3575 static void
3576 ofctl_print_error(struct ovs_cmdl_context *ctx)
3577 {
3578     enum ofperr error;
3579     int version;
3580
3581     error = ofperr_from_name(ctx->argv[1]);
3582     if (!error) {
3583         ovs_fatal(0, "unknown error \"%s\"", ctx->argv[1]);
3584     }
3585
3586     for (version = 0; version <= UINT8_MAX; version++) {
3587         const char *name = ofperr_domain_get_name(version);
3588         if (name) {
3589             int vendor = ofperr_get_vendor(error, version);
3590             int type = ofperr_get_type(error, version);
3591             int code = ofperr_get_code(error, version);
3592
3593             if (vendor != -1 || type != -1 || code != -1) {
3594                 printf("%s: vendor %#x, type %d, code %d\n",
3595                        name, vendor, type, code);
3596             }
3597         }
3598     }
3599 }
3600
3601 /* "encode-error-reply ENUM REQUEST": Encodes an error reply to REQUEST for the
3602  * error named ENUM and prints the error reply in hex. */
3603 static void
3604 ofctl_encode_error_reply(struct ovs_cmdl_context *ctx)
3605 {
3606     const struct ofp_header *oh;
3607     struct ofpbuf request, *reply;
3608     enum ofperr error;
3609
3610     error = ofperr_from_name(ctx->argv[1]);
3611     if (!error) {
3612         ovs_fatal(0, "unknown error \"%s\"", ctx->argv[1]);
3613     }
3614
3615     ofpbuf_init(&request, 0);
3616     if (ofpbuf_put_hex(&request, ctx->argv[2], NULL)[0] != '\0') {
3617         ovs_fatal(0, "Trailing garbage in hex data");
3618     }
3619     if (request.size < sizeof(struct ofp_header)) {
3620         ovs_fatal(0, "Request too short");
3621     }
3622
3623     oh = request.data;
3624     if (request.size != ntohs(oh->length)) {
3625         ovs_fatal(0, "Request size inconsistent");
3626     }
3627
3628     reply = ofperr_encode_reply(error, request.data);
3629     ofpbuf_uninit(&request);
3630
3631     ovs_hex_dump(stdout, reply->data, reply->size, 0, false);
3632     ofpbuf_delete(reply);
3633 }
3634
3635 /* "ofp-print HEXSTRING [VERBOSITY]": Converts the hex digits in HEXSTRING into
3636  * binary data, interpreting them as an OpenFlow message, and prints the
3637  * OpenFlow message on stdout, at VERBOSITY (level 2 by default).
3638  *
3639  * Alternative usage: "ofp-print [VERBOSITY] - < HEXSTRING_FILE", where
3640  * HEXSTRING_FILE contains the HEXSTRING. */
3641 static void
3642 ofctl_ofp_print(struct ovs_cmdl_context *ctx)
3643 {
3644     struct ofpbuf packet;
3645     char *buffer;
3646     int verbosity = 2;
3647     struct ds line;
3648
3649     ds_init(&line);
3650
3651     if (!strcmp(ctx->argv[ctx->argc-1], "-")) {
3652         if (ds_get_line(&line, stdin)) {
3653            VLOG_FATAL("Failed to read stdin");
3654         }
3655
3656         buffer = line.string;
3657         verbosity = ctx->argc > 2 ? atoi(ctx->argv[1]) : verbosity;
3658     } else if (ctx->argc > 2) {
3659         buffer = ctx->argv[1];
3660         verbosity = atoi(ctx->argv[2]);
3661     } else {
3662         buffer = ctx->argv[1];
3663     }
3664
3665     ofpbuf_init(&packet, strlen(buffer) / 2);
3666     if (ofpbuf_put_hex(&packet, buffer, NULL)[0] != '\0') {
3667         ovs_fatal(0, "trailing garbage following hex bytes");
3668     }
3669     ofp_print(stdout, packet.data, packet.size, verbosity);
3670     ofpbuf_uninit(&packet);
3671     ds_destroy(&line);
3672 }
3673
3674 /* "encode-hello BITMAP...": Encodes each BITMAP as an OpenFlow hello message
3675  * and dumps each message in hex.  */
3676 static void
3677 ofctl_encode_hello(struct ovs_cmdl_context *ctx)
3678 {
3679     uint32_t bitmap = strtol(ctx->argv[1], NULL, 0);
3680     struct ofpbuf *hello;
3681
3682     hello = ofputil_encode_hello(bitmap);
3683     ovs_hex_dump(stdout, hello->data, hello->size, 0, false);
3684     ofp_print(stdout, hello->data, hello->size, verbosity);
3685     ofpbuf_delete(hello);
3686 }
3687
3688 static const struct ovs_cmdl_command all_commands[] = {
3689     { "show", "switch",
3690       1, 1, ofctl_show },
3691     { "monitor", "switch [misslen] [invalid_ttl] [watch:[...]]",
3692       1, 3, ofctl_monitor },
3693     { "snoop", "switch",
3694       1, 1, ofctl_snoop },
3695     { "dump-desc", "switch",
3696       1, 1, ofctl_dump_desc },
3697     { "dump-tables", "switch",
3698       1, 1, ofctl_dump_tables },
3699     { "dump-table-features", "switch",
3700       1, 1, ofctl_dump_table_features },
3701     { "dump-table-desc", "switch",
3702       1, 1, ofctl_dump_table_desc },
3703     { "dump-flows", "switch",
3704       1, 2, ofctl_dump_flows },
3705     { "dump-aggregate", "switch",
3706       1, 2, ofctl_dump_aggregate },
3707     { "queue-stats", "switch [port [queue]]",
3708       1, 3, ofctl_queue_stats },
3709     { "queue-get-config", "switch port",
3710       2, 2, ofctl_queue_get_config },
3711     { "add-flow", "switch flow",
3712       2, 2, ofctl_add_flow },
3713     { "add-flows", "switch file",
3714       2, 2, ofctl_add_flows },
3715     { "mod-flows", "switch flow",
3716       2, 2, ofctl_mod_flows },
3717     { "del-flows", "switch [flow]",
3718       1, 2, ofctl_del_flows },
3719     { "replace-flows", "switch file",
3720       2, 2, ofctl_replace_flows },
3721     { "diff-flows", "source1 source2",
3722       2, 2, ofctl_diff_flows },
3723     { "add-meter", "switch meter",
3724       2, 2, ofctl_add_meter },
3725     { "mod-meter", "switch meter",
3726       2, 2, ofctl_mod_meter },
3727     { "del-meter", "switch meter",
3728       2, 2, ofctl_del_meters },
3729     { "del-meters", "switch",
3730       1, 1, ofctl_del_meters },
3731     { "dump-meter", "switch meter",
3732       2, 2, ofctl_dump_meters },
3733     { "dump-meters", "switch",
3734       1, 1, ofctl_dump_meters },
3735     { "meter-stats", "switch [meter]",
3736       1, 2, ofctl_meter_stats },
3737     { "meter-features", "switch",
3738       1, 1, ofctl_meter_features },
3739     { "packet-out", "switch in_port actions packet...",
3740       4, INT_MAX, ofctl_packet_out },
3741     { "dump-ports", "switch [port]",
3742       1, 2, ofctl_dump_ports },
3743     { "dump-ports-desc", "switch [port]",
3744       1, 2, ofctl_dump_ports_desc },
3745     { "mod-port", "switch iface act",
3746       3, 3, ofctl_mod_port },
3747     { "mod-table", "switch mod",
3748       3, 3, ofctl_mod_table },
3749     { "get-frags", "switch",
3750       1, 1, ofctl_get_frags },
3751     { "set-frags", "switch frag_mode",
3752       2, 2, ofctl_set_frags },
3753     { "probe", "target",
3754       1, 1, ofctl_probe },
3755     { "ping", "target [n]",
3756       1, 2, ofctl_ping },
3757     { "benchmark", "target n count",
3758       3, 3, ofctl_benchmark },
3759
3760     { "ofp-parse", "file",
3761       1, 1, ofctl_ofp_parse },
3762     { "ofp-parse-pcap", "pcap",
3763       1, INT_MAX, ofctl_ofp_parse_pcap },
3764
3765     { "add-group", "switch group",
3766       1, 2, ofctl_add_group },
3767     { "add-groups", "switch file",
3768       1, 2, ofctl_add_groups },
3769     { "mod-group", "switch group",
3770       1, 2, ofctl_mod_group },
3771     { "del-groups", "switch [group]",
3772       1, 2, ofctl_del_groups },
3773     { "insert-buckets", "switch [group]",
3774       1, 2, ofctl_insert_bucket },
3775     { "remove-buckets", "switch [group]",
3776       1, 2, ofctl_remove_bucket },
3777     { "dump-groups", "switch [group]",
3778       1, 2, ofctl_dump_group_desc },
3779     { "dump-group-stats", "switch [group]",
3780       1, 2, ofctl_dump_group_stats },
3781     { "dump-group-features", "switch",
3782       1, 1, ofctl_dump_group_features },
3783     { "add-geneve-map", "switch map",
3784       2, 2, ofctl_add_geneve_map },
3785     { "del-geneve-map", "switch [map]",
3786       1, 2, ofctl_del_geneve_map },
3787     { "dump-geneve-map", "switch",
3788       1, 1, ofctl_dump_geneve_map },
3789     { "help", NULL, 0, INT_MAX, ofctl_help },
3790     { "list-commands", NULL, 0, INT_MAX, ofctl_list_commands },
3791
3792     /* Undocumented commands for testing. */
3793     { "parse-flow", NULL, 1, 1, ofctl_parse_flow },
3794     { "parse-flows", NULL, 1, 1, ofctl_parse_flows },
3795     { "parse-nx-match", NULL, 0, 0, ofctl_parse_nxm },
3796     { "parse-nxm", NULL, 0, 0, ofctl_parse_nxm },
3797     { "parse-oxm", NULL, 1, 1, ofctl_parse_oxm },
3798     { "parse-actions", NULL, 1, 1, ofctl_parse_actions },
3799     { "parse-instructions", NULL, 1, 1, ofctl_parse_instructions },
3800     { "parse-ofp10-match", NULL, 0, 0, ofctl_parse_ofp10_match },
3801     { "parse-ofp11-match", NULL, 0, 0, ofctl_parse_ofp11_match },
3802     { "parse-pcap", NULL, 1, 1, ofctl_parse_pcap },
3803     { "check-vlan", NULL, 2, 2, ofctl_check_vlan },
3804     { "print-error", NULL, 1, 1, ofctl_print_error },
3805     { "encode-error-reply", NULL, 2, 2, ofctl_encode_error_reply },
3806     { "ofp-print", NULL, 1, 2, ofctl_ofp_print },
3807     { "encode-hello", NULL, 1, 1, ofctl_encode_hello },
3808
3809     { NULL, NULL, 0, 0, NULL },
3810 };
3811
3812 static const struct ovs_cmdl_command *get_all_commands(void)
3813 {
3814     return all_commands;
3815 }