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