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