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