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