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