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