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