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