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