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