Add "probe" command to dpctl.
[sliver-openvswitch.git] / utilities / dpctl.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <errno.h>
35 #include <getopt.h>
36 #include <inttypes.h>
37 #include <netinet/in.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <sys/time.h>
43
44 #include "command-line.h"
45 #include "compiler.h"
46 #include "buffer.h"
47 #include "dpif.h"
48 #ifdef HAVE_NETLINK
49 #include "netlink.h"
50 #include "openflow-netlink.h"
51 #endif
52 #include "util.h"
53 #include "socket-util.h"
54 #include "openflow.h"
55 #include "ofp-print.h"
56 #include "random.h"
57 #include "signal.h"
58 #include "vconn.h"
59 #include "vconn-ssl.h"
60
61 #include "vlog.h"
62 #define THIS_MODULE VLM_dpctl
63
64 #define DEFAULT_MAX_IDLE 60
65 #define MAX_ADD_ACTS 5
66
67 static const char* ifconfigbin = "/sbin/ifconfig";
68
69 struct command {
70     const char *name;
71     int min_args;
72     int max_args;
73     void (*handler)(int argc, char *argv[]);
74 };
75
76 static struct command all_commands[];
77
78 static void usage(void) NO_RETURN;
79 static void parse_options(int argc, char *argv[]);
80
81 int main(int argc, char *argv[])
82 {
83     struct command *p;
84
85     set_program_name(argv[0]);
86     vlog_init();
87     parse_options(argc, argv);
88
89     argc -= optind;
90     argv += optind;
91     if (argc < 1)
92         fatal(0, "missing command name; use --help for help");
93
94     for (p = all_commands; p->name != NULL; p++) {
95         if (!strcmp(p->name, argv[0])) {
96             int n_arg = argc - 1;
97             if (n_arg < p->min_args)
98                 fatal(0, "'%s' command requires at least %d arguments",
99                       p->name, p->min_args);
100             else if (n_arg > p->max_args)
101                 fatal(0, "'%s' command takes at most %d arguments",
102                       p->name, p->max_args);
103             else {
104                 p->handler(argc, argv);
105                 exit(0);
106             }
107         }
108     }
109     fatal(0, "unknown command '%s'; use --help for help", argv[0]);
110
111     return 0;
112 }
113
114 static void
115 parse_options(int argc, char *argv[])
116 {
117     static struct option long_options[] = {
118         {"timeout", required_argument, 0, 't'},
119         {"verbose", optional_argument, 0, 'v'},
120         {"help", no_argument, 0, 'h'},
121         {"version", no_argument, 0, 'V'},
122         VCONN_SSL_LONG_OPTIONS
123         {0, 0, 0, 0},
124     };
125     char *short_options = long_options_to_short_options(long_options);
126
127     for (;;) {
128         unsigned long int timeout;
129         int indexptr;
130         int c;
131
132         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
133         if (c == -1) {
134             break;
135         }
136
137         switch (c) {
138         case 't':
139             timeout = strtoul(optarg, NULL, 10);
140             if (timeout <= 0) {
141                 fatal(0, "value %s on -t or --timeout is not at least 1",
142                       optarg);
143             } else if (timeout < UINT_MAX) {
144                 /* Add 1 because historical implementations allow an alarm to
145                  * occur up to a second early. */
146                 alarm(timeout + 1);
147             } else {
148                 alarm(UINT_MAX);
149             }
150             signal(SIGALRM, SIG_DFL);
151             break;
152
153         case 'h':
154             usage();
155
156         case 'V':
157             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
158             exit(EXIT_SUCCESS);
159
160         case 'v':
161             vlog_set_verbosity(optarg);
162             break;
163
164         VCONN_SSL_OPTION_HANDLERS
165
166         case '?':
167             exit(EXIT_FAILURE);
168
169         default:
170             abort();
171         }
172     }
173     free(short_options);
174 }
175
176 static void
177 usage(void)
178 {
179     printf("%s: OpenFlow switch management utility\n"
180            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
181 #ifdef HAVE_NETLINK
182            "\nFor local datapaths only:\n"
183            "  adddp nl:DP_ID              add a new local datapath DP_ID\n"
184            "  deldp nl:DP_ID              delete local datapath DP_ID\n"
185            "  addif nl:DP_ID IFACE        add IFACE as a port on DP_ID\n"
186            "  delif nl:DP_ID IFACE        delete IFACE as a port on DP_ID\n"
187            "  monitor nl:DP_ID            print packets received\n"
188 #endif
189            "\nFor local datapaths and remote switches:\n"
190            "  show SWITCH                 show information\n"
191            "  dump-tables SWITCH          print table stats\n"
192            "  dump-ports SWITCH           print port statistics\n"
193            "  dump-flows SWITCH           print all flow entries\n"
194            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
195            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
196            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
197            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
198            "  add-flows SWITCH FILE       add flows from FILE\n"
199            "  del-flows SWITCH FLOW       delete matching FLOWs\n"
200            "\nFor local datapaths, remote switches, and controllers:\n"
201            "  probe VCONN                 probe whether VCONN is up\n"
202            "  ping VCONN [N]              latency of N-byte echos\n"
203            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
204            "where each SWITCH is an active OpenFlow connection method.\n",
205            program_name, program_name);
206     vconn_usage(true, false);
207     printf("\nOptions:\n"
208            "  -t, --timeout=SECS          give up after SECS seconds\n"
209            "  -v, --verbose=MODULE:FACILITY:LEVEL  configure logging levels\n"
210            "  -v, --verbose               set maximum verbosity level\n"
211            "  -h, --help                  display this help message\n"
212            "  -V, --version               display version information\n");
213     exit(EXIT_SUCCESS);
214 }
215
216 static void run(int retval, const char *message, ...)
217     PRINTF_FORMAT(2, 3);
218
219 static void run(int retval, const char *message, ...)
220 {
221     if (retval) {
222         va_list args;
223
224         fprintf(stderr, "%s: ", program_name);
225         va_start(args, message);
226         vfprintf(stderr, message, args);
227         va_end(args);
228         if (retval == EOF) {
229             fputs(": unexpected end of file\n", stderr);
230         } else {
231             fprintf(stderr, ": %s\n", strerror(retval));
232         }
233
234         exit(EXIT_FAILURE);
235     }
236 }
237 \f
238 #ifdef HAVE_NETLINK
239 /* Netlink-only commands. */
240
241 static int  if_up(const char* intf)
242 {
243     char command[256];
244     snprintf(command, sizeof command, "%s %s up &> /dev/null",
245             ifconfigbin, intf);
246     return system(command);
247 }
248
249 static void open_nl_vconn(const char *name, bool subscribe, struct dpif *dpif)
250 {
251     if (strncmp(name, "nl:", 3)
252         || strlen(name) < 4
253         || name[strspn(name + 3, "0123456789") + 3]) {
254         fatal(0, "%s: argument is not of the form \"nl:DP_ID\"", name);
255     }
256     run(dpif_open(atoi(name + 3), subscribe, dpif), "opening datapath");
257 }
258
259 static void do_add_dp(int argc UNUSED, char *argv[])
260 {
261     struct dpif dp;
262     open_nl_vconn(argv[1], false, &dp);
263     run(dpif_add_dp(&dp), "add_dp");
264     dpif_close(&dp);
265 }
266
267 static void do_del_dp(int argc UNUSED, char *argv[])
268 {
269     struct dpif dp;
270     open_nl_vconn(argv[1], false, &dp);
271     run(dpif_del_dp(&dp), "del_dp");
272     dpif_close(&dp);
273 }
274
275 static void do_add_port(int argc UNUSED, char *argv[])
276 {
277     struct dpif dp;
278     if_up(argv[2]);
279     open_nl_vconn(argv[1], false, &dp);
280     run(dpif_add_port(&dp, argv[2]), "add_port");
281     dpif_close(&dp);
282 }
283
284 static void do_del_port(int argc UNUSED, char *argv[])
285 {
286     struct dpif dp;
287     open_nl_vconn(argv[1], false, &dp);
288     run(dpif_del_port(&dp, argv[2]), "del_port");
289     dpif_close(&dp);
290 }
291
292 static void do_monitor(int argc UNUSED, char *argv[])
293 {
294     struct dpif dp;
295     open_nl_vconn(argv[1], true, &dp);
296     for (;;) {
297         struct buffer *b;
298         run(dpif_recv_openflow(&dp, &b, true), "dpif_recv_openflow");
299         ofp_print(stderr, b->data, b->size, 2);
300         buffer_delete(b);
301     }
302 }
303 #endif /* HAVE_NETLINK */
304 \f
305 /* Generic commands. */
306
307 static void *
308 alloc_openflow_buffer(size_t openflow_len, uint8_t type,
309                       struct buffer **bufferp)
310 {
311         struct buffer *buffer;
312         struct ofp_header *oh;
313
314         buffer = *bufferp = buffer_new(openflow_len);
315         oh = buffer_put_uninit(buffer, openflow_len);
316     memset(oh, 0, openflow_len);
317         oh->version = OFP_VERSION;
318         oh->type = type;
319         oh->length = 0;
320         oh->xid = random_uint32();
321         return oh;
322 }
323
324 static void *
325 alloc_stats_request(size_t body_len, uint16_t type, struct buffer **bufferp)
326 {
327     struct ofp_stats_request *rq;
328     rq = alloc_openflow_buffer((offsetof(struct ofp_stats_request, body)
329                                 + body_len), OFPT_STATS_REQUEST, bufferp);
330     rq->type = htons(type);
331     rq->flags = htons(0);
332     return rq->body;
333 }
334
335 static void
336 send_openflow_buffer(struct vconn *vconn, struct buffer *buffer)
337 {
338     struct ofp_header *oh;
339
340     oh = buffer_at_assert(buffer, 0, sizeof *oh);
341     oh->length = htons(buffer->size);
342
343     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
344 }
345
346 static struct buffer *
347 transact_openflow(struct vconn *vconn, struct buffer *request)
348 {
349     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
350
351     send_openflow_buffer(vconn, request);
352     for (;;) {
353         uint32_t recv_xid;
354         struct buffer *reply;
355
356         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
357         recv_xid = ((struct ofp_header *) reply->data)->xid;
358         if (send_xid == recv_xid) {
359             return reply;
360         }
361
362         VLOG_DBG("received reply with xid %08"PRIx32" != expected %08"PRIx32,
363                  recv_xid, send_xid);
364         buffer_delete(reply);
365     }
366 }
367
368 static void
369 dump_transaction(const char *vconn_name, struct buffer *request)
370 {
371     struct vconn *vconn;
372     struct buffer *reply;
373
374     run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
375     reply = transact_openflow(vconn, request);
376     ofp_print(stdout, reply->data, reply->size, 1);
377     vconn_close(vconn);
378 }
379
380 static void
381 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
382 {
383     struct buffer *request;
384     alloc_openflow_buffer(sizeof(struct ofp_header), request_type, &request);
385     dump_transaction(vconn_name, request);
386 }
387
388 static void
389 dump_stats_transaction(const char *vconn_name, struct buffer *request)
390 {
391     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
392     struct vconn *vconn;
393     bool done = false;
394
395     run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
396     send_openflow_buffer(vconn, request);
397     while (!done) {
398         uint32_t recv_xid;
399         struct buffer *reply;
400
401         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
402         recv_xid = ((struct ofp_header *) reply->data)->xid;
403         if (send_xid == recv_xid) {
404             struct ofp_stats_reply *osr;
405
406             ofp_print(stdout, reply->data, reply->size, 1);
407
408             osr = buffer_at(reply, 0, sizeof *osr);
409             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
410         } else {
411             VLOG_DBG("received reply with xid %08"PRIx32" "
412                      "!= expected %08"PRIx32, recv_xid, send_xid);
413         }
414         buffer_delete(reply);
415     }
416     vconn_close(vconn);
417 }
418
419 static void
420 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
421 {
422     struct buffer *request;
423     alloc_stats_request(0, stats_type, &request);
424     dump_stats_transaction(vconn_name, request);
425 }
426
427 static void
428 do_show(int argc UNUSED, char *argv[])
429 {
430     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
431     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
432 }
433
434
435 static void
436 do_dump_tables(int argc, char *argv[])
437 {
438     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
439 }
440
441
442 static uint32_t
443 str_to_int(const char *str) 
444 {
445     uint32_t value;
446     if (sscanf(str, "%"SCNu32, &value) != 1) {
447         fatal(0, "invalid numeric format %s", str);
448     }
449     return value;
450 }
451
452 static void
453 str_to_mac(const char *str, uint8_t mac[6]) 
454 {
455     if (sscanf(str, "%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8,
456                &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
457         fatal(0, "invalid mac address %s", str);
458     }
459 }
460
461 static void
462 str_to_ip(const char *str, uint32_t *ip) 
463 {
464     struct in_addr in_addr;
465     int retval;
466
467     retval = lookup_ip(str, &in_addr);
468     if (retval) {
469         fatal(0, "%s: could not convert to IP address", str);
470     }
471     *ip = in_addr.s_addr;
472 }
473
474 static void
475 str_to_action(char *str, struct ofp_action *action, int *n_actions) 
476 {
477     uint16_t port;
478     int i;
479     int max_actions = *n_actions;
480     char *act, *arg;
481     char *saveptr = NULL;
482     
483     memset(action, 0, sizeof(*action) * max_actions);
484     for (i=0, act = strtok_r(str, ", \t\r\n", &saveptr); 
485          i<max_actions && act;
486          i++, act = strtok_r(NULL, ", \t\r\n", &saveptr)) 
487     {
488         port = OFPP_MAX;
489
490         /* Arguments are separated by colons */
491         arg = strchr(act, ':');
492         if (arg) {
493             *arg = '\0';
494             arg++;
495         } 
496
497         if (!strcasecmp(act, "mod_vlan")) {
498             action[i].type = htons(OFPAT_SET_DL_VLAN);
499
500             if (!strcasecmp(arg, "strip")) {
501                 action[i].arg.vlan_id = htons(OFP_VLAN_NONE);
502             } else {
503                 action[i].arg.vlan_id = htons(str_to_int(arg));
504             }
505         } else if (!strcasecmp(act, "output")) {
506             port = str_to_int(arg);
507         } else if (!strcasecmp(act, "TABLE")) {
508             port = OFPP_TABLE;
509         } else if (!strcasecmp(act, "NORMAL")) {
510             port = OFPP_NORMAL;
511         } else if (!strcasecmp(act, "FLOOD")) {
512             port = OFPP_FLOOD;
513         } else if (!strcasecmp(act, "ALL")) {
514             port = OFPP_ALL;
515         } else if (!strcasecmp(act, "CONTROLLER")) {
516             port = OFPP_CONTROLLER;
517             if (arg) {
518                 if (!strcasecmp(arg, "all")) {
519                     action[i].arg.output.max_len= htons(0);
520                 } else {
521                     action[i].arg.output.max_len= htons(str_to_int(arg));
522                 }
523             }
524         } else if (!strcasecmp(act, "LOCAL")) {
525             port = OFPP_LOCAL;
526         } else if (strspn(act, "0123456789") == strlen(act)) {
527             port = str_to_int(act);
528         } else {
529             fatal(0, "Unknown action: %s", act);
530         }
531
532         if (port != OFPP_MAX) {
533             action[i].type = htons(OFPAT_OUTPUT);
534             action[i].arg.output.port = htons(port);
535         }
536     }
537
538     *n_actions = i;
539 }
540
541 static void
542 str_to_flow(char *string, struct ofp_match *match, 
543         struct ofp_action *action, int *n_actions, uint8_t *table_idx, 
544         uint16_t *priority, uint16_t *max_idle)
545 {
546     struct field {
547         const char *name;
548         uint32_t wildcard;
549         enum { F_U8, F_U16, F_MAC, F_IP } type;
550         size_t offset;
551     };
552
553 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
554     static const struct field fields[] = { 
555         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port) },
556         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan) },
557         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src) },
558         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst) },
559         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type) },
560         { "nw_src", OFPFW_NW_SRC, F_IP, F_OFS(nw_src) },
561         { "nw_dst", OFPFW_NW_DST, F_IP, F_OFS(nw_dst) },
562         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto) },
563         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src) },
564         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst) },
565     };
566
567     char *name, *value;
568     uint32_t wildcards;
569     char *act_str;
570
571     if (table_idx) {
572         *table_idx = 0xff;
573     }
574     if (priority) {
575         *priority = OFP_DEFAULT_PRIORITY;
576     }
577     if (max_idle) {
578         *max_idle = DEFAULT_MAX_IDLE;
579     }
580     if (action) {
581         act_str = strstr(string, "action");
582         if (!act_str) {
583             fatal(0, "must specify an action");
584         }
585         *(act_str-1) = '\0';
586
587         act_str = strchr(act_str, '=');
588         if (!act_str) {
589             fatal(0, "must specify an action");
590         }
591
592         act_str++;
593
594         str_to_action(act_str, action, n_actions);
595     }
596     memset(match, 0, sizeof *match);
597     wildcards = OFPFW_ALL;
598     for (name = strtok(string, "="), value = strtok(NULL, ", \t\r\n");
599          name && value;
600          name = strtok(NULL, "="), value = strtok(NULL, ", \t\r\n"))
601     {
602         const struct field *f;
603         void *data;
604
605         if (table_idx && !strcmp(name, "table")) {
606             *table_idx = atoi(value);
607             continue;
608         }
609
610         if (priority && !strcmp(name, "priority")) {
611             *priority = atoi(value);
612             continue;
613         }
614
615         if (max_idle && !strcmp(name, "max_idle")) {
616             *max_idle = atoi(value);
617             continue;
618         }
619
620         for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
621             if (!strcmp(f->name, name)) {
622                 goto found;
623             }
624         }
625         fprintf(stderr, "%s: unknown field %s (fields are",
626                 program_name, name);
627         for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
628             if (f != fields) {
629                 putc(',', stderr);
630             }
631             fprintf(stderr, " %s", f->name);
632         }
633         fprintf(stderr, ")\n");
634         exit(1);
635
636     found:
637         data = (char *) match + f->offset;
638         if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
639             wildcards |= f->wildcard;
640         } else {
641             wildcards &= ~f->wildcard;
642             if (f->type == F_U8) {
643                 *(uint8_t *) data = str_to_int(value);
644             } else if (f->type == F_U16) {
645                 *(uint16_t *) data = htons(str_to_int(value));
646             } else if (f->type == F_MAC) {
647                 str_to_mac(value, data);
648             } else if (f->type == F_IP) {
649                 str_to_ip(value, data);
650             } else {
651                 NOT_REACHED();
652             }
653         }
654     }
655     if (name && !value) {
656         fatal(0, "field %s missing value", name);
657     }
658     match->wildcards = htons(wildcards);
659 }
660
661 static void do_dump_flows(int argc, char *argv[])
662 {
663     struct ofp_flow_stats_request *req;
664     struct buffer *request;
665
666     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
667     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0, 
668             &req->table_id, NULL, NULL);
669     memset(req->pad, 0, sizeof req->pad);
670
671     dump_stats_transaction(argv[1], request);
672 }
673
674 static void do_dump_aggregate(int argc, char *argv[])
675 {
676     struct ofp_aggregate_stats_request *req;
677     struct buffer *request;
678
679     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
680     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0,
681             &req->table_id, NULL, NULL);
682     memset(req->pad, 0, sizeof req->pad);
683
684     dump_stats_transaction(argv[1], request);
685 }
686
687 static void do_add_flow(int argc, char *argv[])
688 {
689     struct vconn *vconn;
690     struct buffer *buffer;
691     struct ofp_flow_mod *ofm;
692     uint16_t priority, max_idle;
693     size_t size;
694     int n_actions = MAX_ADD_ACTS;
695
696     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
697
698     /* Parse and send. */
699     size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
700     ofm = alloc_openflow_buffer(size, OFPT_FLOW_MOD, &buffer);
701     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &n_actions, 
702             NULL, &priority, &max_idle);
703     ofm->command = htons(OFPFC_ADD);
704     ofm->max_idle = htons(max_idle);
705     ofm->buffer_id = htonl(UINT32_MAX);
706     ofm->priority = htons(priority);
707     ofm->reserved = htonl(0);
708
709     /* xxx Should we use the buffer library? */
710     buffer->size -= (MAX_ADD_ACTS - n_actions) * sizeof ofm->actions[0];
711
712     send_openflow_buffer(vconn, buffer);
713     vconn_close(vconn);
714 }
715
716 static void do_add_flows(int argc, char *argv[])
717 {
718     struct vconn *vconn;
719
720     FILE *file;
721     char line[1024];
722
723     file = fopen(argv[2], "r");
724     if (file == NULL) {
725         fatal(errno, "%s: open", argv[2]);
726     }
727
728     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
729     while (fgets(line, sizeof line, file)) {
730         struct buffer *buffer;
731         struct ofp_flow_mod *ofm;
732         uint16_t priority, max_idle;
733         size_t size;
734         int n_actions = MAX_ADD_ACTS;
735
736         char *comment;
737
738         /* Delete comments. */
739         comment = strchr(line, '#');
740         if (comment) {
741             *comment = '\0';
742         }
743
744         /* Drop empty lines. */
745         if (line[strspn(line, " \t\n")] == '\0') {
746             continue;
747         }
748
749         /* Parse and send. */
750         size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
751         ofm = alloc_openflow_buffer(size, OFPT_FLOW_MOD, &buffer);
752         str_to_flow(line, &ofm->match, &ofm->actions[0], &n_actions, 
753                 NULL, &priority, &max_idle);
754         ofm->command = htons(OFPFC_ADD);
755         ofm->max_idle = htons(max_idle);
756         ofm->buffer_id = htonl(UINT32_MAX);
757         ofm->priority = htons(priority);
758         ofm->reserved = htonl(0);
759
760         /* xxx Should we use the buffer library? */
761         buffer->size -= (MAX_ADD_ACTS - n_actions) * sizeof ofm->actions[0];
762
763         send_openflow_buffer(vconn, buffer);
764     }
765     vconn_close(vconn);
766     fclose(file);
767 }
768
769 static void do_del_flows(int argc, char *argv[])
770 {
771     struct vconn *vconn;
772     uint16_t priority;
773
774     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
775     struct buffer *buffer;
776     struct ofp_flow_mod *ofm;
777     size_t size;
778
779
780     /* Parse and send. */
781     size = sizeof *ofm;
782     ofm = alloc_openflow_buffer(size, OFPT_FLOW_MOD, &buffer);
783     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, 0, NULL, 
784             &priority, NULL);
785     ofm->command = htons(OFPFC_DELETE);
786     ofm->max_idle = htons(0);
787     ofm->buffer_id = htonl(UINT32_MAX);
788     ofm->priority = htons(priority);
789     ofm->reserved = htonl(0);
790
791     send_openflow_buffer(vconn, buffer);
792
793     vconn_close(vconn);
794 }
795
796 static void
797 do_dump_ports(int argc, char *argv[])
798 {
799     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
800 }
801
802 static void
803 do_probe(int argc, char *argv[])
804 {
805     struct buffer *request;
806     struct vconn *vconn;
807     struct buffer *reply;
808
809     alloc_openflow_buffer(sizeof(struct ofp_header), OFPT_ECHO_REQUEST,
810                           &request);
811     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
812     reply = transact_openflow(vconn, request);
813     if (reply->size != request->size) {
814         fatal(0, "reply does not match request");
815     }
816     buffer_delete(reply);
817     vconn_close(vconn);
818 }
819
820 static void
821 do_ping(int argc, char *argv[])
822 {
823     size_t max_payload = 65535 - sizeof(struct ofp_header);
824     unsigned int payload;
825     struct vconn *vconn;
826     int i;
827
828     payload = argc > 2 ? atoi(argv[2]) : 64;
829     if (payload > max_payload) {
830         fatal(0, "payload must be between 0 and %zu bytes", max_payload);
831     }
832
833     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
834     for (i = 0; i < 10; i++) {
835         struct timeval start, end;
836         struct buffer *request, *reply;
837         struct ofp_header *rq_hdr, *rpy_hdr;
838
839         rq_hdr = alloc_openflow_buffer(sizeof(struct ofp_header) + payload,
840                                     OFPT_ECHO_REQUEST, &request);
841         random_bytes(rq_hdr + 1, payload);
842
843         gettimeofday(&start, NULL);
844         reply = transact_openflow(vconn, buffer_clone(request));
845         gettimeofday(&end, NULL);
846
847         rpy_hdr = reply->data;
848         if (reply->size != request->size
849             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
850             || rpy_hdr->xid != rq_hdr->xid
851             || rpy_hdr->type != OFPT_ECHO_REPLY) {
852             printf("Reply does not match request.  Request:\n");
853             ofp_print(stdout, request, request->size, 2);
854             printf("Reply:\n");
855             ofp_print(stdout, reply, reply->size, 2);
856         }
857         printf("%d bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
858                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
859                    (1000*(double)(end.tv_sec - start.tv_sec))
860                    + (.001*(end.tv_usec - start.tv_usec)));
861         buffer_delete(request);
862         buffer_delete(reply);
863     }
864     vconn_close(vconn);
865 }
866
867 static void
868 do_benchmark(int argc, char *argv[])
869 {
870     size_t max_payload = 65535 - sizeof(struct ofp_header);
871     struct timeval start, end;
872     unsigned int payload_size, message_size;
873     struct vconn *vconn;
874     double duration;
875     int count;
876     int i;
877
878     payload_size = atoi(argv[2]);
879     if (payload_size > max_payload) {
880         fatal(0, "payload must be between 0 and %zu bytes", max_payload);
881     }
882     message_size = sizeof(struct ofp_header) + payload_size;
883
884     count = atoi(argv[3]);
885
886     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
887            count, message_size, count * message_size);
888
889     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
890     gettimeofday(&start, NULL);
891     for (i = 0; i < count; i++) {
892         struct buffer *request;
893         struct ofp_header *rq_hdr;
894
895         rq_hdr = alloc_openflow_buffer(message_size, OFPT_ECHO_REQUEST,
896                                        &request);
897         memset(rq_hdr + 1, 0, payload_size);
898         buffer_delete(transact_openflow(vconn, request));
899     }
900     gettimeofday(&end, NULL);
901     vconn_close(vconn);
902
903     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
904                 + (.001*(end.tv_usec - start.tv_usec)));
905     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
906            duration, count / (duration / 1000.0),
907            count * message_size / (duration / 1000.0));
908 }
909
910 static void do_help(int argc UNUSED, char *argv[] UNUSED)
911 {
912     usage();
913 }
914
915 static struct command all_commands[] = {
916 #ifdef HAVE_NETLINK
917     { "adddp", 1, 1, do_add_dp },
918     { "deldp", 1, 1, do_del_dp },
919     { "addif", 2, 2, do_add_port },
920     { "delif", 2, 2, do_del_port },
921 #endif
922
923     { "show", 1, 1, do_show },
924
925     { "help", 0, INT_MAX, do_help },
926     { "monitor", 1, 1, do_monitor },
927     { "dump-tables", 1, 1, do_dump_tables },
928     { "dump-flows", 1, 2, do_dump_flows },
929     { "dump-aggregate", 1, 2, do_dump_aggregate },
930     { "add-flow", 2, 2, do_add_flow },
931     { "add-flows", 2, 2, do_add_flows },
932     { "del-flows", 1, 2, do_del_flows },
933     { "dump-ports", 1, 1, do_dump_ports },
934     { "probe", 1, 1, do_probe },
935     { "ping", 1, 2, do_ping },
936     { "benchmark", 3, 3, do_benchmark },
937     { NULL, 0, 0, NULL },
938 };