ofproto: Implement Nicira Extended Match flexible flow match (NXM).
[sliver-openvswitch.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <errno.h>
19 #include <getopt.h>
20 #include <inttypes.h>
21 #include <net/if.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/stat.h>
27 #include <sys/time.h>
28
29 #include "byte-order.h"
30 #include "classifier.h"
31 #include "command-line.h"
32 #include "compiler.h"
33 #include "dirs.h"
34 #include "dpif.h"
35 #include "dynamic-string.h"
36 #include "netlink.h"
37 #include "nx-match.h"
38 #include "odp-util.h"
39 #include "ofp-parse.h"
40 #include "ofp-print.h"
41 #include "ofp-util.h"
42 #include "ofpbuf.h"
43 #include "openflow/nicira-ext.h"
44 #include "openflow/openflow.h"
45 #include "random.h"
46 #include "stream-ssl.h"
47 #include "timeval.h"
48 #include "util.h"
49 #include "vconn.h"
50 #include "vlog.h"
51
52 VLOG_DEFINE_THIS_MODULE(ofctl);
53
54
55 #define MOD_PORT_CMD_UP      "up"
56 #define MOD_PORT_CMD_DOWN    "down"
57 #define MOD_PORT_CMD_FLOOD   "flood"
58 #define MOD_PORT_CMD_NOFLOOD "noflood"
59
60 /* Use strict matching for flow mod commands? */
61 static bool strict;
62
63 static const struct command all_commands[];
64
65 static void usage(void) NO_RETURN;
66 static void parse_options(int argc, char *argv[]);
67
68 int
69 main(int argc, char *argv[])
70 {
71     set_program_name(argv[0]);
72     parse_options(argc, argv);
73     signal(SIGPIPE, SIG_IGN);
74     run_command(argc - optind, argv + optind, all_commands);
75     return 0;
76 }
77
78 static void
79 parse_options(int argc, char *argv[])
80 {
81     enum {
82         OPT_STRICT = UCHAR_MAX + 1,
83         VLOG_OPTION_ENUMS
84     };
85     static struct option long_options[] = {
86         {"timeout", required_argument, 0, 't'},
87         {"strict", no_argument, 0, OPT_STRICT},
88         {"help", no_argument, 0, 'h'},
89         {"version", no_argument, 0, 'V'},
90         VLOG_LONG_OPTIONS,
91         STREAM_SSL_LONG_OPTIONS
92         {0, 0, 0, 0},
93     };
94     char *short_options = long_options_to_short_options(long_options);
95
96     for (;;) {
97         unsigned long int timeout;
98         int c;
99
100         c = getopt_long(argc, argv, short_options, long_options, NULL);
101         if (c == -1) {
102             break;
103         }
104
105         switch (c) {
106         case 't':
107             timeout = strtoul(optarg, NULL, 10);
108             if (timeout <= 0) {
109                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
110                           optarg);
111             } else {
112                 time_alarm(timeout);
113             }
114             break;
115
116         case 'h':
117             usage();
118
119         case 'V':
120             OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
121             exit(EXIT_SUCCESS);
122
123         case OPT_STRICT:
124             strict = true;
125             break;
126
127         VLOG_OPTION_HANDLERS
128         STREAM_SSL_OPTION_HANDLERS
129
130         case '?':
131             exit(EXIT_FAILURE);
132
133         default:
134             abort();
135         }
136     }
137     free(short_options);
138 }
139
140 static void
141 usage(void)
142 {
143     printf("%s: OpenFlow switch management utility\n"
144            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
145            "\nFor OpenFlow switches:\n"
146            "  show SWITCH                 show OpenFlow information\n"
147            "  status SWITCH [KEY]         report statistics (about KEY)\n"
148            "  dump-desc SWITCH            print switch description\n"
149            "  dump-tables SWITCH          print table stats\n"
150            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
151            "  dump-ports SWITCH [PORT]    print port statistics\n"
152            "  dump-flows SWITCH           print all flow entries\n"
153            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
154            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
155            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
156            "  queue-stats SWITCH [PORT [QUEUE]]  dump queue stats\n"
157            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
158            "  add-flows SWITCH FILE       add flows from FILE\n"
159            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
160            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
161            "  monitor SWITCH [MISSLEN]    print packets received from SWITCH\n"
162            "\nFor OpenFlow switches and controllers:\n"
163            "  probe VCONN                 probe whether VCONN is up\n"
164            "  ping VCONN [N]              latency of N-byte echos\n"
165            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
166            "where each SWITCH is an active OpenFlow connection method.\n",
167            program_name, program_name);
168     vconn_usage(true, false, false);
169     vlog_usage();
170     printf("\nOther options:\n"
171            "  --strict                    use strict match for flow commands\n"
172            "  -t, --timeout=SECS          give up after SECS seconds\n"
173            "  -h, --help                  display this help message\n"
174            "  -V, --version               display version information\n");
175     exit(EXIT_SUCCESS);
176 }
177
178 static void run(int retval, const char *message, ...)
179     PRINTF_FORMAT(2, 3);
180
181 static void run(int retval, const char *message, ...)
182 {
183     if (retval) {
184         va_list args;
185
186         fprintf(stderr, "%s: ", program_name);
187         va_start(args, message);
188         vfprintf(stderr, message, args);
189         va_end(args);
190         if (retval == EOF) {
191             fputs(": unexpected end of file\n", stderr);
192         } else {
193             fprintf(stderr, ": %s\n", strerror(retval));
194         }
195
196         exit(EXIT_FAILURE);
197     }
198 }
199 \f
200 /* Generic commands. */
201
202 static void
203 open_vconn_socket(const char *name, struct vconn **vconnp)
204 {
205     char *vconn_name = xasprintf("unix:%s", name);
206     VLOG_INFO("connecting to %s", vconn_name);
207     run(vconn_open_block(vconn_name, OFP_VERSION, vconnp),
208         "connecting to %s", vconn_name);
209     free(vconn_name);
210 }
211
212 static void
213 open_vconn__(const char *name, const char *default_suffix,
214              struct vconn **vconnp)
215 {
216     struct dpif *dpif;
217     struct stat s;
218     char *bridge_path, *datapath_name, *datapath_type;
219
220     bridge_path = xasprintf("%s/%s.%s", ovs_rundir, name, default_suffix);
221     dp_parse_name(name, &datapath_name, &datapath_type);
222
223     if (strstr(name, ":")) {
224         run(vconn_open_block(name, OFP_VERSION, vconnp),
225             "connecting to %s", name);
226     } else if (!stat(name, &s) && S_ISSOCK(s.st_mode)) {
227         open_vconn_socket(name, vconnp);
228     } else if (!stat(bridge_path, &s) && S_ISSOCK(s.st_mode)) {
229         open_vconn_socket(bridge_path, vconnp);
230     } else if (!dpif_open(datapath_name, datapath_type, &dpif)) {
231         char dpif_name[IF_NAMESIZE + 1];
232         char *socket_name;
233
234         run(dpif_port_get_name(dpif, ODPP_LOCAL, dpif_name, sizeof dpif_name),
235             "obtaining name of %s", dpif_name);
236         dpif_close(dpif);
237         if (strcmp(dpif_name, name)) {
238             VLOG_INFO("datapath %s is named %s", name, dpif_name);
239         }
240
241         socket_name = xasprintf("%s/%s.%s",
242                                 ovs_rundir, dpif_name, default_suffix);
243         if (stat(socket_name, &s)) {
244             ovs_fatal(errno, "cannot connect to %s: stat failed on %s",
245                       name, socket_name);
246         } else if (!S_ISSOCK(s.st_mode)) {
247             ovs_fatal(0, "cannot connect to %s: %s is not a socket",
248                       name, socket_name);
249         }
250
251         open_vconn_socket(socket_name, vconnp);
252         free(socket_name);
253     } else {
254         ovs_fatal(0, "%s is not a valid connection method", name);
255     }
256
257     free(datapath_name);
258     free(datapath_type);
259     free(bridge_path);
260 }
261
262 static void
263 open_vconn(const char *name, struct vconn **vconnp)
264 {
265     return open_vconn__(name, "mgmt", vconnp);
266 }
267
268 static void *
269 alloc_stats_request(size_t body_len, uint16_t type, struct ofpbuf **bufferp)
270 {
271     struct ofp_stats_request *rq;
272     rq = make_openflow((offsetof(struct ofp_stats_request, body)
273                         + body_len), OFPT_STATS_REQUEST, bufferp);
274     rq->type = htons(type);
275     rq->flags = htons(0);
276     return rq->body;
277 }
278
279 static void
280 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
281 {
282     update_openflow_length(buffer);
283     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
284 }
285
286 static void
287 dump_transaction(const char *vconn_name, struct ofpbuf *request)
288 {
289     struct vconn *vconn;
290     struct ofpbuf *reply;
291
292     update_openflow_length(request);
293     open_vconn(vconn_name, &vconn);
294     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
295     ofp_print(stdout, reply->data, reply->size, 1);
296     vconn_close(vconn);
297 }
298
299 static void
300 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
301 {
302     struct ofpbuf *request;
303     make_openflow(sizeof(struct ofp_header), request_type, &request);
304     dump_transaction(vconn_name, request);
305 }
306
307 static void
308 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
309 {
310     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
311     struct vconn *vconn;
312     bool done = false;
313
314     open_vconn(vconn_name, &vconn);
315     send_openflow_buffer(vconn, request);
316     while (!done) {
317         uint32_t recv_xid;
318         struct ofpbuf *reply;
319
320         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
321         recv_xid = ((struct ofp_header *) reply->data)->xid;
322         if (send_xid == recv_xid) {
323             struct ofp_stats_reply *osr;
324
325             ofp_print(stdout, reply->data, reply->size, 1);
326
327             osr = ofpbuf_at(reply, 0, sizeof *osr);
328             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
329         } else {
330             VLOG_DBG("received reply with xid %08"PRIx32" "
331                      "!= expected %08"PRIx32, recv_xid, send_xid);
332         }
333         ofpbuf_delete(reply);
334     }
335     vconn_close(vconn);
336 }
337
338 static void
339 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
340 {
341     struct ofpbuf *request;
342     alloc_stats_request(0, stats_type, &request);
343     dump_stats_transaction(vconn_name, request);
344 }
345
346 static void
347 do_show(int argc OVS_UNUSED, char *argv[])
348 {
349     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
350     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
351 }
352
353 static void
354 do_status(int argc, char *argv[])
355 {
356     struct nicira_header *request, *reply;
357     struct vconn *vconn;
358     struct ofpbuf *b;
359
360     request = make_nxmsg(sizeof *request, NXT_STATUS_REQUEST, &b);
361     if (argc > 2) {
362         ofpbuf_put(b, argv[2], strlen(argv[2]));
363         update_openflow_length(b);
364     }
365     open_vconn(argv[1], &vconn);
366     run(vconn_transact(vconn, b, &b), "talking to %s", argv[1]);
367     vconn_close(vconn);
368
369     if (b->size < sizeof *reply) {
370         ovs_fatal(0, "short reply (%zu bytes)", b->size);
371     }
372     reply = b->data;
373     if (reply->header.type != OFPT_VENDOR
374         || reply->vendor != ntohl(NX_VENDOR_ID)
375         || reply->subtype != ntohl(NXT_STATUS_REPLY)) {
376         ofp_print(stderr, b->data, b->size, 2);
377         ovs_fatal(0, "bad reply");
378     }
379
380     fwrite(reply + 1, b->size - sizeof *reply, 1, stdout);
381 }
382
383 static void
384 do_dump_desc(int argc OVS_UNUSED, char *argv[])
385 {
386     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
387 }
388
389 static void
390 do_dump_tables(int argc OVS_UNUSED, char *argv[])
391 {
392     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
393 }
394
395 static uint16_t
396 str_to_port_no(const char *vconn_name, const char *str)
397 {
398     struct ofpbuf *request, *reply;
399     struct ofp_switch_features *osf;
400     struct vconn *vconn;
401     int n_ports;
402     int port_idx;
403     unsigned int port_no;
404
405
406     /* Check if the argument is a port index.  Otherwise, treat it as
407      * the port name. */
408     if (str_to_uint(str, 10, &port_no)) {
409         return port_no;
410     }
411
412     /* Send a "Features Request" to resolve the name into a number. */
413     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
414     open_vconn(vconn_name, &vconn);
415     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
416
417     osf = reply->data;
418     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
419
420     for (port_idx = 0; port_idx < n_ports; port_idx++) {
421         /* Check argument as an interface name */
422         if (!strncmp((char *)osf->ports[port_idx].name, str,
423                     sizeof osf->ports[0].name)) {
424             break;
425         }
426     }
427     if (port_idx == n_ports) {
428         ovs_fatal(0, "couldn't find monitored port: %s", str);
429     }
430
431     ofpbuf_delete(reply);
432     vconn_close(vconn);
433
434     return port_idx;
435 }
436
437 static void
438 do_dump_flows(int argc, char *argv[])
439 {
440     struct ofp_flow_stats_request *req;
441     uint16_t out_port;
442     struct ofpbuf *request;
443
444     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
445     parse_ofp_str(argc > 2 ? argv[2] : "", &req->match, NULL,
446                   &req->table_id, &out_port, NULL, NULL, NULL, NULL);
447     memset(&req->pad, 0, sizeof req->pad);
448     req->out_port = htons(out_port);
449
450     dump_stats_transaction(argv[1], request);
451 }
452
453 static void
454 do_dump_aggregate(int argc, char *argv[])
455 {
456     struct ofp_aggregate_stats_request *req;
457     struct ofpbuf *request;
458     uint16_t out_port;
459
460     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
461     parse_ofp_str(argc > 2 ? argv[2] : "", &req->match, NULL,
462                   &req->table_id, &out_port, NULL, NULL, NULL, NULL);
463     memset(&req->pad, 0, sizeof req->pad);
464     req->out_port = htons(out_port);
465
466     dump_stats_transaction(argv[1], request);
467 }
468
469 static void
470 do_queue_stats(int argc, char *argv[])
471 {
472     struct ofp_queue_stats_request *req;
473     struct ofpbuf *request;
474
475     req = alloc_stats_request(sizeof *req, OFPST_QUEUE, &request);
476
477     if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
478         req->port_no = htons(str_to_port_no(argv[1], argv[2]));
479     } else {
480         req->port_no = htons(OFPP_ALL);
481     }
482     if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
483         req->queue_id = htonl(atoi(argv[3]));
484     } else {
485         req->queue_id = htonl(OFPQ_ALL);
486     }
487
488     memset(req->pad, 0, sizeof req->pad);
489
490     dump_stats_transaction(argv[1], request);
491 }
492
493 static void
494 do_add_flow(int argc OVS_UNUSED, char *argv[])
495 {
496     struct vconn *vconn;
497     struct ofpbuf *buffer;
498     struct ofp_flow_mod *ofm;
499     uint16_t priority, idle_timeout, hard_timeout;
500     uint64_t cookie;
501     struct ofp_match match;
502
503     /* Parse and send.  parse_ofp_str() will expand and reallocate the
504      * data in 'buffer', so we can't keep pointers to across the
505      * parse_ofp_str() call. */
506     make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
507     parse_ofp_str(argv[2], &match, buffer,
508                   NULL, NULL, &priority, &idle_timeout, &hard_timeout,
509                   &cookie);
510     ofm = buffer->data;
511     ofm->match = match;
512     ofm->command = htons(OFPFC_ADD);
513     ofm->cookie = htonll(cookie);
514     ofm->idle_timeout = htons(idle_timeout);
515     ofm->hard_timeout = htons(hard_timeout);
516     ofm->buffer_id = htonl(UINT32_MAX);
517     ofm->priority = htons(priority);
518
519     open_vconn(argv[1], &vconn);
520     send_openflow_buffer(vconn, buffer);
521     vconn_close(vconn);
522 }
523
524 static void
525 do_add_flows(int argc OVS_UNUSED, char *argv[])
526 {
527     struct vconn *vconn;
528     struct ofpbuf *b;
529     FILE *file;
530
531     file = fopen(argv[2], "r");
532     if (file == NULL) {
533         ovs_fatal(errno, "%s: open", argv[2]);
534     }
535
536     open_vconn(argv[1], &vconn);
537     while ((b = parse_ofp_add_flow_file(file)) != NULL) {
538         send_openflow_buffer(vconn, b);
539     }
540     vconn_close(vconn);
541     fclose(file);
542 }
543
544 static void
545 do_mod_flows(int argc OVS_UNUSED, char *argv[])
546 {
547     uint16_t priority, idle_timeout, hard_timeout;
548     uint64_t cookie;
549     struct vconn *vconn;
550     struct ofpbuf *buffer;
551     struct ofp_flow_mod *ofm;
552     struct ofp_match match;
553
554     /* Parse and send.  parse_ofp_str() will expand and reallocate the
555      * data in 'buffer', so we can't keep pointers to across the
556      * parse_ofp_str() call. */
557     make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
558     parse_ofp_str(argv[2], &match, buffer,
559                   NULL, NULL, &priority, &idle_timeout, &hard_timeout,
560                   &cookie);
561     ofm = buffer->data;
562     ofm->match = match;
563     if (strict) {
564         ofm->command = htons(OFPFC_MODIFY_STRICT);
565     } else {
566         ofm->command = htons(OFPFC_MODIFY);
567     }
568     ofm->idle_timeout = htons(idle_timeout);
569     ofm->hard_timeout = htons(hard_timeout);
570     ofm->cookie = htonll(cookie);
571     ofm->buffer_id = htonl(UINT32_MAX);
572     ofm->priority = htons(priority);
573
574     open_vconn(argv[1], &vconn);
575     send_openflow_buffer(vconn, buffer);
576     vconn_close(vconn);
577 }
578
579 static void do_del_flows(int argc, char *argv[])
580 {
581     struct vconn *vconn;
582     uint16_t priority;
583     uint16_t out_port;
584     struct ofpbuf *buffer;
585     struct ofp_flow_mod *ofm;
586
587     /* Parse and send. */
588     ofm = make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
589     parse_ofp_str(argc > 2 ? argv[2] : "", &ofm->match, NULL, NULL,
590                   &out_port, &priority, NULL, NULL, NULL);
591     if (strict) {
592         ofm->command = htons(OFPFC_DELETE_STRICT);
593     } else {
594         ofm->command = htons(OFPFC_DELETE);
595     }
596     ofm->idle_timeout = htons(0);
597     ofm->hard_timeout = htons(0);
598     ofm->buffer_id = htonl(UINT32_MAX);
599     ofm->out_port = htons(out_port);
600     ofm->priority = htons(priority);
601
602     open_vconn(argv[1], &vconn);
603     send_openflow_buffer(vconn, buffer);
604     vconn_close(vconn);
605 }
606
607 static void
608 do_tun_cookie(int argc OVS_UNUSED, char *argv[])
609 {
610     struct nxt_tun_id_cookie *tun_id_cookie;
611     struct ofpbuf *buffer;
612     struct vconn *vconn;
613
614     tun_id_cookie = make_nxmsg(sizeof *tun_id_cookie, NXT_TUN_ID_FROM_COOKIE,
615                                &buffer);
616     tun_id_cookie->set = !strcmp(argv[2], "true");
617
618     open_vconn(argv[1], &vconn);
619     send_openflow_buffer(vconn, buffer);
620     vconn_close(vconn);
621 }
622
623 static void
624 monitor_vconn(struct vconn *vconn)
625 {
626     for (;;) {
627         struct ofpbuf *b;
628         run(vconn_recv_block(vconn, &b), "vconn_recv");
629         ofp_print(stderr, b->data, b->size, 2);
630         ofpbuf_delete(b);
631     }
632 }
633
634 static void
635 do_monitor(int argc, char *argv[])
636 {
637     struct vconn *vconn;
638
639     open_vconn(argv[1], &vconn);
640     if (argc > 2) {
641         int miss_send_len = atoi(argv[2]);
642         struct ofp_switch_config *osc;
643         struct ofpbuf *buf;
644
645         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &buf);
646         osc->miss_send_len = htons(miss_send_len);
647         send_openflow_buffer(vconn, buf);
648     }
649     monitor_vconn(vconn);
650 }
651
652 static void
653 do_snoop(int argc OVS_UNUSED, char *argv[])
654 {
655     struct vconn *vconn;
656
657     open_vconn__(argv[1], "snoop", &vconn);
658     monitor_vconn(vconn);
659 }
660
661 static void
662 do_dump_ports(int argc, char *argv[])
663 {
664     struct ofp_port_stats_request *req;
665     struct ofpbuf *request;
666     uint16_t port;
667
668     req = alloc_stats_request(sizeof *req, OFPST_PORT, &request);
669     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_NONE;
670     req->port_no = htons(port);
671     dump_stats_transaction(argv[1], request);
672 }
673
674 static void
675 do_probe(int argc OVS_UNUSED, char *argv[])
676 {
677     struct ofpbuf *request;
678     struct vconn *vconn;
679     struct ofpbuf *reply;
680
681     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
682     open_vconn(argv[1], &vconn);
683     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
684     if (reply->size != sizeof(struct ofp_header)) {
685         ovs_fatal(0, "reply does not match request");
686     }
687     ofpbuf_delete(reply);
688     vconn_close(vconn);
689 }
690
691 static void
692 do_mod_port(int argc OVS_UNUSED, char *argv[])
693 {
694     struct ofpbuf *request, *reply;
695     struct ofp_switch_features *osf;
696     struct ofp_port_mod *opm;
697     struct vconn *vconn;
698     char *endptr;
699     int n_ports;
700     int port_idx;
701     int port_no;
702
703
704     /* Check if the argument is a port index.  Otherwise, treat it as
705      * the port name. */
706     port_no = strtol(argv[2], &endptr, 10);
707     if (port_no == 0 && endptr == argv[2]) {
708         port_no = -1;
709     }
710
711     /* Send a "Features Request" to get the information we need in order
712      * to modify the port. */
713     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
714     open_vconn(argv[1], &vconn);
715     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
716
717     osf = reply->data;
718     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
719
720     for (port_idx = 0; port_idx < n_ports; port_idx++) {
721         if (port_no != -1) {
722             /* Check argument as a port index */
723             if (osf->ports[port_idx].port_no == htons(port_no)) {
724                 break;
725             }
726         } else {
727             /* Check argument as an interface name */
728             if (!strncmp((char *)osf->ports[port_idx].name, argv[2],
729                         sizeof osf->ports[0].name)) {
730                 break;
731             }
732
733         }
734     }
735     if (port_idx == n_ports) {
736         ovs_fatal(0, "couldn't find monitored port: %s", argv[2]);
737     }
738
739     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
740     opm->port_no = osf->ports[port_idx].port_no;
741     memcpy(opm->hw_addr, osf->ports[port_idx].hw_addr, sizeof opm->hw_addr);
742     opm->config = htonl(0);
743     opm->mask = htonl(0);
744     opm->advertise = htonl(0);
745
746     printf("modifying port: %s\n", osf->ports[port_idx].name);
747
748     if (!strncasecmp(argv[3], MOD_PORT_CMD_UP, sizeof MOD_PORT_CMD_UP)) {
749         opm->mask |= htonl(OFPPC_PORT_DOWN);
750     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_DOWN,
751                 sizeof MOD_PORT_CMD_DOWN)) {
752         opm->mask |= htonl(OFPPC_PORT_DOWN);
753         opm->config |= htonl(OFPPC_PORT_DOWN);
754     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_FLOOD,
755                 sizeof MOD_PORT_CMD_FLOOD)) {
756         opm->mask |= htonl(OFPPC_NO_FLOOD);
757     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_NOFLOOD,
758                 sizeof MOD_PORT_CMD_NOFLOOD)) {
759         opm->mask |= htonl(OFPPC_NO_FLOOD);
760         opm->config |= htonl(OFPPC_NO_FLOOD);
761     } else {
762         ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
763     }
764
765     send_openflow_buffer(vconn, request);
766
767     ofpbuf_delete(reply);
768     vconn_close(vconn);
769 }
770
771 static void
772 do_ping(int argc, char *argv[])
773 {
774     size_t max_payload = 65535 - sizeof(struct ofp_header);
775     unsigned int payload;
776     struct vconn *vconn;
777     int i;
778
779     payload = argc > 2 ? atoi(argv[2]) : 64;
780     if (payload > max_payload) {
781         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
782     }
783
784     open_vconn(argv[1], &vconn);
785     for (i = 0; i < 10; i++) {
786         struct timeval start, end;
787         struct ofpbuf *request, *reply;
788         struct ofp_header *rq_hdr, *rpy_hdr;
789
790         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
791                                OFPT_ECHO_REQUEST, &request);
792         random_bytes(rq_hdr + 1, payload);
793
794         gettimeofday(&start, NULL);
795         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
796         gettimeofday(&end, NULL);
797
798         rpy_hdr = reply->data;
799         if (reply->size != request->size
800             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
801             || rpy_hdr->xid != rq_hdr->xid
802             || rpy_hdr->type != OFPT_ECHO_REPLY) {
803             printf("Reply does not match request.  Request:\n");
804             ofp_print(stdout, request, request->size, 2);
805             printf("Reply:\n");
806             ofp_print(stdout, reply, reply->size, 2);
807         }
808         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
809                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
810                    (1000*(double)(end.tv_sec - start.tv_sec))
811                    + (.001*(end.tv_usec - start.tv_usec)));
812         ofpbuf_delete(request);
813         ofpbuf_delete(reply);
814     }
815     vconn_close(vconn);
816 }
817
818 static void
819 do_benchmark(int argc OVS_UNUSED, char *argv[])
820 {
821     size_t max_payload = 65535 - sizeof(struct ofp_header);
822     struct timeval start, end;
823     unsigned int payload_size, message_size;
824     struct vconn *vconn;
825     double duration;
826     int count;
827     int i;
828
829     payload_size = atoi(argv[2]);
830     if (payload_size > max_payload) {
831         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
832     }
833     message_size = sizeof(struct ofp_header) + payload_size;
834
835     count = atoi(argv[3]);
836
837     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
838            count, message_size, count * message_size);
839
840     open_vconn(argv[1], &vconn);
841     gettimeofday(&start, NULL);
842     for (i = 0; i < count; i++) {
843         struct ofpbuf *request, *reply;
844         struct ofp_header *rq_hdr;
845
846         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
847         memset(rq_hdr + 1, 0, payload_size);
848         run(vconn_transact(vconn, request, &reply), "transact");
849         ofpbuf_delete(reply);
850     }
851     gettimeofday(&end, NULL);
852     vconn_close(vconn);
853
854     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
855                 + (.001*(end.tv_usec - start.tv_usec)));
856     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
857            duration, count / (duration / 1000.0),
858            count * message_size / (duration / 1000.0));
859 }
860
861 static void
862 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
863 {
864     usage();
865 }
866 \f
867 /* Undocumented commands for unit testing. */
868
869 static void
870 do_parse_flows(int argc OVS_UNUSED, char *argv[])
871 {
872     struct ofpbuf *b;
873     FILE *file;
874
875     file = fopen(argv[1], "r");
876     if (file == NULL) {
877         ovs_fatal(errno, "%s: open", argv[2]);
878     }
879
880     while ((b = parse_ofp_add_flow_file(file)) != NULL) {
881         ofp_print(stdout, b->data, b->size, 0);
882         ofpbuf_delete(b);
883     }
884     fclose(file);
885 }
886
887 static void
888 do_parse_nx_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
889 {
890     struct ds in;
891
892     ds_init(&in);
893     while (!ds_get_line(&in, stdin)) {
894         struct ofpbuf nx_match;
895         struct cls_rule rule;
896         int match_len;
897         int error;
898         char *s;
899
900         /* Delete comments, skip blank lines. */
901         s = ds_cstr(&in);
902         if (*s == '#') {
903             puts(s);
904             continue;
905         }
906         if (strchr(s, '#')) {
907             *strchr(s, '#') = '\0';
908         }
909         if (s[strspn(s, " ")] == '\0') {
910             putchar('\n');
911             continue;
912         }
913
914         /* Convert string to nx_match. */
915         ofpbuf_init(&nx_match, 0);
916         match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
917
918         /* Convert nx_match to cls_rule. */
919         error = nx_pull_match(&nx_match, match_len, 0, &rule);
920         if (!error) {
921             char *out;
922
923             /* Convert cls_rule back to nx_match. */
924             ofpbuf_uninit(&nx_match);
925             ofpbuf_init(&nx_match, 0);
926             match_len = nx_put_match(&nx_match, &rule);
927
928             /* Convert nx_match to string. */
929             out = nx_match_to_string(nx_match.data, match_len);
930             puts(out);
931             free(out);
932         } else {
933             printf("nx_pull_match() returned error %x\n", error);
934         }
935
936         ofpbuf_uninit(&nx_match);
937     }
938     ds_destroy(&in);
939 }
940
941 static const struct command all_commands[] = {
942     { "show", 1, 1, do_show },
943     { "status", 1, 2, do_status },
944     { "monitor", 1, 2, do_monitor },
945     { "snoop", 1, 1, do_snoop },
946     { "dump-desc", 1, 1, do_dump_desc },
947     { "dump-tables", 1, 1, do_dump_tables },
948     { "dump-flows", 1, 2, do_dump_flows },
949     { "dump-aggregate", 1, 2, do_dump_aggregate },
950     { "queue-stats", 1, 3, do_queue_stats },
951     { "add-flow", 2, 2, do_add_flow },
952     { "add-flows", 2, 2, do_add_flows },
953     { "mod-flows", 2, 2, do_mod_flows },
954     { "del-flows", 1, 2, do_del_flows },
955     { "tun-cookie", 2, 2, do_tun_cookie },
956     { "dump-ports", 1, 2, do_dump_ports },
957     { "mod-port", 3, 3, do_mod_port },
958     { "probe", 1, 1, do_probe },
959     { "ping", 1, 2, do_ping },
960     { "benchmark", 3, 3, do_benchmark },
961     { "help", 0, INT_MAX, do_help },
962
963     /* Undocumented commands for testing. */
964     { "parse-flows", 1, 1, do_parse_flows },
965     { "parse-nx-match", 0, 0, do_parse_nx_match },
966
967     { NULL, 0, 0, NULL },
968 };