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