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