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